"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Maximize2, Minimize2, X } from "lucide-react";
import { ChatPaneTabs } from "./ChatPaneTabs.js";
import { useAiChatSessions } from "./AiChatSessions.js";
import { IconButton } from "../primitives/icon-button.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
const LazyAiChat = React.lazy(async () => {
  const mod = await import("./AiChat.js");
  return { default: mod.AiChat };
});
const STORAGE_KEY = "om-ai-dock-v1";
const MIN_WIDTH = 320;
const MAX_WIDTH = 960;
const DEFAULT_WIDTH = 420;
const COLLAPSED_WIDTH = 48;
const AiDockContext = React.createContext(null);
function isRecord(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function readOptionalString(value) {
  return typeof value === "string" && value.length > 0 ? value : void 0;
}
function readWidth(value) {
  return Math.min(
    MAX_WIDTH,
    Math.max(MIN_WIDTH, typeof value === "number" ? value : DEFAULT_WIDTH)
  );
}
function readPersistedSuggestions(value) {
  if (!Array.isArray(value)) return void 0;
  const suggestions = value.filter((entry) => isRecord(entry)).map((entry) => {
    const label = readOptionalString(entry.label);
    const prompt = readOptionalString(entry.prompt);
    if (!label || !prompt) return null;
    return { label, prompt };
  }).filter((entry) => entry !== null);
  return suggestions.length > 0 ? suggestions : void 0;
}
function readPersistedContextItems(value) {
  if (!Array.isArray(value)) return void 0;
  const contextItems = value.filter((entry) => isRecord(entry)).map((entry) => {
    const label = readOptionalString(entry.label);
    if (!label) return null;
    const detail = readOptionalString(entry.detail);
    return detail ? { label, detail } : { label };
  }).filter((entry) => entry !== null);
  return contextItems.length > 0 ? contextItems : void 0;
}
function readPersistedAssistant(value) {
  if (!isRecord(value)) return null;
  const agent = readOptionalString(value.agent);
  const label = readOptionalString(value.label);
  if (!agent || !label) return null;
  return {
    agent,
    label,
    description: readOptionalString(value.description),
    pageContext: isRecord(value.pageContext) ? value.pageContext : void 0,
    placeholder: readOptionalString(value.placeholder),
    welcomeTitle: readOptionalString(value.welcomeTitle),
    welcomeDescription: readOptionalString(value.welcomeDescription),
    suggestions: readPersistedSuggestions(value.suggestions),
    contextItems: readPersistedContextItems(value.contextItems)
  };
}
function serializeAssistant(assistant) {
  if (!assistant) return null;
  return {
    agent: assistant.agent,
    label: assistant.label,
    description: assistant.description,
    pageContext: assistant.pageContext,
    placeholder: assistant.placeholder,
    welcomeTitle: assistant.welcomeTitle,
    welcomeDescription: assistant.welcomeDescription,
    suggestions: assistant.suggestions?.map((suggestion) => ({
      label: suggestion.label,
      prompt: suggestion.prompt
    })),
    contextItems: assistant.contextItems?.map((item) => ({
      label: item.label,
      detail: item.detail
    }))
  };
}
function readPersisted() {
  if (typeof window === "undefined") return { assistant: null, width: DEFAULT_WIDTH, collapsed: false };
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return { assistant: null, width: DEFAULT_WIDTH, collapsed: false };
    const parsed = JSON.parse(raw);
    return {
      assistant: readPersistedAssistant(parsed?.assistant),
      width: readWidth(parsed?.width),
      collapsed: parsed?.collapsed === true
    };
  } catch {
    return { assistant: null, width: DEFAULT_WIDTH, collapsed: false };
  }
}
function writePersisted(state) {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({
        assistant: serializeAssistant(state.assistant),
        width: state.width,
        collapsed: state.collapsed
      })
    );
  } catch {
  }
}
function AiDockProvider({ children }) {
  const [state, setState] = React.useState(() => ({
    assistant: null,
    width: DEFAULT_WIDTH,
    collapsed: false
  }));
  const [hydrated, setHydrated] = React.useState(false);
  React.useEffect(() => {
    const persisted = readPersisted();
    setState(persisted);
    setHydrated(true);
  }, []);
  React.useEffect(() => {
    if (!hydrated) return;
    writePersisted(state);
  }, [hydrated, state]);
  const dock = React.useCallback((assistant) => {
    setState((prev) => ({ ...prev, assistant, collapsed: false }));
  }, []);
  const undock = React.useCallback(() => {
    setState((prev) => ({ ...prev, assistant: null, collapsed: false }));
  }, []);
  const isDocked = React.useCallback(
    (agentId) => state.assistant?.agent === agentId,
    [state.assistant?.agent]
  );
  const setWidth = React.useCallback((width) => {
    setState((prev) => ({ ...prev, width }));
  }, []);
  const setCollapsed = React.useCallback((collapsed) => {
    setState((prev) => ({ ...prev, collapsed }));
  }, []);
  const api = React.useMemo(
    () => ({ state, dock, undock, isDocked }),
    [state, dock, undock, isDocked]
  );
  const reservedWidth = state.assistant ? state.collapsed ? COLLAPSED_WIDTH : state.width : null;
  return /* @__PURE__ */ jsxs(AiDockContext.Provider, { value: api, children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: reservedWidth != null ? "lg:pr-[var(--om-ai-dock-width)]" : void 0,
        style: reservedWidth != null ? { ["--om-ai-dock-width"]: `${reservedWidth}px` } : void 0,
        children
      }
    ),
    state.assistant ? /* @__PURE__ */ jsx(
      AiDockPanel,
      {
        assistant: state.assistant,
        width: state.width,
        collapsed: state.collapsed,
        onCollapsedChange: setCollapsed,
        onWidthChange: setWidth,
        onClose: undock
      }
    ) : null
  ] });
}
function useAiDock() {
  const ctx = React.useContext(AiDockContext);
  if (ctx) return ctx;
  return {
    state: { assistant: null, width: DEFAULT_WIDTH, collapsed: false },
    dock: () => {
    },
    undock: () => {
    },
    isDocked: () => false
  };
}
function AiDockPanel({
  assistant,
  width,
  collapsed,
  onCollapsedChange,
  onWidthChange,
  onClose
}) {
  const t = useT();
  const dragStateRef = React.useRef(null);
  const handlePointerDown = React.useCallback(
    (event) => {
      event.preventDefault();
      const target = event.currentTarget;
      target.setPointerCapture(event.pointerId);
      dragStateRef.current = { startX: event.clientX, startWidth: width };
    },
    [width]
  );
  const handlePointerMove = React.useCallback(
    (event) => {
      if (!dragStateRef.current) return;
      const delta = dragStateRef.current.startX - event.clientX;
      const next = Math.min(
        MAX_WIDTH,
        Math.max(MIN_WIDTH, dragStateRef.current.startWidth + delta)
      );
      onWidthChange(next);
    },
    [onWidthChange]
  );
  const handlePointerUp = React.useCallback(
    (event) => {
      const target = event.currentTarget;
      try {
        target.releasePointerCapture(event.pointerId);
      } catch {
      }
      dragStateRef.current = null;
    },
    []
  );
  return /* @__PURE__ */ jsxs(
    "aside",
    {
      "data-ai-dock-panel": "",
      "data-ai-dock-agent": assistant.agent,
      className: cn(
        // Dock is desktop-only — on small screens the AiChat dialog is the
        // primary surface (full-screen sheet) and a fixed side panel would
        // crowd the viewport.
        "hidden lg:flex",
        "fixed top-0 right-0 z-overlay h-svh min-w-0 flex-col overflow-hidden border-l bg-background shadow-lg",
        collapsed ? "w-12" : ""
      ),
      style: collapsed ? void 0 : { width },
      "aria-label": assistant.label,
      children: [
        !collapsed ? /* @__PURE__ */ jsx(
          "div",
          {
            role: "separator",
            "aria-orientation": "vertical",
            tabIndex: -1,
            onPointerDown: handlePointerDown,
            onPointerMove: handlePointerMove,
            onPointerUp: handlePointerUp,
            onPointerCancel: handlePointerUp,
            className: "absolute left-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/20",
            "data-ai-dock-resize-handle": ""
          }
        ) : null,
        /* @__PURE__ */ jsx("header", { className: "flex items-center gap-2 px-3 py-2", children: collapsed ? /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            "aria-label": t("ai_assistant.chat.dock.expand", "Expand AI dock"),
            title: t("ai_assistant.chat.dock.expand", "Expand AI dock"),
            onClick: () => onCollapsedChange(false),
            children: /* @__PURE__ */ jsx(Maximize2, { className: "size-4" })
          }
        ) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm font-medium", "data-ai-dock-label": "", children: [
              /* @__PURE__ */ jsx("span", { className: "truncate", children: assistant.label }),
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: "inline-flex shrink-0 items-center rounded-full border border-border bg-secondary px-1.5 py-0 text-[10px] font-medium uppercase tracking-wide text-secondary-foreground",
                  "data-ai-beta-chip": "",
                  children: t("ai_assistant.chat.betaChip", "beta")
                }
              )
            ] }),
            assistant.description ? /* @__PURE__ */ jsx("div", { className: "truncate text-xs text-muted-foreground", children: assistant.description }) : null
          ] }),
          /* @__PURE__ */ jsx(
            IconButton,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              "aria-label": t("ai_assistant.chat.dock.collapse", "Collapse AI dock"),
              title: t("ai_assistant.chat.dock.collapse", "Collapse AI dock"),
              onClick: () => onCollapsedChange(true),
              children: /* @__PURE__ */ jsx(Minimize2, { className: "size-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            IconButton,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              "aria-label": t("ai_assistant.chat.dock.close", "Close AI dock"),
              title: t("ai_assistant.chat.dock.close", "Close AI dock"),
              onClick: onClose,
              "data-ai-dock-close": "",
              children: /* @__PURE__ */ jsx(X, { className: "size-4" })
            }
          )
        ] }) }),
        !collapsed ? /* @__PURE__ */ jsx(DockedChatBody, { assistant }) : null
      ]
    }
  );
}
function DockedChatBody({ assistant }) {
  const sessions = useAiChatSessions();
  const session = sessions.getActiveSession(assistant.agent);
  React.useEffect(() => {
    if (!session) sessions.ensureSession(assistant.agent);
  }, [assistant.agent, session, sessions]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ChatPaneTabs, { agentId: assistant.agent, className: "border-b" }),
    /* @__PURE__ */ jsx("div", { className: "min-h-0 min-w-0 flex-1 overflow-hidden", "data-ai-dock-chat-container": "", children: session ? /* @__PURE__ */ jsx(React.Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
      LazyAiChat,
      {
        agent: assistant.agent,
        conversationId: session.conversationId,
        pageContext: assistant.pageContext,
        className: "h-full",
        defaultCompactFooter: true,
        placeholder: assistant.placeholder,
        suggestions: assistant.suggestions,
        contextItems: assistant.contextItems,
        welcomeTitle: assistant.welcomeTitle,
        welcomeDescription: assistant.welcomeDescription
      },
      session.id
    ) }) : null })
  ] });
}
export {
  AiDockProvider,
  useAiDock
};
//# sourceMappingURL=AiDock.js.map
