"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Clock, Pencil, Plus, X } from "lucide-react";
import { IconButton } from "../primitives/icon-button.js";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  defaultSessionLabel,
  useAiChatSessions
} from "./AiChatSessions.js";
function ChatPaneTabs({ agentId, className }) {
  const t = useT();
  const sessions = useAiChatSessions();
  const open = sessions.getOpenSessions(agentId);
  const closed = sessions.getClosedSessions(agentId);
  const active = sessions.getActiveSession(agentId);
  const [historyOpen, setHistoryOpen] = React.useState(false);
  const [renamingId, setRenamingId] = React.useState(null);
  const [draftName, setDraftName] = React.useState("");
  const startRename = (session) => {
    setRenamingId(session.id);
    setDraftName(session.name ?? "");
  };
  const commitRename = () => {
    if (!renamingId) return;
    sessions.renameSession(renamingId, draftName);
    setRenamingId(null);
  };
  const cancelRename = () => {
    setRenamingId(null);
    setDraftName("");
  };
  return (
    // Outer wrapper does NOT scroll; only the inner tabs row does. The
    // `+` button and the history dropdown live OUTSIDE that scroll area
    // so the dropdown's absolute positioning isn't clipped by the
    // strip's `overflow-x-auto` (which CSS resolves to `overflow-y:auto`
    // too once one axis is non-`visible`, making any absolutely-
    // positioned child get cut off at the strip's bottom edge).
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn("flex items-center gap-1 px-2 pt-2 text-sm", className),
        "data-ai-chat-tabs": "",
        role: "tablist",
        "aria-label": "Chat sessions",
        children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: "flex min-w-0 flex-1 items-center gap-1 overflow-x-auto",
              "data-ai-chat-tabs-scroll": "",
              children: open.length === 0 ? /* @__PURE__ */ jsx("span", { className: "px-2 py-1 text-xs text-muted-foreground", "data-ai-chat-tabs-empty": "", children: t("ai_assistant.chat.tabs.noSessions", "No sessions") }) : open.map((session) => {
                const isActive = active?.id === session.id;
                const isRenaming = renamingId === session.id;
                const label = defaultSessionLabel(session);
                return /* @__PURE__ */ jsxs(
                  "div",
                  {
                    role: "tab",
                    "aria-selected": isActive,
                    "data-ai-chat-tab-id": session.id,
                    "data-active": isActive ? "true" : "false",
                    className: cn(
                      "group flex max-w-[12rem] shrink-0 items-center gap-1 rounded-t-md border-b-2 px-2 py-1",
                      isActive ? "border-primary bg-background text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"
                    ),
                    children: [
                      isRenaming ? /* @__PURE__ */ jsx(
                        "input",
                        {
                          autoFocus: true,
                          type: "text",
                          value: draftName,
                          onChange: (event) => setDraftName(event.target.value),
                          onBlur: commitRename,
                          onKeyDown: (event) => {
                            if (event.key === "Enter") {
                              event.preventDefault();
                              commitRename();
                            } else if (event.key === "Escape") {
                              event.preventDefault();
                              cancelRename();
                            }
                          },
                          className: "h-6 max-w-[10rem] rounded border border-input bg-background px-1 text-xs outline-none focus:ring-2 focus:ring-ring/40",
                          "data-ai-chat-tab-rename-input": ""
                        }
                      ) : /* @__PURE__ */ jsx(
                        "button",
                        {
                          type: "button",
                          onClick: () => sessions.setActiveSession(session.id),
                          onDoubleClick: () => startRename(session),
                          title: label,
                          className: "truncate text-xs font-medium",
                          children: label
                        }
                      ),
                      !isRenaming && isActive ? /* @__PURE__ */ jsx(
                        IconButton,
                        {
                          type: "button",
                          variant: "ghost",
                          size: "xs",
                          "aria-label": t("ai_assistant.chat.tabs.rename", "Rename"),
                          title: t("ai_assistant.chat.tabs.rename", "Rename"),
                          className: "opacity-60 hover:opacity-100",
                          onClick: () => startRename(session),
                          "data-ai-chat-tab-rename": "",
                          children: /* @__PURE__ */ jsx(Pencil, { className: "size-3" })
                        }
                      ) : null,
                      /* @__PURE__ */ jsx(
                        IconButton,
                        {
                          type: "button",
                          variant: "ghost",
                          size: "xs",
                          "aria-label": t("ai_assistant.chat.tabs.close", "Close"),
                          title: t("ai_assistant.chat.tabs.close", "Close"),
                          className: cn(
                            "transition-opacity",
                            isActive ? "opacity-60 hover:opacity-100" : "opacity-50 hover:opacity-100"
                          ),
                          "data-active": isActive ? "true" : "false",
                          onMouseDown: (event) => {
                            event.stopPropagation();
                          },
                          onClick: (event) => {
                            event.preventDefault();
                            event.stopPropagation();
                            sessions.closeSession(session.id);
                          },
                          "data-ai-chat-tab-close": "",
                          children: /* @__PURE__ */ jsx(X, { className: "size-3" })
                        }
                      )
                    ]
                  },
                  session.id
                );
              })
            }
          ),
          /* @__PURE__ */ jsx(
            IconButton,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              "aria-label": t("ai_assistant.chat.tabs.newSession", "New session"),
              title: t("ai_assistant.chat.tabs.newSession", "New session"),
              onClick: () => sessions.createSession(agentId),
              "data-ai-chat-new-session": "",
              className: "shrink-0",
              children: /* @__PURE__ */ jsx(Plus, { className: "size-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            HistoryDropdown,
            {
              open: historyOpen,
              onOpenChange: setHistoryOpen,
              closed,
              onPick: (sessionId) => {
                sessions.reopenSession(sessionId);
                setHistoryOpen(false);
              }
            }
          )
        ]
      }
    )
  );
}
function HistoryDropdown({ open, onOpenChange, closed, onPick }) {
  const t = useT();
  const containerRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDown = (event) => {
      const root = containerRef.current;
      if (!root) return;
      if (event.target instanceof Node && root.contains(event.target)) return;
      onOpenChange(false);
    };
    const onKey = (event) => {
      if (event.key === "Escape") onOpenChange(false);
    };
    window.addEventListener("mousedown", onDown);
    window.addEventListener("touchstart", onDown, { passive: true });
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("mousedown", onDown);
      window.removeEventListener("touchstart", onDown);
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onOpenChange]);
  return /* @__PURE__ */ jsxs("div", { ref: containerRef, className: "relative shrink-0", children: [
    /* @__PURE__ */ jsx(
      IconButton,
      {
        type: "button",
        variant: "ghost",
        size: "sm",
        "aria-label": t("ai_assistant.chat.tabs.recentSessions", "Recent sessions"),
        title: t("ai_assistant.chat.tabs.recentSessions", "Recent sessions"),
        "data-ai-chat-history-trigger": "",
        "aria-expanded": open,
        onClick: () => onOpenChange(!open),
        children: /* @__PURE__ */ jsx(Clock, { className: "size-4" })
      }
    ),
    open ? /* @__PURE__ */ jsxs(
      "div",
      {
        className: "absolute right-0 top-full mt-2 w-72 max-h-[60vh] overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
        style: { zIndex: 2147483e3 },
        "data-ai-chat-history-panel": "",
        role: "menu",
        children: [
          /* @__PURE__ */ jsx("div", { className: "px-3 pt-2 pb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("ai_assistant.chat.tabs.recentSessions", "Recent sessions") }),
          closed.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-3 py-3 text-xs text-muted-foreground", "data-ai-chat-history-empty": "", children: t("ai_assistant.chat.tabs.noPreviousSessions", "No previous sessions yet.") }) : /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-0.5", children: closed.map((session) => /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              role: "menuitem",
              onClick: () => onPick(session.id),
              className: "flex w-full items-center justify-between gap-2 rounded-sm px-2 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:outline-none",
              "data-ai-chat-history-item": session.id,
              children: [
                /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: defaultSessionLabel(session) }),
                /* @__PURE__ */ jsx("span", { className: "shrink-0 text-[10px] text-muted-foreground", children: new Date(session.lastUsedAt).toLocaleDateString(void 0, {
                  month: "short",
                  day: "numeric"
                }) })
              ]
            },
            session.id
          )) })
        ]
      }
    ) : null
  ] });
}
export {
  ChatPaneTabs
};
//# sourceMappingURL=ChatPaneTabs.js.map
