"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { ApprovalAction } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
import { cn } from "@stigmer/theme";
import { resolveToolCategory, extractPrimaryArgFromPreview, } from "./tool-categories";
import { CATEGORY_ICON } from "./ToolCallItem";
import { ToolArgsView } from "./ToolArgsView";
/**
 * Renders a pending tool-call approval request with the same visual
 * structure as an expanded {@link ToolCallItem} in the history list.
 *
 * The compact header row matches the ToolCallItem layout:
 *   [CategoryIcon] Label  primaryArg  [⏳ waiting Xm]
 *
 * Arguments are rendered through the shared {@link ToolArgsView}
 * dispatch, ensuring pixel-level parity between the approval
 * preview and the post-execution detail view.
 *
 * Wrapped in `React.memo` — structural sharing (T04) preserves the
 * `PendingApproval` reference when unchanged, so approval cards
 * skip re-renders during unrelated stream updates.
 *
 * @example
 * ```tsx
 * <ApprovalCard
 *   pendingApproval={approval}
 *   onSubmit={(action) => submitApproval(executionId, approval.toolCallId, action)}
 *   isSubmitting={submittingIds.has(approval.toolCallId)}
 * />
 * ```
 */
export const ApprovalCard = memo(function ApprovalCard({ pendingApproval, onSubmit, isSubmitting = false, className, }) {
    const [activeAction, setActiveAction] = useState(null);
    const handleAction = useCallback((action) => {
        setActiveAction(action);
        onSubmit(action);
    }, [onSubmit]);
    useEffect(() => {
        if (!isSubmitting) {
            setActiveAction(null);
        }
    }, [isSubmitting]);
    const categoryInfo = resolveToolCategory(pendingApproval.toolName, pendingApproval.mcpServerSlug);
    const CategoryIcon = CATEGORY_ICON[categoryInfo.category];
    const primaryArg = useMemo(() => extractPrimaryArgFromPreview(pendingApproval.toolName, pendingApproval.argsPreview, pendingApproval.mcpServerSlug), [
        pendingApproval.toolName,
        pendingApproval.argsPreview,
        pendingApproval.mcpServerSlug,
    ]);
    const parsedArgs = useMemo(() => {
        if (!pendingApproval.argsPreview)
            return null;
        try {
            const parsed = JSON.parse(pendingApproval.argsPreview);
            if (typeof parsed === "object" && parsed !== null) {
                return parsed;
            }
            return null;
        }
        catch {
            return null;
        }
    }, [pendingApproval.argsPreview]);
    const borderClass = categoryInfo.category === "delete"
        ? "border-destructive/30 bg-destructive-subtle"
        : "border-warning/30 bg-warning/5";
    return (_jsxs("div", { role: "alert", "aria-label": `Approval required for ${pendingApproval.toolName}`, className: cn("rounded-lg border", borderClass, className), children: [_jsxs("div", { className: cn("flex items-center gap-2 px-2.5 py-1.5 text-xs", "border-b border-border-muted"), children: [_jsx("span", { className: "shrink-0 text-warning", "aria-hidden": "true", children: _jsx(CategoryIcon, {}) }), _jsxs("span", { className: "min-w-0 flex-1 flex items-baseline gap-1.5 overflow-hidden", children: [_jsx("span", { className: "shrink-0 font-medium text-foreground", children: categoryInfo.label }), primaryArg && (_jsx("span", { className: "min-w-0 truncate font-mono text-muted-foreground", children: primaryArg }))] }), pendingApproval.fromSubAgent && pendingApproval.subAgentName && (_jsxs("span", { className: "shrink-0 rounded bg-muted px-1 py-0.5 font-mono text-muted-foreground", children: ["via ", pendingApproval.subAgentSubject || pendingApproval.subAgentName] })), _jsx(WaitingDuration, { requestedAt: pendingApproval.requestedAt }), _jsx("span", { className: "shrink-0 text-warning", "aria-hidden": "true", children: _jsx(ClockIcon, {}) })] }), _jsxs("div", { className: "px-3 py-2.5 space-y-2", children: [pendingApproval.message && categoryInfo.category !== "shell" && (_jsx("p", { className: "text-xs text-foreground", children: pendingApproval.message })), parsedArgs && (_jsx(ToolArgsView, { toolName: pendingApproval.toolName, args: parsedArgs, mcpServerSlug: pendingApproval.mcpServerSlug })), _jsxs("div", { className: "flex items-center gap-2 pt-1", children: [_jsx(ActionButton, { label: "Approve", action: ApprovalAction.APPROVE, activeAction: activeAction, isSubmitting: isSubmitting, onClick: handleAction, variant: "approve", cursorTarget: "approve-button" }), _jsx(ActionButton, { label: "Skip", action: ApprovalAction.SKIP, activeAction: activeAction, isSubmitting: isSubmitting, onClick: handleAction, variant: "skip" }), _jsx(ActionButton, { label: "Reject", action: ApprovalAction.REJECT, activeAction: activeAction, isSubmitting: isSubmitting, onClick: handleAction, variant: "reject" })] })] })] }));
});
// ---------------------------------------------------------------------------
// Internal sub-components
// ---------------------------------------------------------------------------
function ActionButton({ label, action, activeAction, isSubmitting, onClick, variant, cursorTarget, }) {
    const isActive = activeAction === action;
    const disabled = isSubmitting;
    const variantClasses = {
        approve: cn("bg-success text-success-foreground hover:bg-success/90", "disabled:bg-success/50 disabled:text-success-foreground/70"),
        skip: cn("border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground", "disabled:bg-muted-faint disabled:text-muted-foreground-faint"),
        reject: cn("bg-destructive text-destructive-foreground hover:bg-destructive-hover", "disabled:bg-destructive-subtle0 disabled:text-destructive-foreground/70"),
    };
    return (_jsxs("button", { type: "button", disabled: disabled, onClick: () => onClick(action), "aria-label": label, "data-cursor-target": cursorTarget, className: cn("inline-flex items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2", "disabled:cursor-not-allowed", variantClasses[variant]), children: [isActive && isSubmitting ? _jsx(SpinnerIcon, {}) : null, label] }));
}
function WaitingDuration({ requestedAt }) {
    const startMs = useMemo(() => {
        if (!requestedAt)
            return null;
        const t = new Date(requestedAt).getTime();
        return Number.isNaN(t) ? null : t;
    }, [requestedAt]);
    const [elapsed, setElapsed] = useState(null);
    useEffect(() => {
        if (startMs === null) {
            setElapsed(null);
            return;
        }
        setElapsed(Math.max(0, Date.now() - startMs));
        const id = setInterval(() => {
            setElapsed(Math.max(0, Date.now() - startMs));
        }, 1000);
        return () => clearInterval(id);
    }, [startMs]);
    if (elapsed === null)
        return null;
    return (_jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: formatElapsed(elapsed) }));
}
function formatElapsed(ms) {
    if (ms < 1000)
        return "just now";
    const seconds = Math.floor(ms / 1000);
    if (seconds < 60)
        return `${seconds}s`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    if (minutes < 60) {
        return remainingSeconds > 0
            ? `${minutes}m ${remainingSeconds}s`
            : `${minutes}m`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return remainingMinutes > 0
        ? `${hours}h ${remainingMinutes}m`
        : `${hours}h`;
}
// ---------------------------------------------------------------------------
// Inline SVG icons
// ---------------------------------------------------------------------------
function ClockIcon() {
    return (_jsxs("svg", { width: "10", height: "10", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("circle", { cx: "6", cy: "6", r: "4.5" }), _jsx("path", { d: "M6 3.5V6L7.5 7.5" })] }));
}
function SpinnerIcon() {
    return (_jsx("svg", { width: "10", height: "10", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M6 1.5A4.5 4.5 0 1 1 1.5 6", strokeLinecap: "round" }) }));
}
//# sourceMappingURL=ApprovalCard.js.map