"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { createPortal } from "react-dom";
import { Command } from "cmdk";
import { Loader2, Send, Square } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { Button } from "@open-mercato/ui/primitives/button";
import { Dialog, DialogContent, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
import { useCommandPaletteContext } from "./CommandPaletteProvider.js";
import { CommandInput } from "./CommandInput.js";
import { CommandHeader } from "./CommandHeader.js";
import { CommandFooter } from "./CommandFooter.js";
import { ToolChatPage } from "./ToolChatPage.js";
import { DebugPanel } from "./DebugPanel.js";
function IdleState() {
  return /* @__PURE__ */ jsxs("div", { className: "py-8 px-4 text-center text-muted-foreground", children: [
    /* @__PURE__ */ jsx("p", { className: "mb-2", children: "Ask me anything or describe what you want to do." }),
    /* @__PURE__ */ jsx("p", { className: "text-sm", children: "Examples:" }),
    /* @__PURE__ */ jsxs("ul", { className: "text-sm mt-2 space-y-1", children: [
      /* @__PURE__ */ jsx("li", { children: '"Search for customers in New York"' }),
      /* @__PURE__ */ jsx("li", { children: '"Create a new product"' }),
      /* @__PURE__ */ jsx("li", { children: '"Show me recent orders"' })
    ] })
  ] });
}
function RoutingIndicator() {
  return /* @__PURE__ */ jsxs("div", { className: "py-8 flex items-center justify-center gap-2", children: [
    /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
    /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "Analyzing request..." })
  ] });
}
function CommandPalette() {
  const {
    state,
    isThinking,
    agentStatus,
    isSessionAuthorized,
    messages,
    pendingToolCalls,
    selectedTool,
    close,
    setInputValue,
    handleSubmit,
    reset,
    sendAgenticMessage,
    stopExecution,
    approveToolCall,
    rejectToolCall,
    debugEvents,
    showDebug,
    setShowDebug,
    clearDebugEvents,
    pendingQuestion,
    answerQuestion
  } = useCommandPaletteContext();
  const {
    isOpen,
    phase,
    inputValue,
    isLoading,
    isStreaming,
    connectionStatus
  } = state;
  const [localInput, setLocalInput] = React.useState("");
  const [chatInput, setChatInput] = React.useState("");
  const chatInputRef = React.useRef(null);
  React.useEffect(() => {
    if (phase === "idle") {
      setLocalInput("");
      setChatInput("");
    }
  }, [phase]);
  React.useEffect(() => {
    if (phase === "chatting" || phase === "confirming" || phase === "executing") {
      setTimeout(() => chatInputRef.current?.focus(), 50);
    }
  }, [phase]);
  const handleOpenChange = (open) => {
    if (!open) {
      close();
    }
  };
  const handleInputSubmit = async () => {
    const query = localInput.trim();
    if (!query) return;
    setLocalInput("");
    await handleSubmit(query);
  };
  const handleKeyDown = (e) => {
    if (e.key === "Enter" && phase === "idle" && localInput.trim()) {
      e.preventDefault();
      handleInputSubmit();
    }
  };
  const handleChatSubmit = async (e) => {
    e.preventDefault();
    if (!chatInput.trim() || isStreaming) return;
    const content = chatInput;
    setChatInput("");
    await sendAgenticMessage(content);
  };
  const handleChatKeyDown = (e) => {
    if (e.key === "Escape") {
      e.stopPropagation();
    }
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      if (chatInput.trim() && !isStreaming) {
        const content = chatInput;
        setChatInput("");
        sendAgenticMessage(content);
      }
    }
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    isOpen && showDebug && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-overlay bg-black/50 backdrop-blur-sm pointer-events-none" }),
    /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: handleOpenChange, modal: !showDebug, children: /* @__PURE__ */ jsxs(
      DialogContent,
      {
        className: cn(
          "fixed left-1/2 top-[10vh] z-modal -translate-x-1/2",
          "w-full max-w-2xl p-0",
          "rounded-xl border bg-background shadow-2xl",
          "flex flex-col"
        ),
        style: { maxHeight: 500, overflow: "hidden" },
        onKeyDown: handleKeyDown,
        onPointerDownOutside: (e) => {
          if (showDebug) {
            e.preventDefault();
          }
        },
        onInteractOutside: (e) => {
          if (showDebug) {
            e.preventDefault();
          }
        },
        children: [
          /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(DialogTitle, { children: "AI Command Palette" }) }),
          /* @__PURE__ */ jsxs(Command, { className: "flex flex-col flex-1 min-h-0", shouldFilter: false, children: [
            /* @__PURE__ */ jsx(
              CommandHeader,
              {
                phase,
                selectedTool,
                onBack: reset
              }
            ),
            phase === "idle" && /* @__PURE__ */ jsx(
              CommandInput,
              {
                value: localInput,
                onValueChange: setLocalInput,
                mode: "commands",
                isLoading,
                placeholder: "Ask me anything or describe what you want to do..."
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "flex-1 min-h-0 overflow-y-auto", children: [
              phase === "idle" && !localInput && /* @__PURE__ */ jsx(IdleState, {}),
              phase === "routing" && /* @__PURE__ */ jsx(RoutingIndicator, {}),
              (phase === "chatting" || phase === "confirming" || phase === "executing") && /* @__PURE__ */ jsx(
                ToolChatPage,
                {
                  tool: selectedTool,
                  messages,
                  pendingToolCalls,
                  isStreaming,
                  isThinking,
                  agentStatus,
                  onApproveToolCall: approveToolCall,
                  onRejectToolCall: rejectToolCall,
                  pendingQuestion,
                  onAnswerQuestion: answerQuestion
                }
              )
            ] }),
            (phase === "chatting" || phase === "confirming" || phase === "executing") && /* @__PURE__ */ jsx("form", { onSubmit: handleChatSubmit, className: "shrink-0 border-t p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  ref: chatInputRef,
                  type: "text",
                  value: chatInput,
                  onChange: (e) => setChatInput(e.target.value),
                  onKeyDown: handleChatKeyDown,
                  placeholder: "Describe what you want to do...",
                  className: cn(
                    "flex-1 bg-muted rounded-lg px-4 py-2 text-sm outline-none",
                    "focus-visible:ring-2 focus-visible:ring-ring",
                    "disabled:opacity-50"
                  ),
                  disabled: isStreaming
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: isStreaming ? "button" : "submit",
                  size: "icon",
                  variant: isStreaming ? "destructive" : "default",
                  onClick: isStreaming ? stopExecution : void 0,
                  disabled: !isStreaming && !chatInput.trim(),
                  children: isStreaming ? /* @__PURE__ */ jsx(Square, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Send, { className: "h-4 w-4" })
                }
              )
            ] }) }),
            /* @__PURE__ */ jsx(
              CommandFooter,
              {
                phase,
                connectionStatus,
                isSessionAuthorized,
                showDebug,
                onToggleDebug: () => setShowDebug(!showDebug)
              }
            )
          ] })
        ]
      }
    ) }),
    isOpen && showDebug && typeof document !== "undefined" && createPortal(
      /* @__PURE__ */ jsx(
        "div",
        {
          "data-debug-panel": true,
          className: "fixed z-top bg-gray-900 rounded-xl border border-gray-700 shadow-2xl flex flex-col overflow-hidden",
          style: { top: "80px", right: "20px", width: "400px", minWidth: "400px", maxWidth: "400px", maxHeight: "calc(100vh - 100px)" },
          children: /* @__PURE__ */ jsx(
            DebugPanel,
            {
              events: debugEvents,
              onClear: clearDebugEvents,
              isOpen: true,
              onToggle: () => setShowDebug(false)
            }
          )
        }
      ),
      document.body
    )
  ] });
}
export {
  CommandPalette
};
//# sourceMappingURL=CommandPalette.js.map
