"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useRef, useId } from "react";
import { cn } from "@stigmer/theme";
import { useScrollShadows } from "../internal/useScrollShadows";
import { ScrollFade } from "../internal/ScrollFade";
/**
 * Compact form that collects environment variable values for any
 * resource that declares `env` variables (Agents, MCP servers, etc.).
 *
 * Renders one labeled input per variable. Secret variables use a
 * password field with a visibility toggle. The form validates that
 * all fields are non-empty before allowing submission.
 *
 * A "Save for future runs" toggle (on by default) lets the user
 * choose between persisting secrets to their personal environment
 * or using them for a single execution only. The toggle state is
 * reported via `onSubmit` so the caller can route to the
 * appropriate codepath.
 *
 * This is a **pure presentational component** with no knowledge of
 * personal environments, resource instances, or orchestration. It
 * can be used standalone by platform builders for their own env
 * setup UIs, or composed by higher-level hooks like
 * {@link useAgentSetup} or `useMcpServerSetup` within the
 * {@link SessionComposer}.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <EnvVarForm
 *   title="GitHub MCP Server"
 *   description="Enter required credentials."
 *   variables={[
 *     { key: "GITHUB_TOKEN", isSecret: true, description: "Personal access token" },
 *     { key: "REPO_OWNER", isSecret: false },
 *   ]}
 *   onSubmit={(values, { saveForFuture }) => {
 *     if (saveForFuture) saveToEnvironment(values);
 *     else useAsRuntimeEnv(values);
 *   }}
 *   onCancel={() => console.log("cancelled")}
 * />
 * ```
 */
export function EnvVarForm({ variables, onSubmit, onCancel, isSubmitting, disabled, title, description, submitLabel, cancelLabel = "Back", defaultSaveForFuture = true, hideSaveToggle = false, poolValues, className, ariaLabel, }) {
    const [values, setValues] = useState(() => Object.fromEntries(variables.map((v) => {
        const poolVal = poolValues?.(v.key);
        return [v.key, poolVal?.value ?? ""];
    })));
    const [prefilledKeys] = useState(() => {
        if (!poolValues)
            return new Set();
        const keys = new Set();
        for (const v of variables) {
            if (poolValues(v.key))
                keys.add(v.key);
        }
        return keys;
    });
    const [revealedKeys, setRevealedKeys] = useState(new Set());
    const [saveForFuture, setSaveForFuture] = useState(defaultSaveForFuture);
    const firstInputRef = useRef(null);
    const fields = useScrollShadows();
    const instanceId = useId();
    const toggleId = `${instanceId}-save-toggle`;
    const isDisabled = disabled || isSubmitting;
    const allFilled = variables.every((v) => values[v.key]?.trim() !== "");
    const handleChange = useCallback((key, value) => {
        setValues((prev) => ({ ...prev, [key]: value }));
    }, []);
    const toggleReveal = useCallback((key) => {
        setRevealedKeys((prev) => {
            const next = new Set(prev);
            if (next.has(key)) {
                next.delete(key);
            }
            else {
                next.add(key);
            }
            return next;
        });
    }, []);
    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        if (!allFilled || isDisabled)
            return;
        const result = {};
        for (const variable of variables) {
            result[variable.key] = {
                value: values[variable.key],
                isSecret: variable.isSecret,
                ...(variable.description && { description: variable.description }),
            };
        }
        onSubmit(result, { saveForFuture });
    }, [allFilled, isDisabled, values, variables, onSubmit, saveForFuture]);
    const resolvedAriaLabel = ariaLabel ?? (title ? `Configure ${title}` : "Configure environment variables");
    const resolvedSubmitLabel = submitLabel ?? (saveForFuture ? "Save" : "Use once");
    return (_jsxs("form", { onSubmit: handleSubmit, className: cn("w-72 space-y-3", className), "aria-label": resolvedAriaLabel, children: [title && (_jsxs("div", { className: "space-y-0.5", children: [_jsx("h3", { className: "text-xs font-medium text-foreground", children: title }), description && (_jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: description }))] })), _jsxs("div", { className: "relative", children: [fields.canScrollUp && _jsx(ScrollFade, { position: "top" }), _jsx("div", { ref: fields.scrollRef, className: "max-h-64 space-y-2.5 overflow-y-auto", children: variables.map((variable, idx) => {
                            const inputId = `${instanceId}-env-${variable.key}`;
                            const descId = variable.description
                                ? `${inputId}-desc`
                                : undefined;
                            const isRevealed = revealedKeys.has(variable.key);
                            return (_jsxs("div", { className: "space-y-1", children: [_jsxs("label", { htmlFor: inputId, className: "flex items-baseline gap-1.5 text-[0.65rem] font-medium text-muted-foreground", children: [_jsx("span", { className: "font-mono", children: variable.key }), variable.isSecret && (_jsx("span", { className: "text-[0.55rem] uppercase tracking-wider text-muted-foreground-subtle", children: "secret" }))] }), _jsxs("div", { className: "relative", children: [_jsx("input", { ref: idx === 0 ? firstInputRef : undefined, id: inputId, type: variable.isSecret && !isRevealed ? "password" : "text", value: values[variable.key], onChange: (e) => handleChange(variable.key, e.target.value), disabled: isDisabled, required: true, "aria-required": true, "aria-describedby": descId, autoComplete: "off", autoFocus: idx === 0, className: cn("w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50", variable.isSecret && "pr-8") }), variable.isSecret && (_jsx("button", { type: "button", onClick: () => toggleReveal(variable.key), disabled: isDisabled, className: cn("absolute right-2 top-1/2 -translate-y-1/2", "text-muted-foreground hover:text-foreground", "disabled:pointer-events-none disabled:opacity-50"), "aria-label": isRevealed ? `Hide ${variable.key}` : `Show ${variable.key}`, tabIndex: -1, children: isRevealed ? _jsx(EyeOffIcon, {}) : _jsx(EyeIcon, {}) }))] }), variable.description && (_jsx("p", { id: descId, className: "text-[0.6rem] leading-relaxed text-muted-foreground-subtle", children: variable.description })), prefilledKeys.has(variable.key) && (_jsx("p", { className: "text-[0.55rem] text-primary-muted", children: "Pre-filled from session variables" }))] }, variable.key));
                        }) }), fields.canScrollDown && _jsx(ScrollFade, { position: "bottom" })] }), !hideSaveToggle && (_jsxs("div", { className: "flex items-start gap-2 pt-0.5", children: [_jsx("button", { id: toggleId, type: "button", role: "switch", "aria-checked": saveForFuture, onClick: () => setSaveForFuture((prev) => !prev), disabled: isDisabled, className: cn("relative mt-0.5 inline-flex h-4 w-7 shrink-0 cursor-pointer rounded-full transition-colors", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2", "disabled:pointer-events-none disabled:opacity-50", saveForFuture ? "bg-primary" : "bg-input"), children: _jsx("span", { className: cn("pointer-events-none block h-3 w-3 translate-y-0.5 rounded-full bg-background shadow-sm ring-0 transition-transform", saveForFuture ? "translate-x-3.5" : "translate-x-0.5") }) }), _jsxs("label", { htmlFor: toggleId, className: "cursor-pointer select-none space-y-0.5", children: [_jsx("span", { className: "block text-[0.65rem] font-medium text-muted-foreground", children: "Save for future runs" }), !saveForFuture && (_jsx("span", { className: "block text-[0.6rem] leading-relaxed text-muted-foreground-subtle", children: "These values will only be used for this run." }))] })] })), _jsxs("div", { className: "flex items-center justify-end gap-2 pt-1", children: [onCancel && (_jsx("button", { type: "button", onClick: onCancel, disabled: isDisabled, className: cn("rounded-md px-3 py-1.5 text-xs", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "disabled:pointer-events-none disabled:opacity-50"), children: cancelLabel })), _jsxs("button", { type: "submit", disabled: !allFilled || isDisabled, "data-cursor-target": "env-form-submit", className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium", "bg-primary text-primary-foreground", "hover:bg-primary-hover", "disabled:pointer-events-none disabled:opacity-40"), children: [isSubmitting && _jsx(SpinnerIcon, {}), resolvedSubmitLabel] })] })] }));
}
// ---------------------------------------------------------------------------
// Icons (internal to this module)
// ---------------------------------------------------------------------------
function EyeIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M1.5 8s2.5-4.5 6.5-4.5S14.5 8 14.5 8s-2.5 4.5-6.5 4.5S1.5 8 1.5 8z" }), _jsx("circle", { cx: "8", cy: "8", r: "2" })] }));
}
function EyeOffIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M6.59 6.59a2 2 0 0 0 2.82 2.82" }), _jsx("path", { d: "M10.73 10.73A6.5 6.5 0 0 1 8 12.5c-4 0-6.5-4.5-6.5-4.5a11.5 11.5 0 0 1 3.77-3.73" }), _jsx("path", { d: "M5.71 3.56A6.3 6.3 0 0 1 8 3.5c4 0 6.5 4.5 6.5 4.5a11.5 11.5 0 0 1-1.28 1.73" }), _jsx("path", { d: "M2 2l12 12" })] }));
}
function SpinnerIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=EnvVarForm.js.map