"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Bot,
  BookOpen,
  History,
  Image as ImageIcon,
  FileText,
  Loader2,
  Lock,
  Paperclip,
  RefreshCcw,
  Save,
  ShieldAlert,
  ShieldOff,
  Trash2,
  Wand2,
  Wrench
} from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Button } from "@open-mercato/ui/primitives/button";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import { Radio, RadioGroup } from "@open-mercato/ui/primitives/radio";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger
} from "@open-mercato/ui/primitives/tooltip";
import { EmptyState } from "@open-mercato/ui/backend/EmptyState";
import { apiCall, apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useAiShortcuts } from "@open-mercato/ui/ai";
const PROMPT_SECTION_IDS = [
  "role",
  "scope",
  "data",
  "tools",
  "attachments",
  "mutationPolicy",
  "responseStyle",
  "overrides"
];
const mutationPolicyStatusMap = {
  "read-only": "neutral",
  "confirm-required": "warning",
  "destructive-confirm-required": "error"
};
const executionModeStatusMap = {
  chat: "info",
  object: "success"
};
const mediaTypeIconMap = {
  image: ImageIcon,
  pdf: FileText,
  file: Paperclip
};
async function fetchAgents() {
  const { result, status } = await apiCallOrThrow(
    "/api/ai_assistant/ai/agents",
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load agents" }
  );
  if (!result) throw new Error(`Failed to load agents (${status})`);
  return result;
}
async function fetchRuntimeSettings() {
  const { result, status } = await apiCallOrThrow(
    "/api/ai_assistant/settings",
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load runtime settings" }
  );
  if (!result) throw new Error(`Failed to load runtime settings (${status})`);
  return result;
}
async function fetchOverride(agentId) {
  const { result, status } = await apiCallOrThrow(
    `/api/ai_assistant/ai/agents/${encodeURIComponent(agentId)}/prompt-override`,
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load prompt override" }
  );
  if (!result) throw new Error(`Failed to load prompt override (${status})`);
  return result;
}
const MUTATION_POLICY_OPTIONS = [
  "read-only",
  "destructive-confirm-required",
  "confirm-required"
];
const POLICY_RESTRICTIVENESS_UI = {
  "read-only": 0,
  "destructive-confirm-required": 1,
  "confirm-required": 2
};
async function fetchMutationPolicy(agentId) {
  const { result, status } = await apiCallOrThrow(
    `/api/ai_assistant/ai/agents/${encodeURIComponent(agentId)}/mutation-policy`,
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load mutation policy" }
  );
  if (!result) throw new Error(`Failed to load mutation policy (${status})`);
  return result;
}
function SettingsLoading({ message }) {
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "flex items-center gap-2 rounded-lg border border-border bg-background p-4 text-sm text-muted-foreground",
      role: "status",
      children: [
        /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }),
        /* @__PURE__ */ jsx("span", { children: message })
      ]
    }
  );
}
function EmptyAgents() {
  const t = useT();
  return /* @__PURE__ */ jsx(
    EmptyState,
    {
      icon: /* @__PURE__ */ jsx(Bot, { className: "size-6", "aria-hidden": true }),
      title: t(
        "ai_assistant.agents.empty.title",
        "No AI agents are registered for your role yet."
      ),
      description: t(
        "ai_assistant.agents.empty.description",
        "Declare agents inside `packages/<module>/src/modules/<module>/ai-agents.ts`, run `yarn generate`, and ensure the caller holds the agent's required features."
      ),
      children: /* @__PURE__ */ jsxs("div", { className: "mt-2 inline-flex items-center gap-2 text-xs text-muted-foreground", children: [
        /* @__PURE__ */ jsx(BookOpen, { className: "size-3", "aria-hidden": true }),
        /* @__PURE__ */ jsx("span", { children: t(
          "ai_assistant.agents.empty.docLabel",
          "See packages/ai-assistant/AGENTS.md for the agent definition reference."
        ) })
      ] })
    }
  );
}
function PromptSectionEditor({
  sectionId,
  defaultText,
  overrideText,
  override,
  onToggleOverride,
  onOverrideChange,
  onSaveShortcut
}) {
  const t = useT();
  const sectionLabel = t(
    `ai_assistant.agents.prompt.sections.${sectionId}`,
    sectionId.charAt(0).toUpperCase() + sectionId.slice(1)
  );
  const textareaId = `ai-agent-prompt-${sectionId}`;
  const textareaRef = React.useRef(null);
  const { handleKeyDown } = useAiShortcuts({
    onSubmit: onSaveShortcut,
    onCancel: () => {
      textareaRef.current?.blur();
    }
  });
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "flex flex-col gap-2 rounded-md border border-border bg-muted/20 p-3",
      "data-ai-agent-prompt-section": sectionId,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-col", children: [
            /* @__PURE__ */ jsx("span", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: sectionLabel }),
            /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: override ? t(
              "ai_assistant.agents.prompt.overrideModeLabel",
              "Override mode \u2014 replaces the default when persistence lands."
            ) : t(
              "ai_assistant.agents.prompt.defaultModeLabel",
              "Default \u2014 shipped with the agent definition."
            ) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: `${textareaId}-toggle`, className: "text-xs", children: t("ai_assistant.agents.prompt.toggleOverride", "Override") }),
            /* @__PURE__ */ jsx(
              Switch,
              {
                id: `${textareaId}-toggle`,
                checked: override,
                onCheckedChange: (next) => onToggleOverride(next),
                "aria-label": t("ai_assistant.agents.prompt.toggleOverride", "Override"),
                "data-ai-agent-prompt-toggle": sectionId
              }
            )
          ] })
        ] }),
        override ? /* @__PURE__ */ jsx(
          Textarea,
          {
            id: textareaId,
            ref: textareaRef,
            rows: 4,
            value: overrideText,
            onChange: (event) => onOverrideChange(event.target.value),
            onKeyDown: handleKeyDown,
            className: "resize-y font-mono text-xs",
            placeholder: t(
              "ai_assistant.agents.prompt.overridePlaceholder",
              "Write the replacement text for this section..."
            ),
            "aria-label": `${sectionLabel} override`,
            "data-ai-agent-prompt-override": sectionId
          }
        ) : /* @__PURE__ */ jsx(
          "pre",
          {
            className: "max-h-40 overflow-auto rounded border border-border bg-background p-2 text-xs font-mono whitespace-pre-wrap",
            "data-ai-agent-prompt-default": sectionId,
            children: defaultText
          }
        )
      ]
    }
  );
}
function ToolRow({ tool }) {
  const t = useT();
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "flex flex-wrap items-center justify-between gap-3 rounded-md border border-border bg-background px-3 py-2",
      "data-ai-agent-tool-row": tool.name,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2 min-w-0", children: [
          /* @__PURE__ */ jsx(Wrench, { className: "mt-0.5 size-4 text-muted-foreground", "aria-hidden": true }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-w-0", children: [
            /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium", children: tool.displayName }),
            /* @__PURE__ */ jsx("span", { className: "truncate text-xs font-mono text-muted-foreground", children: tool.name })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 flex-shrink-0", children: [
          tool.isMutation ? /* @__PURE__ */ jsx(StatusBadge, { variant: "warning", dot: true, children: t("ai_assistant.agents.tools.mutationBadge", "Mutation") }) : /* @__PURE__ */ jsx(StatusBadge, { variant: "neutral", dot: true, children: t("ai_assistant.agents.tools.readBadge", "Read") }),
          !tool.registered ? /* @__PURE__ */ jsx(StatusBadge, { variant: "error", dot: true, children: t("ai_assistant.agents.tools.missingBadge", "Missing") }) : null,
          /* @__PURE__ */ jsxs(Tooltip, { children: [
            /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
              /* @__PURE__ */ jsx(
                Label,
                {
                  htmlFor: `ai-agent-tool-${tool.name}`,
                  className: "text-xs text-muted-foreground",
                  children: t("ai_assistant.agents.tools.enabledLabel", "Enabled")
                }
              ),
              /* @__PURE__ */ jsx(
                Switch,
                {
                  id: `ai-agent-tool-${tool.name}`,
                  checked: true,
                  disabled: true,
                  "aria-label": t("ai_assistant.agents.tools.enabledLabel", "Enabled"),
                  "data-ai-agent-tool-switch": tool.name
                }
              )
            ] }) }),
            /* @__PURE__ */ jsx(TooltipContent, { children: t(
              "ai_assistant.agents.tools.tooltipDisabled",
              "Editable after Phase 3 lands mutation policy controls."
            ) })
          ] })
        ] })
      ]
    }
  );
}
function AttachmentPolicyBadges({ mediaTypes }) {
  const t = useT();
  if (!mediaTypes.length) {
    return /* @__PURE__ */ jsx(Badge, { variant: "neutral", children: t("ai_assistant.agents.attachments.noneBadge", "No attachments accepted") });
  }
  return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-2", children: mediaTypes.map((mediaType) => {
    const Icon = mediaTypeIconMap[mediaType] ?? Paperclip;
    return /* @__PURE__ */ jsxs(
      Badge,
      {
        variant: "info",
        className: "gap-1.5",
        "data-ai-agent-attachment-badge": mediaType,
        children: [
          /* @__PURE__ */ jsx(Icon, { className: "size-3", "aria-hidden": true }),
          /* @__PURE__ */ jsx("span", { className: "font-mono text-xs", children: mediaType })
        ]
      },
      mediaType
    );
  }) });
}
function MutationPolicySection({ agent }) {
  const t = useT();
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ["ai_assistant", "agent_settings", "mutation_policy", agent.id],
    queryFn: () => fetchMutationPolicy(agent.id),
    retry: false
  });
  const codeDeclared = query.data?.codeDeclared ?? agent.mutationPolicy;
  const currentOverride = query.data?.override ?? null;
  const [selected, setSelected] = React.useState(null);
  const [isSaving, setIsSaving] = React.useState(false);
  const [isClearing, setIsClearing] = React.useState(false);
  const [state, setState] = React.useState({ kind: "idle" });
  const { runMutation: runSavePolicyMutation } = useGuardedMutation({
    contextId: `ai-agent-mutation-policy-save-${agent.id}`
  });
  const { runMutation: runClearPolicyMutation } = useGuardedMutation({
    contextId: `ai-agent-mutation-policy-clear-${agent.id}`
  });
  React.useEffect(() => {
    setSelected(currentOverride?.mutationPolicy ?? null);
    setState({ kind: "idle" });
  }, [agent.id, currentOverride?.mutationPolicy]);
  const codeRank = POLICY_RESTRICTIVENESS_UI[codeDeclared] ?? 0;
  const effectivePolicy = (() => {
    if (!currentOverride) return codeDeclared;
    const overrideRank = POLICY_RESTRICTIVENESS_UI[currentOverride.mutationPolicy];
    return overrideRank < codeRank ? currentOverride.mutationPolicy : codeDeclared;
  })();
  const hasChange = selected !== null && selected !== (currentOverride?.mutationPolicy ?? null);
  const save = React.useCallback(async () => {
    if (!selected || isSaving) return;
    setIsSaving(true);
    setState({ kind: "idle" });
    try {
      await runSavePolicyMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            `/api/ai_assistant/ai/agents/${encodeURIComponent(agent.id)}/mutation-policy`,
            {
              method: "POST",
              headers: { "content-type": "application/json" },
              credentials: "include",
              body: JSON.stringify({ mutationPolicy: selected })
            }
          );
          const payload = result ?? {};
          if (!ok) {
            const message = payload.code === "escalation_not_allowed" ? payload.error ?? t(
              "ai_assistant.agents.mutation_policy.errors.escalationNotAllowed",
              "Cannot upgrade beyond the agent's declared policy \u2014 this is a code-level change."
            ) : payload.error ?? `Failed to save mutation policy (${status}).`;
            throw new Error(message);
          }
        },
        context: {}
      });
      const successMessage = t(
        "ai_assistant.agents.mutation_policy.savedMessage",
        "Mutation policy override saved."
      );
      setState({ kind: "success", message: successMessage });
      flash(successMessage, "success");
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "mutation_policy", agent.id]
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setState({ kind: "error", message });
      flash(message, "error");
    } finally {
      setIsSaving(false);
    }
  }, [agent.id, isSaving, queryClient, runSavePolicyMutation, selected, t]);
  const clear = React.useCallback(async () => {
    if (isClearing) return;
    setIsClearing(true);
    setState({ kind: "idle" });
    try {
      await runClearPolicyMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            `/api/ai_assistant/ai/agents/${encodeURIComponent(agent.id)}/mutation-policy`,
            {
              method: "DELETE",
              credentials: "include"
            }
          );
          const payload = result ?? {};
          if (!ok) {
            throw new Error(payload.error ?? `Failed to clear override (${status}).`);
          }
        },
        context: {}
      });
      const successMessage = t(
        "ai_assistant.agents.mutation_policy.clearedMessage",
        "Mutation policy override cleared; agent is using its code-declared policy."
      );
      setState({ kind: "success", message: successMessage });
      flash(successMessage, "success");
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "mutation_policy", agent.id]
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setState({ kind: "error", message });
      flash(message, "error");
    } finally {
      setIsClearing(false);
    }
  }, [agent.id, isClearing, queryClient, t]);
  return /* @__PURE__ */ jsxs(
    "section",
    {
      className: "rounded-lg border border-border bg-background p-4",
      "data-ai-agent-mutation-policy": agent.id,
      children: [
        /* @__PURE__ */ jsxs("header", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [
            /* @__PURE__ */ jsx(ShieldAlert, { className: "size-4 text-muted-foreground", "aria-hidden": true }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.mutation_policy.title", "Mutation policy") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "ai_assistant.agents.mutation_policy.subtitle",
                "Downgrade this agent's mutation capability per tenant. Upgrading beyond the code-declared policy is blocked by the server."
              ) })
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            StatusBadge,
            {
              variant: mutationPolicyStatusMap[effectivePolicy] ?? "neutral",
              dot: true,
              className: "max-w-full whitespace-normal break-all",
              "data-ai-agent-mutation-policy-effective": true,
              children: effectivePolicy
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-col gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] gap-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("span", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.mutation_policy.codeDeclared", "Code-declared") }),
              /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap items-center gap-2", children: [
                /* @__PURE__ */ jsx(
                  StatusBadge,
                  {
                    variant: mutationPolicyStatusMap[codeDeclared] ?? "neutral",
                    dot: true,
                    className: "max-w-full whitespace-normal break-all",
                    "data-ai-agent-mutation-policy-code-declared": true,
                    children: codeDeclared
                  }
                ),
                /* @__PURE__ */ jsx(Lock, { className: "size-3 text-muted-foreground", "aria-hidden": true }),
                /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t(
                  "ai_assistant.agents.mutation_policy.codeDeclaredHint",
                  "Compiled into the agent definition."
                ) })
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("span", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.mutation_policy.tenantOverride", "Tenant override") }),
              /* @__PURE__ */ jsx("div", { className: "mt-1", children: currentOverride ? /* @__PURE__ */ jsx(
                StatusBadge,
                {
                  variant: mutationPolicyStatusMap[currentOverride.mutationPolicy] ?? "neutral",
                  dot: true,
                  className: "max-w-full whitespace-normal break-all",
                  "data-ai-agent-mutation-policy-override-current": true,
                  children: currentOverride.mutationPolicy
                }
              ) : /* @__PURE__ */ jsx(
                "span",
                {
                  className: "text-xs text-muted-foreground",
                  "data-ai-agent-mutation-policy-override-empty": true,
                  children: t(
                    "ai_assistant.agents.mutation_policy.noOverride",
                    "No override \u2014 using code-declared policy."
                  )
                }
              ) })
            ] })
          ] }),
          /* @__PURE__ */ jsxs(
            Alert,
            {
              variant: "info",
              icon: /* @__PURE__ */ jsx(ShieldAlert, { "aria-hidden": "true" }),
              "data-ai-agent-mutation-policy-notice": true,
              children: [
                /* @__PURE__ */ jsx(AlertTitle, { children: t(
                  "ai_assistant.agents.mutation_policy.noticeTitle",
                  "Downgrade only \u2014 escalation is a code change"
                ) }),
                /* @__PURE__ */ jsx(AlertDescription, { children: t(
                  "ai_assistant.agents.mutation_policy.noticeBody",
                  "Overrides can only make the policy more restrictive. Options more permissive than the code-declared policy are disabled and rejected server-side."
                ) })
              ]
            }
          ),
          query.isLoading ? /* @__PURE__ */ jsx(
            SettingsLoading,
            {
              message: t(
                "ai_assistant.agents.mutation_policy.loading",
                "Loading mutation policy..."
              )
            }
          ) : query.isError ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-mutation-policy-load-error": true, children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t(
              "ai_assistant.agents.mutation_policy.loadErrorTitle",
              "Failed to load mutation policy"
            ) }),
            /* @__PURE__ */ jsx(AlertDescription, { children: query.error instanceof Error ? query.error.message : String(query.error) })
          ] }) : /* @__PURE__ */ jsx(
            RadioGroup,
            {
              value: selected ?? "",
              onValueChange: (value) => {
                setSelected(value);
              },
              className: "flex flex-col gap-2",
              "aria-label": t(
                "ai_assistant.agents.mutation_policy.pickerLabel",
                "Mutation policy override"
              ),
              "data-ai-agent-mutation-policy-picker": true,
              children: MUTATION_POLICY_OPTIONS.map((option) => {
                const optionRank = POLICY_RESTRICTIVENESS_UI[option];
                const wouldEscalate = optionRank > codeRank;
                const isSelected = selected === option;
                return /* @__PURE__ */ jsxs(Tooltip, { children: [
                  /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                    "div",
                    {
                      className: `flex items-start gap-3 rounded-md border px-3 py-2 text-sm cursor-pointer transition-colors ${wouldEscalate ? "border-border bg-muted/30 cursor-not-allowed opacity-60" : isSelected ? "border-accent-indigo bg-accent-indigo/5" : "border-border bg-background hover:bg-muted/40"}`,
                      onClick: () => {
                        if (wouldEscalate) return;
                        setSelected(option);
                      },
                      "data-ai-agent-mutation-policy-option": option,
                      "data-ai-agent-mutation-policy-option-disabled": wouldEscalate ? "true" : "false",
                      children: [
                        /* @__PURE__ */ jsx(
                          Radio,
                          {
                            value: option,
                            disabled: wouldEscalate,
                            className: "mt-0.5",
                            "aria-disabled": wouldEscalate
                          }
                        ),
                        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-0.5 min-w-0", children: [
                          /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
                            /* @__PURE__ */ jsx(
                              StatusBadge,
                              {
                                variant: mutationPolicyStatusMap[option] ?? "neutral",
                                dot: true,
                                children: option
                              }
                            ),
                            wouldEscalate ? /* @__PURE__ */ jsx(Lock, { className: "size-3 text-muted-foreground", "aria-hidden": true }) : null
                          ] }),
                          /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t(
                            `ai_assistant.agents.mutation_policy.options.${option}`,
                            option
                          ) })
                        ] })
                      ]
                    }
                  ) }),
                  wouldEscalate ? /* @__PURE__ */ jsx(TooltipContent, { children: t(
                    "ai_assistant.agents.mutation_policy.escalationTooltip",
                    "Cannot be set above the agent's declared policy \u2014 this is a code-level change."
                  ) }) : null
                ] }, option);
              })
            }
          ),
          state.kind === "success" ? /* @__PURE__ */ jsxs(Alert, { variant: "success", "data-ai-agent-mutation-policy-state": "success", children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.agents.mutation_policy.savedTitle", "Mutation policy updated") }),
            /* @__PURE__ */ jsx(AlertDescription, { children: state.message })
          ] }) : null,
          state.kind === "error" ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-mutation-policy-state": "error", children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t(
              "ai_assistant.agents.mutation_policy.errorTitle",
              "Failed to update mutation policy"
            ) }),
            /* @__PURE__ */ jsx(AlertDescription, { children: state.message })
          ] }) : null,
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-end gap-2", children: [
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                variant: "outline",
                onClick: () => void clear(),
                disabled: isClearing || isSaving || !currentOverride,
                "data-ai-agent-mutation-policy-clear": true,
                children: [
                  isClearing ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Trash2, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.mutation_policy.clear", "Clear override") })
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => void save(),
                disabled: isSaving || isClearing || !hasChange || selected === null,
                "data-ai-agent-mutation-policy-save": true,
                children: [
                  isSaving ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Save, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.mutation_policy.save", "Save override") })
                ]
              }
            )
          ] })
        ] })
      ]
    }
  );
}
function AgentModelOverrideSection({ agent }) {
  const t = useT();
  const queryClient = useQueryClient();
  const settingsQuery = useQuery({
    queryKey: ["ai_assistant", "agent_settings", "runtime_settings"],
    queryFn: fetchRuntimeSettings,
    retry: false
  });
  const agentResolution = settingsQuery.data?.agents.find((entry) => entry.agentId === agent.id) ?? null;
  const configuredProviders = React.useMemo(
    () => (settingsQuery.data?.availableProviders ?? []).filter((provider) => provider.configured),
    [settingsQuery.data?.availableProviders]
  );
  const [selectedProviderId, setSelectedProviderId] = React.useState("");
  const [selectedModelId, setSelectedModelId] = React.useState("");
  const [allowedProviders, setAllowedProviders] = React.useState(null);
  const [allowedModelsByProvider, setAllowedModelsByProvider] = React.useState({});
  const [allowlistDirty, setAllowlistDirty] = React.useState(false);
  const [isSaving, setIsSaving] = React.useState(false);
  const [isClearing, setIsClearing] = React.useState(false);
  const [isSavingAllowlist, setIsSavingAllowlist] = React.useState(false);
  const [state, setState] = React.useState({ kind: "idle" });
  const { runMutation: runSaveModelOverrideMutation } = useGuardedMutation({
    contextId: `ai-agent-model-override-save-${agent.id}`
  });
  const { runMutation: runClearModelOverrideMutation } = useGuardedMutation({
    contextId: `ai-agent-model-override-clear-${agent.id}`
  });
  const { runMutation: runSaveModelAllowlistMutation } = useGuardedMutation({
    contextId: `ai-agent-model-override-allowlist-${agent.id}`
  });
  React.useEffect(() => {
    const override = agentResolution?.override;
    setSelectedProviderId(override?.providerId ?? "");
    setSelectedModelId(override?.modelId ?? "");
    setAllowedProviders(agentResolution?.runtimeOverrideAllowlist.tenant?.allowedProviders ?? null);
    setAllowedModelsByProvider({
      ...agentResolution?.runtimeOverrideAllowlist.tenant?.allowedModelsByProvider ?? {}
    });
    setAllowlistDirty(false);
    setState({ kind: "idle" });
  }, [
    agent.id,
    agentResolution?.override?.modelId,
    agentResolution?.override?.providerId,
    agentResolution?.runtimeOverrideAllowlist.tenant
  ]);
  const selectedProvider = configuredProviders.find((provider) => provider.id === selectedProviderId);
  const isProviderAllowedForPicker = React.useCallback(
    (providerId) => {
      if (allowedProviders === null) return true;
      return allowedProviders.includes(providerId);
    },
    [allowedProviders]
  );
  const isModelAllowedForPicker = React.useCallback(
    (providerId, modelId) => {
      const list = allowedModelsByProvider[providerId];
      if (list === void 0) return true;
      return list.includes(modelId);
    },
    [allowedModelsByProvider]
  );
  const hasChange = selectedProviderId.length > 0 && selectedModelId.length > 0 && (selectedProviderId !== (agentResolution?.override?.providerId ?? "") || selectedModelId !== (agentResolution?.override?.modelId ?? ""));
  const save = React.useCallback(async () => {
    if (isSaving || !selectedProviderId || !selectedModelId) return;
    setIsSaving(true);
    setState({ kind: "idle" });
    try {
      await runSaveModelOverrideMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            "/api/ai_assistant/settings",
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              credentials: "include",
              body: JSON.stringify({
                agentId: agent.id,
                providerId: selectedProviderId,
                modelId: selectedModelId
              })
            }
          );
          if (!ok) {
            throw new Error(result?.error ?? `Failed to save model override (${status}).`);
          }
        },
        context: {}
      });
      const successMessage = t("ai_assistant.agents.model_override.saved", "Model override saved.");
      setState({ kind: "success", message: successMessage });
      flash(successMessage, "success");
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "runtime_settings"]
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setState({ kind: "error", message });
      flash(message, "error");
    } finally {
      setIsSaving(false);
    }
  }, [agent.id, isSaving, queryClient, runSaveModelOverrideMutation, selectedModelId, selectedProviderId, t]);
  const clear = React.useCallback(async () => {
    if (isClearing) return;
    setIsClearing(true);
    setState({ kind: "idle" });
    try {
      await runClearModelOverrideMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            "/api/ai_assistant/settings",
            {
              method: "DELETE",
              headers: { "content-type": "application/json" },
              credentials: "include",
              body: JSON.stringify({ agentId: agent.id })
            }
          );
          if (!ok) {
            throw new Error(result?.error ?? `Failed to clear model override (${status}).`);
          }
        },
        context: {}
      });
      setSelectedProviderId("");
      setSelectedModelId("");
      const successMessage = t(
        "ai_assistant.agents.model_override.cleared",
        "Model override cleared; the agent is using the normal resolution chain."
      );
      setState({ kind: "success", message: successMessage });
      flash(successMessage, "success");
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "runtime_settings"]
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setState({ kind: "error", message });
      flash(message, "error");
    } finally {
      setIsClearing(false);
    }
  }, [agent.id, isClearing, queryClient, runClearModelOverrideMutation, t]);
  const toggleAllowedProvider = React.useCallback(
    (providerId, next) => {
      setAllowlistDirty(true);
      setState({ kind: "idle" });
      setAllowedProviders((current) => {
        if (next) {
          return current === null ? [providerId] : Array.from(/* @__PURE__ */ new Set([...current, providerId]));
        }
        const baseline = current === null ? configuredProviders.map((provider) => provider.id) : current;
        return baseline.filter((id) => id !== providerId);
      });
    },
    [configuredProviders]
  );
  const toggleAllowedModel = React.useCallback(
    (providerId, modelId, next) => {
      setAllowlistDirty(true);
      setState({ kind: "idle" });
      const provider = configuredProviders.find((entry) => entry.id === providerId);
      const allModelIds = provider?.defaultModels.map((model) => model.id) ?? [];
      setAllowedModelsByProvider((current) => {
        const existing = current[providerId];
        const baseline = existing === void 0 ? allModelIds : existing;
        const nextModels = next ? Array.from(/* @__PURE__ */ new Set([...baseline, modelId])) : baseline.filter((id) => id !== modelId);
        return { ...current, [providerId]: nextModels };
      });
    },
    [configuredProviders]
  );
  const resetAllowlistDraft = React.useCallback(() => {
    setAllowedProviders(null);
    setAllowedModelsByProvider({});
    setAllowlistDirty(true);
    setState({ kind: "idle" });
  }, []);
  const saveAllowlist = React.useCallback(async () => {
    if (isSavingAllowlist) return;
    setIsSavingAllowlist(true);
    setState({ kind: "idle" });
    try {
      await runSaveModelAllowlistMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            "/api/ai_assistant/settings",
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              credentials: "include",
              body: JSON.stringify({
                agentId: agent.id,
                allowedOverrideProviders: allowedProviders,
                allowedOverrideModelsByProvider: allowedModelsByProvider
              })
            }
          );
          if (!ok) {
            throw new Error(result?.error ?? `Failed to save chat override allowlist (${status}).`);
          }
        },
        context: {}
      });
      setAllowlistDirty(false);
      const successMessage = t(
        "ai_assistant.agents.model_override.allowlistSaved",
        "Chat override choices saved."
      );
      setState({ kind: "success", message: successMessage });
      flash(successMessage, "success");
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "runtime_settings"]
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setState({ kind: "error", message });
      flash(message, "error");
    } finally {
      setIsSavingAllowlist(false);
    }
  }, [agent.id, allowedModelsByProvider, allowedProviders, isSavingAllowlist, queryClient, runSaveModelAllowlistMutation, t]);
  const busy = isSaving || isClearing || isSavingAllowlist;
  return /* @__PURE__ */ jsxs(
    "section",
    {
      className: "rounded-lg border border-border bg-background p-4",
      "data-ai-agent-model-override": agent.id,
      children: [
        /* @__PURE__ */ jsxs("header", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [
            /* @__PURE__ */ jsx(Bot, { className: "size-4 text-muted-foreground", "aria-hidden": true }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.model_override.title", "Provider and model") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "ai_assistant.agents.model_override.subtitle",
                "Override the default provider and model for this tenant and agent."
              ) })
            ] })
          ] }),
          agentResolution ? /* @__PURE__ */ jsxs(
            StatusBadge,
            {
              variant: "info",
              dot: true,
              className: "max-w-full whitespace-normal break-all",
              "data-ai-agent-model-override-effective": true,
              children: [
                agentResolution.providerId,
                " / ",
                agentResolution.modelId
              ]
            }
          ) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-col gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] gap-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("span", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.model_override.codeDefault", "Code-declared default") }),
              /* @__PURE__ */ jsxs("p", { className: "mt-1 break-all font-mono text-xs", children: [
                agent.defaultProvider ?? t("ai_assistant.agents.model_override.anyProvider", "first configured"),
                " / ",
                agent.defaultModel ?? t("ai_assistant.agents.model_override.providerDefault", "provider default")
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("span", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.model_override.tenantOverride", "Tenant override") }),
              /* @__PURE__ */ jsx("p", { className: "mt-1 break-all font-mono text-xs text-muted-foreground", children: agentResolution?.override ? `${agentResolution.override.providerId ?? "\u2014"} / ${agentResolution.override.modelId ?? "\u2014"}` : t("ai_assistant.agents.model_override.noOverride", "No per-agent override") })
            ] })
          ] }),
          settingsQuery.isLoading ? /* @__PURE__ */ jsx(
            SettingsLoading,
            {
              message: t(
                "ai_assistant.agents.model_override.loading",
                "Loading provider catalog..."
              )
            }
          ) : settingsQuery.isError ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-model-override-load-error": true, children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t(
              "ai_assistant.agents.model_override.loadErrorTitle",
              "Failed to load provider catalog"
            ) }),
            /* @__PURE__ */ jsx(AlertDescription, { children: settingsQuery.error instanceof Error ? settingsQuery.error.message : String(settingsQuery.error) })
          ] }) : /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] gap-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-col gap-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `ai-agent-model-provider-${agent.id}`, className: "text-xs", children: t("ai_assistant.agents.model_override.provider", "Provider") }),
              /* @__PURE__ */ jsxs(
                Select,
                {
                  value: selectedProviderId,
                  onValueChange: (value) => {
                    setSelectedProviderId(value);
                    setSelectedModelId("");
                    setState({ kind: "idle" });
                  },
                  disabled: busy || configuredProviders.length === 0,
                  children: [
                    /* @__PURE__ */ jsx(
                      SelectTrigger,
                      {
                        id: `ai-agent-model-provider-${agent.id}`,
                        className: "w-full min-w-0",
                        "data-ai-agent-model-provider-select": true,
                        children: /* @__PURE__ */ jsx(
                          SelectValue,
                          {
                            placeholder: t(
                              "ai_assistant.agents.model_override.selectProvider",
                              "Select provider"
                            )
                          }
                        )
                      }
                    ),
                    /* @__PURE__ */ jsx(SelectContent, { children: configuredProviders.map((provider) => /* @__PURE__ */ jsx(SelectItem, { value: provider.id, children: provider.name }, provider.id)) })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-col gap-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `ai-agent-model-model-${agent.id}`, className: "text-xs", children: t("ai_assistant.agents.model_override.model", "Model") }),
              /* @__PURE__ */ jsxs(
                Select,
                {
                  value: selectedModelId,
                  onValueChange: (value) => {
                    setSelectedModelId(value);
                    setState({ kind: "idle" });
                  },
                  disabled: busy || !selectedProvider,
                  children: [
                    /* @__PURE__ */ jsx(
                      SelectTrigger,
                      {
                        id: `ai-agent-model-model-${agent.id}`,
                        className: "w-full min-w-0",
                        "data-ai-agent-model-select": true,
                        children: /* @__PURE__ */ jsx(
                          SelectValue,
                          {
                            placeholder: t(
                              "ai_assistant.agents.model_override.selectModel",
                              "Select model"
                            )
                          }
                        )
                      }
                    ),
                    /* @__PURE__ */ jsx(SelectContent, { children: (selectedProvider?.defaultModels ?? []).map((model) => /* @__PURE__ */ jsx(SelectItem, { value: model.id, children: model.name }, model.id)) })
                  ]
                }
              )
            ] })
          ] }),
          agent.allowRuntimeModelOverride ? /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-border bg-muted/20 p-3", "data-ai-agent-model-picker-allowlist": true, children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [
              /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                /* @__PURE__ */ jsx("h4", { className: "text-sm font-semibold", children: t(
                  "ai_assistant.agents.model_override.allowlistTitle",
                  "Chat override choices"
                ) }),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                  "ai_assistant.agents.model_override.allowlistHelp",
                  "Limit which provider/model overrides users can pick in the chat footer for this agent."
                ) }),
                agentResolution?.runtimeOverrideAllowlist.env ? /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
                  /* @__PURE__ */ jsx("code", { className: "font-mono text-xs", children: agentResolution.runtimeOverrideAllowlist.envVarNames.providers }),
                  " ",
                  t(
                    "ai_assistant.agents.model_override.envAlsoNarrows",
                    "also narrows this list from env."
                  )
                ] }) : null
              ] }),
              /* @__PURE__ */ jsx(
                StatusBadge,
                {
                  variant: agentResolution?.runtimeOverrideAllowlist.tenant ? "info" : "neutral",
                  dot: true,
                  children: agentResolution?.runtimeOverrideAllowlist.tenant ? t("ai_assistant.agents.model_override.allowlistCustom", "custom") : t("ai_assistant.agents.model_override.allowlistInherited", "inherited")
                }
              )
            ] }),
            /* @__PURE__ */ jsx("div", { className: "mt-3 flex flex-col gap-3", children: configuredProviders.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
              "ai_assistant.agents.model_override.allowlistEmpty",
              "No configured providers are available for chat overrides."
            ) }) : configuredProviders.map((provider) => {
              const providerEnabled = isProviderAllowedForPicker(provider.id);
              return /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-border bg-background p-3", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(
                    Checkbox,
                    {
                      id: `ai-agent-picker-provider-${agent.id}-${provider.id}`,
                      checked: providerEnabled,
                      onCheckedChange: (value) => toggleAllowedProvider(provider.id, value === true)
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Label,
                    {
                      htmlFor: `ai-agent-picker-provider-${agent.id}-${provider.id}`,
                      className: "text-sm font-medium",
                      children: provider.name
                    }
                  )
                ] }),
                providerEnabled ? /* @__PURE__ */ jsx("div", { className: "mt-2 grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] gap-2", children: provider.defaultModels.map((model) => /* @__PURE__ */ jsxs(
                  "label",
                  {
                    className: "flex min-w-0 items-center gap-2 text-xs",
                    children: [
                      /* @__PURE__ */ jsx(
                        Checkbox,
                        {
                          checked: isModelAllowedForPicker(provider.id, model.id),
                          onCheckedChange: (value) => toggleAllowedModel(provider.id, model.id, value === true)
                        }
                      ),
                      /* @__PURE__ */ jsx("span", { className: "truncate font-mono", children: model.id }),
                      model.id === provider.defaultModel ? /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-overline", children: t("ai_assistant.agents.model_override.defaultBadge", "default") }) : null
                    ]
                  },
                  model.id
                )) }) : null
              ] }, provider.id);
            }) }),
            /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center justify-end gap-2", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  size: "sm",
                  variant: "outline",
                  onClick: resetAllowlistDraft,
                  disabled: busy,
                  children: t("ai_assistant.agents.model_override.allowlistReset", "Inherit")
                }
              ),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  size: "sm",
                  onClick: () => void saveAllowlist(),
                  disabled: busy || !allowlistDirty,
                  "data-ai-agent-model-allowlist-save": true,
                  children: [
                    isSavingAllowlist ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Save, { className: "size-4", "aria-hidden": true }),
                    /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.model_override.allowlistSave", "Save choices") })
                  ]
                }
              )
            ] })
          ] }) : null,
          state.kind === "success" ? /* @__PURE__ */ jsx(Alert, { variant: "success", "data-ai-agent-model-override-state": "success", children: /* @__PURE__ */ jsx(AlertDescription, { children: state.message }) }) : null,
          state.kind === "error" ? /* @__PURE__ */ jsx(Alert, { variant: "destructive", "data-ai-agent-model-override-state": "error", children: /* @__PURE__ */ jsx(AlertDescription, { children: state.message }) }) : null,
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-end gap-2", children: [
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                variant: "outline",
                onClick: () => void clear(),
                disabled: busy || !agentResolution?.override,
                "data-ai-agent-model-clear": true,
                children: [
                  isClearing ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Trash2, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.model_override.clear", "Clear override") })
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => void save(),
                disabled: busy || !hasChange,
                "data-ai-agent-model-save": true,
                children: [
                  isSaving ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Save, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.model_override.save", "Save override") })
                ]
              }
            )
          ] })
        ] })
      ]
    }
  );
}
async function fetchLoopOverride(agentId) {
  const { result, status } = await apiCallOrThrow(
    `/api/ai_assistant/ai/agents/${encodeURIComponent(agentId)}/loop-override`,
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load loop override" }
  );
  if (!result) throw new Error(`Failed to load loop override (${status})`);
  return result;
}
function LoopPolicySection({ agent }) {
  const t = useT();
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ["ai_assistant", "agent_settings", "loop_override", agent.id],
    queryFn: () => fetchLoopOverride(agent.id),
    retry: false
  });
  const currentOverride = query.data?.override ?? null;
  const [loopDisabled, setLoopDisabled] = React.useState(false);
  const [maxSteps, setMaxSteps] = React.useState("");
  const [maxToolCalls, setMaxToolCalls] = React.useState("");
  const [maxWallClockMs, setMaxWallClockMs] = React.useState("");
  const [maxTokens, setMaxTokens] = React.useState("");
  const [isSaving, setIsSaving] = React.useState(false);
  const [isClearing, setIsClearing] = React.useState(false);
  const [state, setState] = React.useState({ kind: "idle" });
  React.useEffect(() => {
    setLoopDisabled(currentOverride?.loopDisabled ?? false);
    setMaxSteps(currentOverride?.loopMaxSteps != null ? String(currentOverride.loopMaxSteps) : "");
    setMaxToolCalls(
      currentOverride?.loopMaxToolCalls != null ? String(currentOverride.loopMaxToolCalls) : ""
    );
    setMaxWallClockMs(
      currentOverride?.loopMaxWallClockMs != null ? String(currentOverride.loopMaxWallClockMs) : ""
    );
    setMaxTokens(
      currentOverride?.loopMaxTokens != null ? String(currentOverride.loopMaxTokens) : ""
    );
    setState({ kind: "idle" });
  }, [
    agent.id,
    currentOverride?.loopDisabled,
    currentOverride?.loopMaxSteps,
    currentOverride?.loopMaxToolCalls,
    currentOverride?.loopMaxWallClockMs,
    currentOverride?.loopMaxTokens
  ]);
  const toNullableInt = (value) => {
    const trimmed = value.trim();
    if (trimmed === "") return null;
    const parsed = parseInt(trimmed, 10);
    return isNaN(parsed) ? null : parsed;
  };
  const save = React.useCallback(async () => {
    if (isSaving) return;
    setIsSaving(true);
    setState({ kind: "idle" });
    try {
      const { ok, status, result } = await apiCall(
        `/api/ai_assistant/ai/agents/${encodeURIComponent(agent.id)}/loop-override`,
        {
          method: "PUT",
          headers: { "content-type": "application/json" },
          credentials: "include",
          body: JSON.stringify({
            loopDisabled: loopDisabled || null,
            loopMaxSteps: toNullableInt(maxSteps),
            loopMaxToolCalls: toNullableInt(maxToolCalls),
            loopMaxWallClockMs: toNullableInt(maxWallClockMs),
            loopMaxTokens: toNullableInt(maxTokens)
          })
        }
      );
      const payload = result ?? {};
      if (!ok) {
        setState({
          kind: "error",
          message: payload.error ?? `Failed to save loop policy (${status}).`
        });
        return;
      }
      setState({
        kind: "success",
        message: t("ai_assistant.agents.loop_policy.savedMessage", "Loop policy override saved.")
      });
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "loop_override", agent.id]
      });
    } catch (err) {
      setState({
        kind: "error",
        message: err instanceof Error ? err.message : String(err)
      });
    } finally {
      setIsSaving(false);
    }
  }, [agent.id, isSaving, loopDisabled, maxSteps, maxToolCalls, maxWallClockMs, maxTokens, queryClient, t]);
  const clear = React.useCallback(async () => {
    if (isClearing) return;
    setIsClearing(true);
    setState({ kind: "idle" });
    try {
      const { ok, status, result } = await apiCall(
        `/api/ai_assistant/ai/agents/${encodeURIComponent(agent.id)}/loop-override`,
        { method: "DELETE", credentials: "include" }
      );
      const payload = result ?? {};
      if (!ok) {
        setState({
          kind: "error",
          message: payload.error ?? `Failed to clear loop override (${status}).`
        });
        return;
      }
      setState({
        kind: "success",
        message: t(
          "ai_assistant.agents.loop_policy.clearedMessage",
          "Loop policy override cleared; agent is using its declared defaults."
        )
      });
      await queryClient.invalidateQueries({
        queryKey: ["ai_assistant", "agent_settings", "loop_override", agent.id]
      });
    } catch (err) {
      setState({
        kind: "error",
        message: err instanceof Error ? err.message : String(err)
      });
    } finally {
      setIsClearing(false);
    }
  }, [agent.id, isClearing, queryClient, t]);
  return /* @__PURE__ */ jsxs(
    "section",
    {
      className: "rounded-lg border border-border bg-background p-4",
      "data-ai-agent-loop-policy": agent.id,
      children: [
        /* @__PURE__ */ jsxs("header", { className: "flex items-center justify-between gap-3 border-b border-border pb-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(ShieldOff, { className: "size-4 text-muted-foreground", "aria-hidden": true }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.loop_policy.title", "Loop policy") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "ai_assistant.agents.loop_policy.subtitle",
                "Set per-tenant budget limits or disable the agentic loop for this agent."
              ) })
            ] })
          ] }),
          currentOverride?.loopDisabled ? /* @__PURE__ */ jsx(Badge, { variant: "destructive", "data-ai-agent-loop-disabled-badge": true, children: t("ai_assistant.agents.loop_policy.disabledBadge", "Loop disabled") }) : null
        ] }),
        /* @__PURE__ */ jsx("div", { className: "mt-3 flex flex-col gap-4", children: query.isLoading ? /* @__PURE__ */ jsx(
          SettingsLoading,
          {
            message: t("ai_assistant.agents.loop_policy.loading", "Loading loop policy...")
          }
        ) : query.isError ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-loop-policy-load-error": true, children: [
          /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.agents.loop_policy.loadErrorTitle", "Failed to load loop policy") }),
          /* @__PURE__ */ jsx(AlertDescription, { children: query.error instanceof Error ? query.error.message : String(query.error) })
        ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: t("ai_assistant.agents.loop_policy.killSwitchLabel", "Kill switch") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "ai_assistant.agents.loop_policy.killSwitchDescription",
                "When enabled, the agent runs as a single model call with no tool loop."
              ) })
            ] }),
            /* @__PURE__ */ jsx(
              Switch,
              {
                checked: loopDisabled,
                onCheckedChange: (next) => setLoopDisabled(next),
                "aria-label": t("ai_assistant.agents.loop_policy.killSwitchLabel", "Kill switch"),
                "data-ai-agent-loop-kill-switch": true
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `loop-max-steps-${agent.id}`, className: "text-xs", children: t("ai_assistant.agents.loop_policy.maxStepsLabel", "Max steps") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `loop-max-steps-${agent.id}`,
                  type: "number",
                  min: 1,
                  max: 1e3,
                  value: maxSteps,
                  onChange: (event) => setMaxSteps(event.target.value),
                  placeholder: t("ai_assistant.agents.loop_policy.noOverridePlaceholder", "No override"),
                  className: "h-8 text-sm",
                  "data-ai-agent-loop-max-steps": true
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `loop-max-tool-calls-${agent.id}`, className: "text-xs", children: t("ai_assistant.agents.loop_policy.maxToolCallsLabel", "Max tool calls") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `loop-max-tool-calls-${agent.id}`,
                  type: "number",
                  min: 1,
                  max: 1e4,
                  value: maxToolCalls,
                  onChange: (event) => setMaxToolCalls(event.target.value),
                  placeholder: t("ai_assistant.agents.loop_policy.noOverridePlaceholder", "No override"),
                  className: "h-8 text-sm",
                  "data-ai-agent-loop-max-tool-calls": true
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `loop-max-wall-clock-${agent.id}`, className: "text-xs", children: t("ai_assistant.agents.loop_policy.maxWallClockMsLabel", "Max wall-clock (ms)") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `loop-max-wall-clock-${agent.id}`,
                  type: "number",
                  min: 100,
                  max: 36e5,
                  value: maxWallClockMs,
                  onChange: (event) => setMaxWallClockMs(event.target.value),
                  placeholder: t("ai_assistant.agents.loop_policy.noOverridePlaceholder", "No override"),
                  className: "h-8 text-sm",
                  "data-ai-agent-loop-max-wall-clock-ms": true
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `loop-max-tokens-${agent.id}`, className: "text-xs", children: t("ai_assistant.agents.loop_policy.maxTokensLabel", "Max tokens") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `loop-max-tokens-${agent.id}`,
                  type: "number",
                  min: 1,
                  max: 1e7,
                  value: maxTokens,
                  onChange: (event) => setMaxTokens(event.target.value),
                  placeholder: t("ai_assistant.agents.loop_policy.noOverridePlaceholder", "No override"),
                  className: "h-8 text-sm",
                  "data-ai-agent-loop-max-tokens": true
                }
              )
            ] })
          ] }),
          state.kind === "success" ? /* @__PURE__ */ jsxs(Alert, { variant: "success", "data-ai-agent-loop-policy-state": "success", children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.agents.loop_policy.savedTitle", "Loop policy updated") }),
            /* @__PURE__ */ jsx(AlertDescription, { children: state.message })
          ] }) : null,
          state.kind === "error" ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-loop-policy-state": "error", children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t(
              "ai_assistant.agents.loop_policy.errorTitle",
              "Failed to update loop policy"
            ) }),
            /* @__PURE__ */ jsx(AlertDescription, { children: state.message })
          ] }) : null,
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2", children: [
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                variant: "outline",
                onClick: () => void clear(),
                disabled: isClearing || isSaving || !currentOverride,
                "data-ai-agent-loop-policy-clear": true,
                children: [
                  isClearing ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Trash2, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.loop_policy.clear", "Clear override") })
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => void save(),
                disabled: isSaving || isClearing,
                "data-ai-agent-loop-policy-save": true,
                children: [
                  isSaving ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Save, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.loop_policy.save", "Save override") })
                ]
              }
            )
          ] })
        ] }) })
      ]
    }
  );
}
function AgentDetailPanel({ agent }) {
  const t = useT();
  const queryClient = useQueryClient();
  const [overrideFlags, setOverrideFlags] = React.useState(() => ({
    role: false,
    scope: false,
    data: false,
    tools: false,
    attachments: false,
    mutationPolicy: false,
    responseStyle: false,
    overrides: false
  }));
  const [overrideDrafts, setOverrideDrafts] = React.useState(() => ({
    role: "",
    scope: "",
    data: "",
    tools: "",
    attachments: "",
    mutationPolicy: "",
    responseStyle: "",
    overrides: ""
  }));
  const [isSaving, setIsSaving] = React.useState(false);
  const [saveState, setSaveState] = React.useState({ kind: "idle" });
  const { runMutation: runSavePromptOverrideMutation } = useGuardedMutation({
    contextId: `ai-agent-prompt-override-save-${agent.id}`
  });
  const overrideQuery = useQuery({
    queryKey: ["ai_assistant", "agent_settings", "override", agent.id],
    queryFn: () => fetchOverride(agent.id),
    retry: false
  });
  React.useEffect(() => {
    setOverrideFlags({
      role: false,
      scope: false,
      data: false,
      tools: false,
      attachments: false,
      mutationPolicy: false,
      responseStyle: false,
      overrides: false
    });
    setOverrideDrafts({
      role: "",
      scope: "",
      data: "",
      tools: "",
      attachments: "",
      mutationPolicy: "",
      responseStyle: "",
      overrides: ""
    });
    setSaveState({ kind: "idle" });
  }, [agent.id]);
  React.useEffect(() => {
    const latest = overrideQuery.data?.override;
    if (!latest) return;
    const nextFlags = {
      role: false,
      scope: false,
      data: false,
      tools: false,
      attachments: false,
      mutationPolicy: false,
      responseStyle: false,
      overrides: false
    };
    const nextDrafts = {
      role: "",
      scope: "",
      data: "",
      tools: "",
      attachments: "",
      mutationPolicy: "",
      responseStyle: "",
      overrides: ""
    };
    for (const [rawKey, value] of Object.entries(latest.sections ?? {})) {
      if (typeof value !== "string") continue;
      const key = rawKey;
      if (PROMPT_SECTION_IDS.includes(key)) {
        nextFlags[key] = true;
        nextDrafts[key] = value;
      }
    }
    setOverrideFlags(nextFlags);
    setOverrideDrafts(nextDrafts);
  }, [overrideQuery.data?.override]);
  const activeOverrides = React.useMemo(() => {
    const payload = {};
    for (const section of PROMPT_SECTION_IDS) {
      if (overrideFlags[section]) {
        payload[section] = overrideDrafts[section];
      }
    }
    return payload;
  }, [overrideDrafts, overrideFlags]);
  const hasAnyOverride = Object.keys(activeOverrides).length > 0;
  const handleSave = React.useCallback(async () => {
    if (isSaving) return;
    setIsSaving(true);
    setSaveState({ kind: "idle" });
    try {
      const payload = await runSavePromptOverrideMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            `/api/ai_assistant/ai/agents/${encodeURIComponent(agent.id)}/prompt-override`,
            {
              method: "POST",
              headers: { "content-type": "application/json" },
              credentials: "include",
              body: JSON.stringify({
                // Send both keys so a pre-Step-5.3 server still accepts the payload.
                sections: activeOverrides,
                overrides: activeOverrides
              })
            }
          );
          const body = result ?? {};
          if (!ok) {
            const message = body.code === "reserved_key" ? t(
              "ai_assistant.agents.override.errors.reservedKey",
              "Prompt overrides cannot modify policy fields (mutationPolicy, readOnly, allowedTools, acceptedMediaTypes). Remove those sections and retry."
            ) : body.error ?? `Failed to save overrides (${status}).`;
            throw new Error(message);
          }
          return body;
        },
        context: {}
      });
      if (payload.ok === true && typeof payload.version === "number") {
        const successMessage = t(
          "ai_assistant.agents.override.savedMessage",
          "Prompt override saved."
        );
        setSaveState({
          kind: "success",
          version: payload.version,
          message: successMessage
        });
        flash(successMessage, "success");
        await queryClient.invalidateQueries({
          queryKey: ["ai_assistant", "agent_settings", "override", agent.id]
        });
        return;
      }
      const legacyMessage = payload.message ?? t(
        "ai_assistant.agents.prompt.pendingMessage",
        "Prompt overrides accepted."
      );
      setSaveState({
        kind: "success",
        version: 0,
        message: legacyMessage
      });
      flash(legacyMessage, "success");
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setSaveState({ kind: "error", message });
      flash(message, "error");
    } finally {
      setIsSaving(false);
    }
  }, [activeOverrides, agent.id, isSaving, queryClient, runSavePromptOverrideMutation, t]);
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4", "data-ai-agent-detail": agent.id, children: [
    /* @__PURE__ */ jsxs("section", { className: "rounded-lg border border-border bg-background p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-xl font-semibold", children: agent.label }),
      /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: agent.description }),
      /* @__PURE__ */ jsxs("dl", { className: "mt-4 grid grid-cols-[repeat(auto-fit,minmax(min(100%,9rem),1fr))] gap-3 text-sm", children: [
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.meta.module", "Module") }),
          /* @__PURE__ */ jsx("dd", { className: "mt-1 break-all font-mono text-xs", children: agent.moduleId })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.meta.id", "Agent id") }),
          /* @__PURE__ */ jsx("dd", { className: "mt-1 break-all font-mono text-xs", children: agent.id })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.meta.executionMode", "Execution mode") }),
          /* @__PURE__ */ jsx("dd", { className: "mt-1", children: /* @__PURE__ */ jsx(StatusBadge, { variant: executionModeStatusMap[agent.executionMode], children: agent.executionMode }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.meta.mutationPolicy", "Mutation policy") }),
          /* @__PURE__ */ jsx("dd", { className: "mt-1", children: /* @__PURE__ */ jsx(
            StatusBadge,
            {
              variant: mutationPolicyStatusMap[agent.mutationPolicy] ?? "neutral",
              dot: true,
              className: "max-w-full whitespace-normal break-all",
              children: agent.mutationPolicy
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.meta.readOnly", "Read-only") }),
          /* @__PURE__ */ jsx("dd", { className: "mt-1 text-xs", children: agent.readOnly ? t("ai_assistant.agents.meta.readOnlyYes", "Yes") : t("ai_assistant.agents.meta.readOnlyNo", "No") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.meta.maxSteps", "Max steps") }),
          /* @__PURE__ */ jsx("dd", { className: "mt-1 font-mono text-xs", children: agent.maxSteps ?? t("ai_assistant.agents.meta.unlimited", "Unlimited") })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx(AgentModelOverrideSection, { agent }),
    /* @__PURE__ */ jsx(MutationPolicySection, { agent }),
    /* @__PURE__ */ jsx(LoopPolicySection, { agent }),
    /* @__PURE__ */ jsxs(
      "section",
      {
        className: "rounded-lg border border-border bg-background p-4",
        "data-ai-agent-prompt-editor": agent.id,
        children: [
          /* @__PURE__ */ jsxs("header", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.prompt.title", "Prompt sections") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "ai_assistant.agents.prompt.subtitle",
                "Toggle any section to write an additive override. Saving stores a new tenant-scoped version; built-in section text is always preserved."
              ) })
            ] }),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => void handleSave(),
                disabled: isSaving || !hasAnyOverride,
                "data-ai-agent-prompt-save": true,
                children: [
                  isSaving ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Save, { className: "size-4", "aria-hidden": true }),
                  /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.prompt.save", "Save overrides") })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsxs(
            Alert,
            {
              variant: "info",
              icon: /* @__PURE__ */ jsx(Wand2, { "aria-hidden": "true" }),
              "data-ai-agent-prompt-notice": true,
              children: [
                /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.agents.override.noticeTitle", "Prompt overrides are additive") }),
                /* @__PURE__ */ jsx(AlertDescription, { children: t(
                  "ai_assistant.agents.override.noticeBody",
                  "Overrides append to the built-in sections \u2014 they never remove or replace shipped text. Saved versions are tenant-scoped and auditable from the history panel below."
                ) })
              ]
            }
          ) }),
          saveState.kind === "success" ? /* @__PURE__ */ jsxs(Alert, { variant: "success", className: "mt-3", "data-ai-agent-prompt-state": "success", children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: saveState.version > 0 ? t("ai_assistant.agents.override.savedTitle", "Prompt override saved") : t("ai_assistant.agents.prompt.pendingTitle", "Overrides accepted") }),
            /* @__PURE__ */ jsx(AlertDescription, { children: saveState.version > 0 ? `${saveState.message} ${t("ai_assistant.agents.override.versionLabel", "Version")} ${saveState.version}.` : saveState.message })
          ] }) : null,
          saveState.kind === "error" ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", className: "mt-3", "data-ai-agent-prompt-state": "error", children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.agents.override.errorTitle", "Failed to save prompt override") }),
            /* @__PURE__ */ jsx(AlertDescription, { children: saveState.message })
          ] }) : null,
          /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-col gap-3", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("span", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("ai_assistant.agents.prompt.fullSystemPromptLabel", "Full system prompt (default)") }),
              /* @__PURE__ */ jsx("pre", { className: "mt-2 max-h-40 overflow-auto rounded border border-border bg-muted/30 p-2 text-xs font-mono whitespace-pre-wrap", children: agent.systemPrompt })
            ] }),
            PROMPT_SECTION_IDS.map((sectionId) => /* @__PURE__ */ jsx(
              PromptSectionEditor,
              {
                sectionId,
                defaultText: sectionId === "role" ? agent.systemPrompt : t(
                  "ai_assistant.agents.prompt.defaultSectionPlaceholder",
                  "No default copy declared for this section \u2014 the agent ships a single systemPrompt. Override to inject additional text once Step 5.3 lands."
                ),
                overrideText: overrideDrafts[sectionId],
                override: overrideFlags[sectionId],
                onToggleOverride: (next) => {
                  setOverrideFlags((prev) => ({ ...prev, [sectionId]: next }));
                  if (next) {
                    setOverrideDrafts((prev) => {
                      if (prev[sectionId]) return prev;
                      const defaultText = sectionId === "role" ? agent.systemPrompt : "";
                      return { ...prev, [sectionId]: defaultText };
                    });
                  }
                },
                onOverrideChange: (next) => setOverrideDrafts((prev) => ({ ...prev, [sectionId]: next })),
                onSaveShortcut: () => void handleSave()
              },
              sectionId
            ))
          ] })
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      "section",
      {
        className: "rounded-lg border border-border bg-background p-4",
        "data-ai-agent-tools-list": agent.id,
        children: [
          /* @__PURE__ */ jsxs("header", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.tools.title", "Allowed tools") }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "ai_assistant.agents.tools.subtitle",
                "Read-only surface in Phase 2. Editing the per-tool toggle and mutation policy lands in Step 5.4 / Phase 3."
              ) })
            ] }),
            /* @__PURE__ */ jsx(Badge, { variant: "neutral", className: "font-mono text-xs", children: agent.tools.length })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "mt-3 flex flex-col gap-2", children: agent.tools.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
            "ai_assistant.agents.tools.emptyBody",
            "This agent declares no tools in its allowedTools whitelist."
          ) }) : agent.tools.map((tool) => /* @__PURE__ */ jsx(ToolRow, { tool }, tool.name)) })
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      "section",
      {
        className: "rounded-lg border border-border bg-background p-4",
        "data-ai-agent-override-history": agent.id,
        children: [
          /* @__PURE__ */ jsxs("header", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [
              /* @__PURE__ */ jsx(History, { className: "size-4 text-muted-foreground", "aria-hidden": true }),
              /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.override.history.title", "Prompt override history") }),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                  "ai_assistant.agents.override.history.subtitle",
                  "Newest first. Each save creates a new version scoped to the current tenant."
                ) })
              ] })
            ] }),
            overrideQuery.data ? /* @__PURE__ */ jsx(Badge, { variant: "neutral", className: "font-mono text-xs", children: overrideQuery.data.versions.length }) : null
          ] }),
          /* @__PURE__ */ jsx("div", { className: "mt-3 flex flex-col gap-2", children: overrideQuery.isLoading ? /* @__PURE__ */ jsx(
            SettingsLoading,
            {
              message: t(
                "ai_assistant.agents.override.history.loading",
                "Loading override history..."
              )
            }
          ) : overrideQuery.isError ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-override-history-error": true, children: [
            /* @__PURE__ */ jsx(AlertTitle, { children: t(
              "ai_assistant.agents.override.history.errorTitle",
              "Failed to load override history"
            ) }),
            /* @__PURE__ */ jsx(AlertDescription, { children: overrideQuery.error instanceof Error ? overrideQuery.error.message : String(overrideQuery.error) })
          ] }) : (overrideQuery.data?.versions ?? []).length === 0 ? /* @__PURE__ */ jsx(
            "p",
            {
              className: "text-xs text-muted-foreground",
              "data-ai-agent-override-history-empty": true,
              children: t(
                "ai_assistant.agents.override.history.empty",
                "No prompt overrides have been saved for this agent yet."
              )
            }
          ) : (overrideQuery.data?.versions ?? []).slice(0, 5).map((entry) => /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex flex-wrap items-center justify-between gap-3 rounded-md border border-border bg-background px-3 py-2",
              "data-ai-agent-override-history-row": entry.version,
              children: [
                /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-w-0", children: [
                  /* @__PURE__ */ jsxs("span", { className: "text-xs font-semibold", children: [
                    t("ai_assistant.agents.override.versionLabel", "Version"),
                    " ",
                    entry.version
                  ] }),
                  /* @__PURE__ */ jsx("span", { className: "truncate text-xs text-muted-foreground", children: new Date(entry.updatedAt).toLocaleString() })
                ] }),
                /* @__PURE__ */ jsxs(Badge, { variant: "neutral", className: "font-mono text-xs", children: [
                  Object.keys(entry.sections ?? {}).length,
                  " ",
                  t("ai_assistant.agents.override.history.sectionsLabel", "sections")
                ] })
              ]
            },
            entry.id
          )) })
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      "section",
      {
        className: "rounded-lg border border-border bg-background p-4",
        "data-ai-agent-attachments": agent.id,
        children: [
          /* @__PURE__ */ jsx("header", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3", children: /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("ai_assistant.agents.attachments.title", "Attachment policy") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
              "ai_assistant.agents.attachments.subtitle",
              "Accepted media types the agent declares. Read-only in Phase 2."
            ) })
          ] }) }),
          /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(AttachmentPolicyBadges, { mediaTypes: agent.acceptedMediaTypes }) })
        ]
      }
    )
  ] });
}
function AiAgentSettingsPageClient() {
  const t = useT();
  const [selectedAgentId, setSelectedAgentId] = React.useState(null);
  const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
    queryKey: ["ai_assistant", "agent_settings", "agents"],
    queryFn: fetchAgents
  });
  const agents = React.useMemo(() => data?.agents ?? [], [data]);
  React.useEffect(() => {
    if (!agents.length) {
      if (selectedAgentId !== null) setSelectedAgentId(null);
      return;
    }
    if (!selectedAgentId || !agents.some((agent) => agent.id === selectedAgentId)) {
      setSelectedAgentId(agents[0].id);
    }
  }, [agents, selectedAgentId]);
  const selectedAgent = React.useMemo(() => {
    if (!selectedAgentId) return null;
    return agents.find((agent) => agent.id === selectedAgentId) ?? null;
  }, [agents, selectedAgentId]);
  if (isLoading) {
    return /* @__PURE__ */ jsx(
      SettingsLoading,
      {
        message: t("ai_assistant.agents.loadingAgents", "Loading AI agents...")
      }
    );
  }
  if (isError) {
    return /* @__PURE__ */ jsxs(Alert, { variant: "destructive", "data-ai-agent-settings-error": true, children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.agents.loadErrorTitle", "Failed to load AI agents") }),
      /* @__PURE__ */ jsxs(AlertDescription, { children: [
        /* @__PURE__ */ jsx("span", { children: error instanceof Error ? error.message : String(error) }),
        /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            variant: "outline",
            onClick: () => {
              void refetch();
            },
            children: [
              /* @__PURE__ */ jsx(RefreshCcw, { className: "size-4", "aria-hidden": true }),
              /* @__PURE__ */ jsx("span", { children: t("ai_assistant.agents.retry", "Retry") })
            ]
          }
        ) })
      ] })
    ] });
  }
  if (!agents.length) {
    return /* @__PURE__ */ jsx(EmptyAgents, {});
  }
  return /* @__PURE__ */ jsx(TooltipProvider, { delayDuration: 200, children: /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-col gap-4", "data-ai-agent-settings": true, children: [
    /* @__PURE__ */ jsxs("header", { className: "flex min-w-0 flex-col gap-1", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("ai_assistant.agents.title", "AI Agents") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
        "ai_assistant.agents.subtitle",
        "Inspect every registered agent and manage tenant-scoped additive prompt-section overrides."
      ) })
    ] }),
    /* @__PURE__ */ jsx(
      "section",
      {
        className: "flex flex-col gap-3 rounded-lg border border-border bg-background p-3",
        "data-ai-agent-settings-picker-wrap": true,
        children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-end justify-between gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex min-w-[min(100%,16rem)] flex-1 flex-col gap-2", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "ai-agent-settings-picker", children: t("ai_assistant.agents.agentPickerLabel", "Agent") }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: selectedAgentId ?? "",
                onValueChange: (value) => setSelectedAgentId(value),
                children: [
                  /* @__PURE__ */ jsx(
                    SelectTrigger,
                    {
                      id: "ai-agent-settings-picker",
                      "data-ai-agent-settings-picker": true,
                      className: "w-full min-w-0",
                      children: /* @__PURE__ */ jsx(SelectValue, {})
                    }
                  ),
                  /* @__PURE__ */ jsx(SelectContent, { children: agents.map((agent) => /* @__PURE__ */ jsxs(SelectItem, { value: agent.id, children: [
                    agent.label,
                    " (",
                    agent.id,
                    ")"
                  ] }, agent.id)) })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 sm:flex-shrink-0", children: /* @__PURE__ */ jsx(
            IconButton,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => {
                void refetch();
              },
              "aria-label": t("ai_assistant.agents.refresh", "Refresh agents"),
              disabled: isFetching,
              children: /* @__PURE__ */ jsx(RefreshCcw, { className: "size-4", "aria-hidden": true })
            }
          ) })
        ] })
      }
    ),
    selectedAgent ? /* @__PURE__ */ jsx(AgentDetailPanel, { agent: selectedAgent }) : null
  ] }) });
}
var AiAgentSettingsPageClient_default = AiAgentSettingsPageClient;
export {
  AiAgentSettingsPageClient,
  AiAgentSettingsPageClient_default as default
};
//# sourceMappingURL=AiAgentSettingsPageClient.js.map
