"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,
  X,
  Minimize2,
  PanelRight,
  PanelLeft,
  PanelBottom,
  MessageCircle
} from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { Button } from "@open-mercato/ui/primitives/button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useCommandPaletteContext } from "../CommandPalette/CommandPaletteProvider.js";
import { CommandInput } from "../CommandPalette/CommandInput.js";
import { CommandHeader } from "../CommandPalette/CommandHeader.js";
import { CommandFooter } from "../CommandPalette/CommandFooter.js";
import { ToolChatPage } from "../CommandPalette/ToolChatPage.js";
import { DebugPanel } from "../CommandPalette/DebugPanel.js";
import { AiDot } from "../AiDot/index.js";
import { useDockPosition } from "../../hooks/useDockPosition.js";
function IdleState() {
  const t = useT();
  return /* @__PURE__ */ jsxs("div", { className: "py-8 px-4 text-center text-muted-foreground", children: [
    /* @__PURE__ */ jsx("p", { className: "mb-2", children: t("ai_assistant.chat.idleTitle") }),
    /* @__PURE__ */ jsx("p", { className: "text-sm", children: t("ai_assistant.chat.idleExamples") }),
    /* @__PURE__ */ jsxs("ul", { className: "text-sm mt-2 space-y-1", children: [
      /* @__PURE__ */ jsxs("li", { children: [
        '"',
        t("ai_assistant.chat.example.search"),
        '"'
      ] }),
      /* @__PURE__ */ jsxs("li", { children: [
        '"',
        t("ai_assistant.chat.example.create"),
        '"'
      ] }),
      /* @__PURE__ */ jsxs("li", { children: [
        '"',
        t("ai_assistant.chat.example.show"),
        '"'
      ] })
    ] })
  ] });
}
function RoutingIndicator() {
  const t = useT();
  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: t("ai_assistant.status.analyzing") })
  ] });
}
function DockControls({
  position,
  onPositionChange,
  onMinimize,
  onClose
}) {
  const t = useT();
  const positions = [
    { value: "floating", icon: /* @__PURE__ */ jsx(MessageCircle, { className: "h-3.5 w-3.5" }), labelKey: "ai_assistant.dock.floating" },
    { value: "left", icon: /* @__PURE__ */ jsx(PanelLeft, { className: "h-3.5 w-3.5" }), labelKey: "ai_assistant.dock.left" },
    { value: "bottom", icon: /* @__PURE__ */ jsx(PanelBottom, { className: "h-3.5 w-3.5" }), labelKey: "ai_assistant.dock.bottom" },
    { value: "right", icon: /* @__PURE__ */ jsx(PanelRight, { className: "h-3.5 w-3.5" }), labelKey: "ai_assistant.dock.right" }
  ];
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
    positions.map((pos) => /* @__PURE__ */ jsx(
      Button,
      {
        variant: "ghost",
        size: "icon",
        className: cn("h-6 w-6", position === pos.value && "bg-accent"),
        onClick: () => onPositionChange(pos.value),
        title: t(pos.labelKey),
        children: pos.icon
      },
      pos.value
    )),
    /* @__PURE__ */ jsx("div", { className: "w-px h-4 bg-border mx-1" }),
    /* @__PURE__ */ jsx(
      Button,
      {
        variant: "ghost",
        size: "icon",
        className: "h-6 w-6",
        onClick: onMinimize,
        title: t("ai_assistant.dock.minimize"),
        children: /* @__PURE__ */ jsx(Minimize2, { className: "h-3.5 w-3.5" })
      }
    ),
    /* @__PURE__ */ jsx(
      Button,
      {
        variant: "ghost",
        size: "icon",
        className: "h-6 w-6",
        onClick: onClose,
        title: t("ai_assistant.dock.close"),
        children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" })
      }
    )
  ] });
}
const FLOATING_POSITION_STYLE = {
  bottom: 24,
  right: 24
};
function DockableChat() {
  const t = useT();
  const {
    state,
    isThinking,
    agentStatus,
    isSessionAuthorized,
    messages,
    pendingToolCalls,
    selectedTool,
    close,
    reset,
    handleSubmit,
    sendAgenticMessage,
    stopExecution,
    approveToolCall,
    rejectToolCall,
    debugEvents,
    showDebug,
    setShowDebug,
    clearDebugEvents,
    pendingQuestion,
    answerQuestion
  } = useCommandPaletteContext();
  const {
    dockState,
    setPosition,
    toggleMinimized,
    setMinimized,
    isFloating,
    isHydrated
  } = useDockPosition();
  const {
    isOpen,
    phase,
    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 handleInputSubmit = async () => {
    const query = localInput.trim();
    if (!query) return;
    setLocalInput("");
    await handleSubmit(query);
  };
  const handleInputKeyDown = (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 (phase !== "idle") {
        reset();
      } else {
        close();
      }
    }
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      if (chatInput.trim() && !isStreaming) {
        const content = chatInput;
        setChatInput("");
        sendAgenticMessage(content);
      }
    }
  };
  if (!isHydrated) return null;
  if (isOpen && dockState.isMinimized) {
    return typeof document !== "undefined" ? createPortal(
      /* @__PURE__ */ jsx(
        AiDot,
        {
          onClick: () => setMinimized(false),
          isActive: isStreaming || isThinking,
          hasMessages: messages.length > 0,
          position: "bottom-right"
        }
      ),
      document.body
    ) : null;
  }
  if (isFloating) {
    if (!isOpen) return null;
    return typeof document !== "undefined" ? createPortal(
      /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: cn(
              "fixed z-modal",
              "rounded-xl border bg-background shadow-2xl",
              "flex flex-col",
              "transition-all duration-200 ease-out"
            ),
            style: {
              ...FLOATING_POSITION_STYLE,
              width: dockState.width,
              height: dockState.height,
              maxHeight: "calc(100vh - 48px)"
            },
            onKeyDown: handleInputKeyDown,
            children: /* @__PURE__ */ jsxs(Command, { className: "flex flex-col flex-1 min-h-0 rounded-xl overflow-hidden", shouldFilter: false, children: [
              /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end px-2 py-1.5 border-b shrink-0", children: /* @__PURE__ */ jsx(
                DockControls,
                {
                  position: dockState.position,
                  onPositionChange: setPosition,
                  onMinimize: toggleMinimized,
                  onClose: close
                }
              ) }),
              /* @__PURE__ */ jsx(
                CommandHeader,
                {
                  phase,
                  selectedTool,
                  onBack: reset
                }
              ),
              phase === "idle" && /* @__PURE__ */ jsx(
                CommandInput,
                {
                  value: localInput,
                  onValueChange: setLocalInput,
                  mode: "commands",
                  isLoading,
                  placeholder: t("ai_assistant.chat.placeholder")
                }
              ),
              /* @__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: t("ai_assistant.chat.describePlaceholder"),
                    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)
                }
              )
            ] })
          }
        ),
        showDebug && /* @__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: "24px",
              left: "24px",
              width: "400px",
              maxHeight: "calc(100vh - 48px)"
            },
            children: /* @__PURE__ */ jsx(
              DebugPanel,
              {
                events: debugEvents,
                onClear: clearDebugEvents,
                isOpen: true,
                onToggle: () => setShowDebug(false)
              }
            )
          }
        )
      ] }),
      document.body
    ) : null;
  }
  if (!isOpen) return null;
  const positionStyles = {
    right: {
      position: "fixed",
      top: 0,
      right: 0,
      bottom: 0,
      width: dockState.width,
      zIndex: 40
    },
    left: {
      position: "fixed",
      top: 0,
      left: 0,
      bottom: 0,
      width: dockState.width,
      zIndex: 40
    },
    bottom: {
      position: "fixed",
      bottom: 0,
      left: 0,
      right: 0,
      height: dockState.height,
      zIndex: 40
    }
  };
  const panelPosition = dockState.position;
  return typeof document !== "undefined" ? createPortal(
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(
          "bg-background border shadow-xl flex flex-col",
          panelPosition === "right" && "border-l",
          panelPosition === "left" && "border-r",
          panelPosition === "bottom" && "border-t"
        ),
        style: positionStyles[panelPosition],
        onKeyDown: handleInputKeyDown,
        children: [
          /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end px-2 py-1.5 border-b shrink-0", children: /* @__PURE__ */ jsx(
            DockControls,
            {
              position: dockState.position,
              onPositionChange: setPosition,
              onMinimize: toggleMinimized,
              onClose: close
            }
          ) }),
          !dockState.isMinimized && /* @__PURE__ */ jsx(Fragment, { children: /* @__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: t("ai_assistant.chat.placeholder")
              }
            ),
            /* @__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: t("ai_assistant.chat.describePlaceholder"),
                  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)
              }
            )
          ] }) }),
          showDebug && /* @__PURE__ */ jsx(
            "div",
            {
              className: cn(
                "bg-gray-900 border-gray-700 flex flex-col overflow-hidden",
                panelPosition === "right" && "absolute left-0 top-0 bottom-0 w-[400px] -translate-x-full border-r",
                panelPosition === "left" && "absolute right-0 top-0 bottom-0 w-[400px] translate-x-full border-l",
                panelPosition === "bottom" && "absolute bottom-full left-0 right-0 h-[300px] border-t"
              ),
              children: /* @__PURE__ */ jsx(
                DebugPanel,
                {
                  events: debugEvents,
                  onClear: clearDebugEvents,
                  isOpen: true,
                  onToggle: () => setShowDebug(false)
                }
              )
            }
          )
        ]
      }
    ),
    document.body
  ) : null;
}
export {
  DockableChat
};
//# sourceMappingURL=DockableChat.js.map
