"use client";
import { useCallback, useMemo, useState } from "react";
import { create } from "@bufbuild/protobuf";
import { SubmitApprovalInputSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/io_pb";
import { useStigmer } from "../hooks.js";
import { toError } from "../internal/toError.js";
import { useKeyedSubmission } from "../internal/useKeyedSubmission.js";
/**
 * Behavior hook that wraps `agentExecution.submitApproval()` with
 * per-tool-call loading state and error management.
 *
 * Tracks submitting state per tool call ID (not a single boolean)
 * because batch approvals allow concurrent decisions on different
 * tool calls within the same execution.
 *
 * Platform builders who need full control over the approval UI use
 * this hook directly. Those who prefer drop-in components use
 * {@link ApprovalCard} which accepts the callback shape produced
 * by this hook.
 *
 * @example
 * ```tsx
 * const { submitApproval, submittingToolCallIds, error } = useSubmitApproval();
 *
 * await submitApproval(executionId, toolCallId, ApprovalAction.APPROVAL_ACTION_APPROVE);
 * ```
 */
export function useSubmitApproval() {
    const stigmer = useStigmer();
    // Per-gate in-flight + error state, keyed by tool-call id, lives in the
    // shared keyed-submission primitive. The scalar `error` below is a thin
    // mirror kept in lockstep for headless / ink consumers.
    const keyed = useKeyedSubmission();
    const [error, setError] = useState(null);
    const clearError = useCallback(() => {
        keyed.clearErrors();
        setError(null);
    }, [keyed.clearErrors]);
    const submitApproval = useCallback(async (executionId, toolCallId, action, comment) => {
        // Clear the scalar mirror at submit-start; `keyed.run` clears this gate's
        // keyed entry, so the map and `error` are updated together and never drift.
        setError(null);
        try {
            await keyed.run(toolCallId, async () => {
                await stigmer.agentExecution.submitApproval(create(SubmitApprovalInputSchema, {
                    agentExecutionId: executionId,
                    toolCallId,
                    action,
                    comment: comment ?? "",
                }));
            });
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
    }, [stigmer, keyed.run]);
    return useMemo(() => ({
        submitApproval,
        submittingToolCallIds: keyed.submittingKeys,
        errorsByToolCallId: keyed.errorsByKey,
        error,
        clearError,
    }), [submitApproval, keyed.submittingKeys, keyed.errorsByKey, error, clearError]);
}
//# sourceMappingURL=useSubmitApproval.js.map