"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Bot, Loader2, CheckCircle2, XCircle, ChevronDown, ChevronRight, Server, Wrench, Eye, EyeOff, Database, Link2, Settings, Key, X } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { AI_ASSISTANT_LAUNCHER_OPEN_EVENT } from "@open-mercato/ui/ai/AiAssistantLauncher";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { Button } from "@open-mercato/ui/primitives/button";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@open-mercato/ui/primitives/select";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useAiAssistantVisibility } from "../../../frontend/hooks/useAiAssistantVisibility.js";
import McpConfigDialog from "./McpConfigDialog.js";
import SessionKeyDialog from "./SessionKeyDialog.js";
const LEGACY_AI_ASSISTANT_OPEN_EVENT = "om:open-ai-chat";
async function fetchHealth() {
  const result = await apiCall("/api/ai_assistant/health");
  if (!result.ok || !result.result) throw new Error("Failed to fetch health");
  return result.result;
}
async function fetchSettings() {
  const result = await apiCall("/api/ai_assistant/settings");
  if (!result.ok || !result.result) throw new Error("Failed to fetch settings");
  return result.result;
}
async function fetchTools() {
  const result = await apiCall("/api/ai_assistant/tools");
  if (!result.ok || !result.result) throw new Error("Failed to fetch tools");
  return result.result;
}
function GlobalOverrideForm({
  availableProviders,
  tenantOverride,
  onSaved
}) {
  const t = useT();
  const [selectedProviderId, setSelectedProviderId] = React.useState(
    tenantOverride?.providerId ?? ""
  );
  const [selectedModelId, setSelectedModelId] = React.useState(
    tenantOverride?.modelId ?? ""
  );
  const selectedProvider = availableProviders.find((p) => p.id === selectedProviderId);
  const { runMutation: runSaveMutation } = useGuardedMutation({ contextId: "ai-settings-save-override" });
  const { runMutation: runClearMutation } = useGuardedMutation({ contextId: "ai-settings-clear-override" });
  const [isSaving, setIsSaving] = React.useState(false);
  const [isClearing, setIsClearing] = React.useState(false);
  const handleSave = React.useCallback(async () => {
    setIsSaving(true);
    try {
      await runSaveMutation({
        operation: async () => {
          const result = await apiCall("/api/ai_assistant/settings", {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              providerId: selectedProviderId || null,
              modelId: selectedModelId || null
            })
          });
          if (!result.ok) {
            const err = result.result?.error;
            throw new Error(err ?? t("ai_assistant.settings.saveError", "Failed to save override."));
          }
        },
        context: {}
      });
      flash(t("ai_assistant.settings.saveSuccess", "Default model override saved."), "success");
      onSaved();
    } finally {
      setIsSaving(false);
    }
  }, [onSaved, runSaveMutation, selectedModelId, selectedProviderId, t]);
  const handleClear = React.useCallback(async () => {
    setIsClearing(true);
    try {
      await runClearMutation({
        operation: async () => {
          const result = await apiCall("/api/ai_assistant/settings", {
            method: "DELETE",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({})
          });
          if (!result.ok) {
            const err = result.result?.error;
            throw new Error(err ?? t("ai_assistant.settings.clearError", "Failed to clear override."));
          }
        },
        context: {}
      });
      flash(t("ai_assistant.settings.clearSuccess", "Default model override cleared."), "success");
      setSelectedProviderId("");
      setSelectedModelId("");
      onSaved();
    } finally {
      setIsClearing(false);
    }
  }, [runClearMutation, onSaved, t]);
  const isBusy = isSaving || isClearing;
  const configuredProviders = availableProviders.filter((p) => p.configured);
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", "data-ai-settings-override-form": "", children: [
    /* @__PURE__ */ jsx("h2", { className: "mb-1 text-sm font-semibold", children: t("ai_assistant.settings.defaultOverrideTitle", "Default model override") }),
    /* @__PURE__ */ jsx("p", { className: "mb-4 text-xs text-muted-foreground", children: t(
      "ai_assistant.settings.defaultOverrideDescription",
      "Set a tenant-wide default provider and model. Agents with a per-agent override or specific defaultModel will take precedence."
    ) }),
    tenantOverride && (tenantOverride.providerId || tenantOverride.modelId) ? /* @__PURE__ */ jsxs("div", { className: "mb-4 flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-xs", children: [
      /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("ai_assistant.settings.currentOverride", "Current override:") }),
      /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
        tenantOverride.providerId ?? "\u2014",
        " / ",
        tenantOverride.modelId ?? "\u2014"
      ] }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: "ml-auto h-6 gap-1 text-xs",
          disabled: isBusy,
          onClick: handleClear,
          "data-ai-settings-clear-override": "",
          children: [
            /* @__PURE__ */ jsx(X, { className: "size-3", "aria-hidden": true }),
            t("ai_assistant.settings.clearOverride", "Clear override")
          ]
        }
      )
    ] }) : null,
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-end gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
        /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-muted-foreground", children: t("ai_assistant.settings.providerLabel", "Provider") }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: selectedProviderId,
            onValueChange: (val) => {
              setSelectedProviderId(val);
              setSelectedModelId("");
            },
            disabled: isBusy,
            children: [
              /* @__PURE__ */ jsx(
                SelectTrigger,
                {
                  className: "w-[180px]",
                  "data-ai-settings-provider-select": "",
                  children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("ai_assistant.settings.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 flex-col gap-1", children: [
        /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-muted-foreground", children: t("ai_assistant.settings.modelLabel", "Model") }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: selectedModelId,
            onValueChange: setSelectedModelId,
            disabled: isBusy || !selectedProviderId,
            children: [
              /* @__PURE__ */ jsx(
                SelectTrigger,
                {
                  className: "w-[220px]",
                  "data-ai-settings-model-select": "",
                  children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("ai_assistant.settings.selectModel", "Select model") })
                }
              ),
              /* @__PURE__ */ jsx(SelectContent, { children: (selectedProvider?.defaultModels ?? []).map((model) => /* @__PURE__ */ jsx(SelectItem, { value: model.id, children: model.name }, model.id)) })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          size: "sm",
          disabled: isBusy || !selectedProviderId || !selectedModelId,
          onClick: handleSave,
          "data-ai-settings-save-override": "",
          children: [
            isSaving ? /* @__PURE__ */ jsx(Loader2, { className: "size-3.5 animate-spin", "aria-hidden": true }) : null,
            t("ai_assistant.settings.saveOverride", "Save override")
          ]
        }
      )
    ] })
  ] });
}
function PerAgentOverrideList({
  agents,
  onCleared
}) {
  const t = useT();
  const { runMutation: runClearAgentMutation } = useGuardedMutation({ contextId: "ai-settings-clear-agent-override" });
  const [clearingAgentId, setClearingAgentId] = React.useState(null);
  const handleClearAgentOverride = React.useCallback(
    async (agentId) => {
      setClearingAgentId(agentId);
      try {
        await runClearAgentMutation({
          operation: async () => {
            const result = await apiCall("/api/ai_assistant/settings", {
              method: "DELETE",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ agentId })
            });
            if (!result.ok) {
              const err = result.result?.error;
              throw new Error(err ?? t("ai_assistant.settings.clearAgentError", "Failed to clear agent override."));
            }
          },
          context: {}
        });
        flash(t("ai_assistant.settings.clearAgentSuccess", "Agent override cleared."), "success");
        onCleared();
      } finally {
        setClearingAgentId(null);
      }
    },
    [runClearAgentMutation, onCleared, t]
  );
  if (agents.length === 0) return null;
  const overriddenAgents = agents.filter((agent) => agent.source !== "env_default" && agent.source !== "provider_default");
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", "data-ai-settings-agent-overrides": "", children: [
    /* @__PURE__ */ jsx("h2", { className: "mb-1 text-sm font-semibold", children: t("ai_assistant.settings.agentOverridesTitle", "Per-agent model resolution") }),
    /* @__PURE__ */ jsx("p", { className: "mb-4 text-xs text-muted-foreground", children: t(
      "ai_assistant.settings.agentOverridesDescription",
      "Resolved model for each registered agent. Agents with a custom override show a Clear button."
    ) }),
    /* @__PURE__ */ jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-xs", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-border text-left text-muted-foreground", children: [
        /* @__PURE__ */ jsx("th", { className: "pb-2 pr-4 font-medium", children: t("ai_assistant.settings.agentIdColumn", "Agent") }),
        /* @__PURE__ */ jsx("th", { className: "pb-2 pr-4 font-medium", children: t("ai_assistant.settings.providerColumn", "Provider") }),
        /* @__PURE__ */ jsx("th", { className: "pb-2 pr-4 font-medium", children: t("ai_assistant.settings.modelColumn", "Model") }),
        /* @__PURE__ */ jsx("th", { className: "pb-2 pr-4 font-medium", children: t("ai_assistant.settings.sourceColumn", "Source") }),
        /* @__PURE__ */ jsx("th", { className: "pb-2 font-medium" })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: agents.map((agent) => {
        const hasOverride = overriddenAgents.some((a) => a.agentId === agent.agentId);
        return /* @__PURE__ */ jsxs(
          "tr",
          {
            className: "border-b border-border/50 last:border-0",
            "data-ai-settings-agent-row": agent.agentId,
            children: [
              /* @__PURE__ */ jsx("td", { className: "py-2 pr-4 font-mono", children: agent.agentId }),
              /* @__PURE__ */ jsx("td", { className: "py-2 pr-4", children: agent.providerId }),
              /* @__PURE__ */ jsx("td", { className: "py-2 pr-4", children: agent.modelId }),
              /* @__PURE__ */ jsx("td", { className: "py-2 pr-4 text-muted-foreground", children: agent.source }),
              /* @__PURE__ */ jsx("td", { className: "py-2", children: hasOverride ? /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  className: "h-6 gap-1 text-xs",
                  disabled: clearingAgentId !== null,
                  onClick: () => void handleClearAgentOverride(agent.agentId),
                  "data-ai-settings-clear-agent-override": agent.agentId,
                  children: [
                    /* @__PURE__ */ jsx(X, { className: "size-3", "aria-hidden": true }),
                    t("ai_assistant.settings.clearOverride", "Clear override")
                  ]
                }
              ) : null })
            ]
          },
          agent.agentId
        );
      }) })
    ] }) })
  ] });
}
function AiAssistantLauncherCard({
  launchMode,
  showVisibilityControl
}) {
  const t = useT();
  const { isEnabled, toggleEnabled, isLoaded } = useAiAssistantVisibility();
  const openAiAssistant = () => {
    const eventName = launchMode === "legacy" ? LEGACY_AI_ASSISTANT_OPEN_EVENT : AI_ASSISTANT_LAUNCHER_OPEN_EVENT;
    window.dispatchEvent(new CustomEvent(eventName));
  };
  return /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-6", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsxs("h2", { className: "flex items-center gap-2 text-lg font-semibold", children: [
        /* @__PURE__ */ jsx(Bot, { className: "size-5" }),
        t("ai_assistant.settings.visibilityTitle", "AI Assistant")
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: showVisibilityControl ? isEnabled ? t("ai_assistant.settings.visibilityEnabled", "Visible in header with Cmd+J shortcut enabled.") : t("ai_assistant.settings.visibilityDisabled", "Hidden from header. Enable to show the button and Cmd+J shortcut.") : t("ai_assistant.settings.launchDescription", "Open the AI assistant from this page.") })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
      showVisibilityControl ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-md border bg-muted/30 px-4 py-2", children: [
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: t("ai_assistant.settings.visibilityToggleLabel", "Visibility") }),
        isEnabled ? /* @__PURE__ */ jsx(Eye, { className: "size-4 text-muted-foreground" }) : /* @__PURE__ */ jsx(EyeOff, { className: "size-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(
          Switch,
          {
            checked: isEnabled,
            onCheckedChange: toggleEnabled,
            disabled: !isLoaded
          }
        )
      ] }) : null,
      /* @__PURE__ */ jsxs(Button, { type: "button", onClick: openAiAssistant, size: "default", className: "gap-2", children: [
        /* @__PURE__ */ jsx(Bot, { className: "size-4" }),
        launchMode === "legacy" ? t("ai_assistant.settings.openButton", "Open AI Assistant") : t("ai_assistant.settings.openSelectorButton", "Open AI assistants")
      ] })
    ] })
  ] }) });
}
function AiAssistantSettingsContent({
  launchMode,
  showVisibilityControl
}) {
  const t = useT();
  const queryClient = useQueryClient();
  const [toolsExpanded, setToolsExpanded] = React.useState(false);
  const [mcpConfigOpen, setMcpConfigOpen] = React.useState(false);
  const [sessionKeyOpen, setSessionKeyOpen] = React.useState(false);
  const healthQuery = useQuery({
    queryKey: ["ai-assistant", "health"],
    queryFn: fetchHealth,
    refetchInterval: 1e4,
    staleTime: 5e3
  });
  const settingsQuery = useQuery({
    queryKey: ["ai-assistant", "settings"],
    queryFn: fetchSettings,
    staleTime: 6e4
  });
  const toolsQuery = useQuery({
    queryKey: ["ai-assistant", "tools"],
    queryFn: fetchTools,
    staleTime: 6e4
  });
  const handleOverrideSaved = React.useCallback(() => {
    void queryClient.invalidateQueries({ queryKey: ["ai-assistant", "settings"] });
  }, [queryClient]);
  const isLoading = healthQuery.isLoading || settingsQuery.isLoading || toolsQuery.isLoading;
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 py-8 text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin" }),
      t("ai_assistant.settings.loading", "Loading settings...")
    ] });
  }
  const health = healthQuery.data;
  const settings = settingsQuery.data;
  const tools = toolsQuery.data?.tools ?? [];
  const toolsByModule = tools.reduce((acc, tool) => {
    const module = tool.module || "other";
    if (!acc[module]) acc[module] = [];
    acc[module].push(tool);
    return acc;
  }, {});
  const provider = settings?.provider;
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-6", "data-ai-assistant-settings": "", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsxs("h1", { className: "flex items-center gap-2 text-2xl font-bold", children: [
        /* @__PURE__ */ jsx(Bot, { className: "size-6" }),
        t("ai_assistant.settings.pageTitle", "AI Assistant Settings")
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t("ai_assistant.settings.pageDescription", "Configure and monitor the AI assistant") })
    ] }),
    /* @__PURE__ */ jsx(
      AiAssistantLauncherCard,
      {
        launchMode,
        showVisibilityControl
      }
    ),
    settings ? /* @__PURE__ */ jsx(
      GlobalOverrideForm,
      {
        availableProviders: settings.availableProviders,
        tenantOverride: settings.tenantOverride,
        onSaved: handleOverrideSaved
      }
    ) : null,
    settings?.agents && settings.agents.length > 0 ? /* @__PURE__ */ jsx(
      PerAgentOverrideList,
      {
        agents: settings.agents,
        onCleared: handleOverrideSaved
      }
    ) : null,
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "mb-4 flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs("h2", { className: "flex items-center gap-2 text-sm font-semibold", children: [
          /* @__PURE__ */ jsx(Link2, { className: "size-4" }),
          t("ai_assistant.settings.connectionsTitle", "Connections")
        ] }),
        healthQuery.isFetching && !healthQuery.isLoading ? /* @__PURE__ */ jsx(Loader2, { className: "size-3 animate-spin text-muted-foreground" }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-3", children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: `rounded-lg border-2 p-4 ${health?.status === "ok" && health.opencode?.healthy ? "border-status-success-border bg-status-success-bg" : "border-destructive/50 bg-destructive/5"}`,
            children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
              /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(Server, { className: "size-4 shrink-0 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "OpenCode" })
                ] }),
                /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: health?.status === "ok" && health.opencode?.healthy ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-status-success-text", children: [
                  /* @__PURE__ */ jsx(CheckCircle2, { className: "size-3" }),
                  t("ai_assistant.settings.connected", "Connected")
                ] }) : /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-destructive", children: [
                  /* @__PURE__ */ jsx(XCircle, { className: "size-3" }),
                  health?.message ?? t("ai_assistant.settings.disconnected", "Disconnected")
                ] }) }),
                health?.opencode?.version ? /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
                  "v",
                  health.opencode.version
                ] }) : null,
                /* @__PURE__ */ jsx("p", { className: "mt-1 truncate text-xs text-muted-foreground", children: health?.url ?? t("ai_assistant.settings.notConfigured", "Not configured") })
              ] }),
              health?.status === "ok" && health.opencode?.healthy ? /* @__PURE__ */ jsx("div", { className: "flex size-5 shrink-0 items-center justify-center rounded-full bg-status-success-bg text-status-success-icon", children: /* @__PURE__ */ jsx("svg", { className: "size-3", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 3, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 13l4 4L19 7" }) }) }) : null
            ] })
          }
        ),
        (() => {
          const mcpConnected = health?.mcp && Object.values(health.mcp).some((s) => s.status === "connected");
          const mcpConnecting = health?.mcp && Object.values(health.mcp).some((s) => s.status === "connecting");
          const mcpError = health?.mcp && Object.values(health.mcp).find((s) => s.error)?.error;
          return /* @__PURE__ */ jsx(
            "div",
            {
              className: `rounded-lg border-2 p-4 ${mcpConnected ? "border-status-success-border bg-status-success-bg" : mcpConnecting ? "border-status-warning-border bg-status-warning-bg" : "border-destructive/50 bg-destructive/5"}`,
              children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
                /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                    /* @__PURE__ */ jsx(Wrench, { className: "size-4 shrink-0 text-muted-foreground" }),
                    /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "MCP Server" })
                  ] }),
                  /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: mcpConnected ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-status-success-text", children: [
                    /* @__PURE__ */ jsx(CheckCircle2, { className: "size-3" }),
                    t("ai_assistant.settings.connected", "Connected")
                  ] }) : mcpConnecting ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-status-warning-text", children: [
                    /* @__PURE__ */ jsx(Loader2, { className: "size-3 animate-spin" }),
                    t("ai_assistant.settings.connecting", "Connecting...")
                  ] }) : /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-destructive", children: [
                    /* @__PURE__ */ jsx(XCircle, { className: "size-3" }),
                    mcpError ?? t("ai_assistant.settings.disconnected", "Disconnected")
                  ] }) }),
                  /* @__PURE__ */ jsx("p", { className: "mt-1 truncate text-xs text-muted-foreground", children: health?.mcpUrl ?? t("ai_assistant.settings.notConfigured", "Not configured") })
                ] }),
                mcpConnected ? /* @__PURE__ */ jsx("div", { className: "flex size-5 shrink-0 items-center justify-center rounded-full bg-status-success-bg text-status-success-icon", children: /* @__PURE__ */ jsx("svg", { className: "size-3", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 3, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 13l4 4L19 7" }) }) }) : null
              ] })
            }
          );
        })(),
        /* @__PURE__ */ jsx(
          "div",
          {
            className: `rounded-lg border-2 p-4 ${health?.search?.available ? "border-status-success-border bg-status-success-bg" : "border-destructive/50 bg-destructive/5"}`,
            children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
              /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx(Database, { className: "size-4 shrink-0 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Meilisearch" })
                ] }),
                /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: health?.search?.available ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-status-success-text", children: [
                  /* @__PURE__ */ jsx(CheckCircle2, { className: "size-3" }),
                  t("ai_assistant.settings.connected", "Connected")
                ] }) : /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-destructive", children: [
                  /* @__PURE__ */ jsx(XCircle, { className: "size-3" }),
                  t("ai_assistant.settings.notAvailable", "Not available")
                ] }) }),
                /* @__PURE__ */ jsx("p", { className: "mt-1 truncate text-xs text-muted-foreground", children: health?.search?.url ?? t("ai_assistant.settings.notConfigured", "Not configured") })
              ] }),
              health?.search?.available ? /* @__PURE__ */ jsx("div", { className: "flex size-5 shrink-0 items-center justify-center rounded-full bg-status-success-bg text-status-success-icon", children: /* @__PURE__ */ jsx("svg", { className: "size-3", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 3, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 13l4 4L19 7" }) }) }) : null
            ] })
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-4 rounded-md border bg-muted/30 p-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
          /* @__PURE__ */ jsx(Key, { className: "size-4 text-muted-foreground" }),
          /* @__PURE__ */ jsx("span", { className: "font-medium", children: t("ai_assistant.settings.mcpAuthLabel", "MCP Authentication:") }),
          settings?.mcpKeyConfigured ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-xs text-status-success-text", children: [
            /* @__PURE__ */ jsx(CheckCircle2, { className: "size-3" }),
            t("ai_assistant.settings.mcpKeyConfigured", "MCP_SERVER_API_KEY configured")
          ] }) : /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-xs text-status-warning-text", children: [
            /* @__PURE__ */ jsx(XCircle, { className: "size-3" }),
            t("ai_assistant.settings.mcpKeyMissing", "MCP_SERVER_API_KEY not set")
          ] })
        ] }),
        /* @__PURE__ */ jsx("p", { className: "ml-6 mt-1 text-xs text-muted-foreground", children: t(
          "ai_assistant.settings.mcpAuthNote",
          "Required for AI to access platform tools via MCP server."
        ) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "mt-4 rounded-md border bg-muted/30 p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
        /* @__PURE__ */ jsx(Server, { className: "size-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: t("ai_assistant.settings.llmProviderLabel", "LLM Provider:") }),
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: provider?.name ?? "Anthropic" }),
        provider?.configured ? /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-xs text-status-success-text", children: [
          /* @__PURE__ */ jsx(CheckCircle2, { className: "size-3" }),
          provider?.envKey ? t("ai_assistant.settings.envKeyConfigured", "{{key}} configured", { key: provider.envKey }) : t("ai_assistant.settings.configured", "Configured")
        ] }) : /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 text-xs text-status-warning-text", children: [
          /* @__PURE__ */ jsx(XCircle, { className: "size-3" }),
          t("ai_assistant.settings.envKeyMissing", "{{key}} not set", { key: provider?.envKey ?? "ANTHROPIC_API_KEY" })
        ] })
      ] }) }),
      /* @__PURE__ */ jsx("p", { className: "mt-4 text-xs text-muted-foreground", children: t(
        "ai_assistant.settings.meilisearchNote",
        "Meilisearch is required for API endpoint discovery. Endpoints are indexed automatically when the MCP server starts."
      ) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
      /* @__PURE__ */ jsxs("h2", { className: "mb-4 flex items-center gap-2 text-sm font-semibold", children: [
        /* @__PURE__ */ jsx(Settings, { className: "size-4" }),
        t("ai_assistant.settings.developerToolsTitle", "Developer Tools")
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
        /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-muted/30 p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsx("div", { className: "rounded-md bg-primary/10 p-2", children: /* @__PURE__ */ jsx(Settings, { className: "size-5 text-primary" }) }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium", children: t("ai_assistant.settings.mcpConfigTitle", "MCP Configuration") }),
            /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: t(
              "ai_assistant.settings.mcpConfigDescription",
              "Generate config for Claude Code or other MCP clients."
            ) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                size: "sm",
                variant: "outline",
                className: "mt-3",
                onClick: () => setMcpConfigOpen(true),
                children: t("ai_assistant.settings.generateMcpConfig", "Generate MCP Config")
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-muted/30 p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsx("div", { className: "rounded-md bg-primary/10 p-2", children: /* @__PURE__ */ jsx(Key, { className: "size-5 text-primary" }) }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium", children: t("ai_assistant.settings.sessionKeyTitle", "Session API Key") }),
            /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: t(
              "ai_assistant.settings.sessionKeyDescription",
              "Generate a temporary token for programmatic LLM access. Expires after 2 hours."
            ) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                size: "sm",
                variant: "outline",
                className: "mt-3",
                onClick: () => setSessionKeyOpen(true),
                children: t("ai_assistant.settings.generateSessionKey", "Generate Session Key")
              }
            )
          ] })
        ] }) })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      McpConfigDialog,
      {
        open: mcpConfigOpen,
        onOpenChange: setMcpConfigOpen,
        mcpUrl: health?.mcpUrl ?? "http://localhost:3001"
      }
    ),
    /* @__PURE__ */ jsx(
      SessionKeyDialog,
      {
        open: sessionKeyOpen,
        onOpenChange: setSessionKeyOpen
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
      /* @__PURE__ */ jsxs(
        "button",
        {
          type: "button",
          onClick: () => setToolsExpanded((prev) => !prev),
          className: "flex w-full items-center justify-between text-left",
          children: [
            /* @__PURE__ */ jsxs("h2", { className: "flex items-center gap-2 text-sm font-semibold", children: [
              /* @__PURE__ */ jsx(Wrench, { className: "size-4" }),
              t("ai_assistant.settings.mcpToolsTitle", "MCP Tools"),
              " (",
              tools.length,
              " ",
              t("ai_assistant.settings.mcpToolsCount", "tools"),
              ")"
            ] }),
            toolsExpanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "size-4 text-muted-foreground" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "size-4 text-muted-foreground" })
          ]
        }
      ),
      toolsExpanded ? /* @__PURE__ */ jsx("div", { className: "mt-4 space-y-4", children: Object.entries(toolsByModule).map(([module, moduleTools]) => /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-xs font-medium uppercase tracking-wider text-muted-foreground", children: module }),
        /* @__PURE__ */ jsx("div", { className: "space-y-1", children: moduleTools.map((tool) => /* @__PURE__ */ jsxs("div", { className: "border-l-2 border-muted py-1 pl-2", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: tool.name }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: tool.description })
        ] }, tool.name)) })
      ] }, module)) }) : null
    ] })
  ] });
}
function AiAssistantSettingsPageClient({
  launchMode = "selector",
  showVisibilityControl = false
}) {
  return /* @__PURE__ */ jsx(
    AiAssistantSettingsContent,
    {
      launchMode,
      showVisibilityControl
    }
  );
}
var AiAssistantSettingsPageClient_default = AiAssistantSettingsPageClient;
export {
  AiAssistantSettingsPageClient,
  AiAssistantSettingsPageClient_default as default
};
//# sourceMappingURL=AiAssistantSettingsPageClient.js.map
