"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Boxes, ChevronDown, FileText, Package, PanelRightOpen, PenLine, Tags, TrendingUp } from "lucide-react";
import { AiChat } from "@open-mercato/ui/ai/AiChat";
import { AiIcon } from "@open-mercato/ui/ai/AiIcon";
import { useAiDock } from "@open-mercato/ui/ai/AiDock";
import { useAiChatSessions } from "@open-mercato/ui/ai/AiChatSessions";
import { ChatPaneTabs } from "@open-mercato/ui/ai/ChatPaneTabs";
import "../../../components/CatalogStatsCard.js";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { Button } from "@open-mercato/ui/primitives/button";
import { ButtonGroup } from "@open-mercato/ui/primitives/button-group";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Popover, PopoverContent, PopoverTrigger } from "@open-mercato/ui/primitives/popover";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
const MERCHANDISING_AGENT_ID = "catalog.merchandising_assistant";
function useMerchandisingSuggestions(hasSelection, selectedCount) {
  const t = useT();
  return React.useMemo(() => {
    if (hasSelection) {
      return [
        {
          label: t(
            "catalog.merchandising_assistant.suggestions.draftDescriptions",
            "Draft product descriptions for selected items"
          ),
          prompt: `Draft compelling product descriptions for my ${selectedCount} selected products`,
          icon: /* @__PURE__ */ jsx(PenLine, { className: "size-4" })
        },
        {
          label: t(
            "catalog.merchandising_assistant.suggestions.extractAttributes",
            "Extract attributes from descriptions"
          ),
          prompt: `Extract structured attributes from the descriptions of my ${selectedCount} selected products`,
          icon: /* @__PURE__ */ jsx(Tags, { className: "size-4" })
        },
        {
          label: t(
            "catalog.merchandising_assistant.suggestions.titleVariants",
            "Generate title variants for SEO"
          ),
          prompt: `Generate SEO-optimized title variants for my ${selectedCount} selected products`,
          icon: /* @__PURE__ */ jsx(FileText, { className: "size-4" })
        },
        {
          label: t(
            "catalog.merchandising_assistant.suggestions.priceAdjustments",
            "Suggest price adjustments"
          ),
          prompt: `Analyze and suggest price adjustments for my ${selectedCount} selected products`,
          icon: /* @__PURE__ */ jsx(TrendingUp, { className: "size-4" })
        }
      ];
    }
    return [
      {
        label: t(
          "catalog.merchandising_assistant.suggestions.showStats",
          "Show catalog overview"
        ),
        // Triggers the `catalog.show_stats` tool, which returns the inline
        // catalog-stats UI part (live counts of products, active products,
        // categories, tags). Demo entry-point for the dynamic UI-part path.
        prompt: "Show me a quick catalog overview using the stats card.",
        icon: /* @__PURE__ */ jsx(Boxes, { className: "size-4" })
      },
      {
        label: t(
          "catalog.merchandising_assistant.suggestions.browseProducts",
          "Show me an overview of my product catalog"
        ),
        prompt: "Give me an overview of my product catalog \u2014 categories, total products, and pricing ranges",
        icon: /* @__PURE__ */ jsx(Package, { className: "size-4" })
      },
      {
        label: t(
          "catalog.merchandising_assistant.suggestions.findMissingDescriptions",
          "Find products with missing descriptions"
        ),
        prompt: "Find products that are missing descriptions or have very short descriptions",
        icon: /* @__PURE__ */ jsx(PenLine, { className: "size-4" })
      },
      {
        label: t(
          "catalog.merchandising_assistant.suggestions.analyzeAttributes",
          "Analyze attribute coverage"
        ),
        prompt: "Analyze which products have incomplete attribute data",
        icon: /* @__PURE__ */ jsx(Tags, { className: "size-4" })
      },
      {
        label: t(
          "catalog.merchandising_assistant.suggestions.pricingOverview",
          "Show pricing distribution"
        ),
        prompt: "Show me the pricing distribution across categories",
        icon: /* @__PURE__ */ jsx(TrendingUp, { className: "size-4" })
      }
    ];
  }, [hasSelection, selectedCount, t]);
}
function useContextItems(pageContext) {
  const t = useT();
  return React.useMemo(() => {
    const items = [];
    const { selectedCount, totalMatching, filter } = pageContext.extra;
    if (selectedCount > 0) {
      items.push({
        label: t(
          "catalog.merchandising_assistant.context.selectedProducts",
          "{count} products selected"
        ).replace("{count}", String(selectedCount))
      });
    } else if (totalMatching > 0) {
      items.push({
        label: t(
          "catalog.merchandising_assistant.context.matchingProducts",
          "{count} products in view"
        ).replace("{count}", String(totalMatching))
      });
    }
    if (filter.categoryId) {
      items.push({
        label: t("catalog.merchandising_assistant.context.filteredByCategory", "Filtered by category"),
        detail: filter.categoryId
      });
    }
    if (filter.status) {
      items.push({ label: filter.status });
    }
    if (filter.tags.length > 0) {
      items.push({
        label: t("catalog.merchandising_assistant.context.tags", "{count} tags").replace(
          "{count}",
          String(filter.tags.length)
        )
      });
    }
    return items;
  }, [pageContext, t]);
}
function useMerchandisingAgents() {
  const t = useT();
  const [accessibleAgentIds, setAccessibleAgentIds] = React.useState(null);
  const declaredAgents = React.useMemo(
    () => [
      {
        id: MERCHANDISING_AGENT_ID,
        label: t(
          "catalog.merchandising_assistant.agents.merchandising.label",
          "Merchandising Assistant"
        ),
        description: t(
          "catalog.merchandising_assistant.agents.merchandising.description",
          "Draft copy, normalize attributes, and propose price changes for the current selection."
        ),
        icon: /* @__PURE__ */ jsx(AiIcon, { className: "size-4" })
      }
    ],
    [t]
  );
  React.useEffect(() => {
    let cancelled = false;
    apiCall("/api/ai_assistant/ai/agents", {
      credentials: "same-origin",
      headers: { "x-om-forbidden-redirect": "0", "x-om-unauthorized-redirect": "0" }
    }).then((call) => {
      if (cancelled) return;
      if (!call.ok || !call.result || !Array.isArray(call.result.agents)) {
        setAccessibleAgentIds(/* @__PURE__ */ new Set());
        return;
      }
      setAccessibleAgentIds(
        new Set(
          call.result.agents.map((agent) => agent?.id).filter((id) => typeof id === "string" && id.length > 0)
        )
      );
    }).catch(() => {
      if (!cancelled) setAccessibleAgentIds(/* @__PURE__ */ new Set());
    });
    return () => {
      cancelled = true;
    };
  }, []);
  return React.useMemo(
    () => ({
      agents: accessibleAgentIds === null ? [] : declaredAgents.filter((agent) => accessibleAgentIds.has(agent.id)),
      loaded: accessibleAgentIds !== null
    }),
    [accessibleAgentIds, declaredAgents]
  );
}
function MerchandisingAssistantSheet({
  pageContext,
  enabled = true,
  className
}) {
  const t = useT();
  const dock = useAiDock();
  const [open, setOpen] = React.useState(false);
  const [popoverOpen, setPopoverOpen] = React.useState(false);
  const [activeAgent, setActiveAgent] = React.useState(MERCHANDISING_AGENT_ID);
  const [lastAgent, setLastAgent] = React.useState(null);
  const selectedCount = pageContext.extra.selectedCount;
  const hasSelection = selectedCount > 0;
  const suggestions = useMerchandisingSuggestions(hasSelection, selectedCount);
  const contextItems = useContextItems(pageContext);
  const { agents, loaded: agentsLoaded } = useMerchandisingAgents();
  if (!enabled || !agentsLoaded || agents.length === 0) return null;
  const openAgent = (agentId) => {
    setActiveAgent(agentId);
    setLastAgent(agentId);
    setPopoverOpen(false);
    if (dock.state.assistant?.agent === agentId) {
      dock.dock(dock.state.assistant);
      setOpen(false);
      return;
    }
    setOpen(true);
  };
  const handleSelectAgent = (agentId) => {
    openAgent(agentId);
  };
  const handleMainTriggerClick = () => {
    if (agents.length === 1) {
      openAgent(agents[0].id);
      return;
    }
    if (lastAgent && agents.some((a) => a.id === lastAgent)) {
      openAgent(lastAgent);
      return;
    }
    setPopoverOpen(true);
  };
  const handleDock = () => {
    const agent = agents.find((a) => a.id === activeAgent) ?? agents[0];
    if (!agent) return;
    dock.dock({
      agent: agent.id,
      label: agent.label,
      description: t("catalog.merchandising_assistant.dock.subtitle", "Catalog"),
      pageContext,
      placeholder: t(
        "catalog.merchandising_assistant.sheet.composerPlaceholder",
        "Ask for descriptions, attributes, titles, or price ideas..."
      ),
      suggestions,
      contextItems,
      welcomeTitle: t(
        "catalog.merchandising_assistant.sheet.welcomeTitle",
        "Merchandising Assistant"
      ),
      welcomeDescription: hasSelection ? t(
        "catalog.merchandising_assistant.sheet.welcomeDescriptionSelection",
        "Ready to work with your {count} selected products. Try one of these:"
      ).replace("{count}", String(selectedCount)) : t(
        "catalog.merchandising_assistant.sheet.welcomeDescriptionAll",
        "Select products for targeted actions, or explore your catalog:"
      )
    });
    setOpen(false);
  };
  const triggerLabel = t(
    "catalog.merchandising_assistant.trigger.ariaLabel",
    "Open AI merchandising assistant"
  );
  const labelText = t("catalog.merchandising_assistant.trigger.label", "AI");
  const moreAgentsLabel = t(
    "catalog.merchandising_assistant.trigger.moreAgentsAriaLabel",
    "Choose an AI assistant"
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(ButtonGroup, { className, children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: handleMainTriggerClick,
          "data-ai-merchandising-trigger": "",
          "aria-label": triggerLabel,
          title: triggerLabel,
          className: "relative",
          children: [
            /* @__PURE__ */ jsx(AiIcon, { className: "size-4" }),
            /* @__PURE__ */ jsx("span", { children: labelText }),
            hasSelection ? /* @__PURE__ */ jsx(
              "span",
              {
                className: "absolute -top-1 -right-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium leading-none text-primary-foreground",
                "data-ai-merchandising-selected-count": selectedCount,
                children: selectedCount
              }
            ) : null
          ]
        }
      ),
      agents.length > 1 ? /* @__PURE__ */ jsxs(Popover, { open: popoverOpen, onOpenChange: setPopoverOpen, children: [
        /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "outline",
            "aria-label": moreAgentsLabel,
            title: moreAgentsLabel,
            "data-ai-merchandising-picker": "",
            children: /* @__PURE__ */ jsx(ChevronDown, { className: "size-4", "aria-hidden": true })
          }
        ) }),
        /* @__PURE__ */ jsxs(PopoverContent, { align: "end", className: "w-72 p-1", children: [
          /* @__PURE__ */ jsx("div", { className: "px-3 pt-2 pb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("catalog.merchandising_assistant.popover.heading", "AI assistants") }),
          /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-0.5", children: agents.map((agent) => /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              onClick: () => handleSelectAgent(agent.id),
              "data-ai-merchandising-agent-option": agent.id,
              className: "h-auto w-full items-start justify-start gap-2 whitespace-normal rounded-sm px-2 py-2 text-left text-sm font-normal",
              children: [
                /* @__PURE__ */ jsx("span", { className: "mt-0.5 inline-flex size-6 items-center justify-center rounded-full bg-secondary text-secondary-foreground", children: agent.icon }),
                /* @__PURE__ */ jsxs("span", { className: "flex-1 min-w-0", children: [
                  /* @__PURE__ */ jsx("span", { className: "block font-medium leading-tight", children: agent.label }),
                  /* @__PURE__ */ jsx("span", { className: "block text-xs text-muted-foreground leading-snug", children: agent.description })
                ] })
              ]
            },
            agent.id
          )) })
        ] })
      ] }) : null
    ] }),
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: setOpen, children: /* @__PURE__ */ jsxs(
      DialogContent,
      {
        className: cn(
          // Mobile: full-screen sheet. Desktop (≥sm): right-anchored side sheet.
          // The Dialog primitive applies a centering transform at the
          // sm breakpoint; each piece (`top`, `left`, transform, inset)
          // must be overridden at the same breakpoint or the panel
          // renders half off the viewport.
          "top-0 left-0 right-0 bottom-0 translate-x-0 translate-y-0 max-w-none w-screen h-svh max-h-svh rounded-none",
          "sm:top-0 sm:bottom-0 sm:right-0 sm:left-auto sm:translate-x-0 sm:translate-y-0",
          "sm:max-w-xl sm:w-[36rem] sm:rounded-l-2xl sm:h-screen sm:max-h-screen",
          "flex flex-col gap-3 p-4 z-[70]"
        ),
        "data-ai-merchandising-sheet": "",
        children: [
          /* @__PURE__ */ jsxs(DialogHeader, { children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 pr-8", children: [
              /* @__PURE__ */ jsx(
                IconButton,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  "aria-label": t("catalog.merchandising_assistant.sheet.dock", "Dock to side"),
                  title: t("catalog.merchandising_assistant.sheet.dock", "Dock to side"),
                  onClick: handleDock,
                  "data-ai-merchandising-dock": "",
                  className: "hidden lg:inline-flex shrink-0",
                  children: /* @__PURE__ */ jsx(PanelRightOpen, { className: "size-4", "aria-hidden": true })
                }
              ),
              /* @__PURE__ */ jsx(DialogTitle, { className: "flex-1 min-w-0 truncate", children: t("catalog.merchandising_assistant.sheet.title", "Catalog merchandising assistant") }),
              hasSelection ? /* @__PURE__ */ jsx(
                "span",
                {
                  className: "shrink-0 inline-flex items-center rounded-full border border-border bg-secondary px-2 py-0.5 text-xs text-secondary-foreground",
                  "data-ai-merchandising-selection-pill": "",
                  "data-ai-merchandising-selected-count": selectedCount,
                  children: t(
                    "catalog.merchandising_assistant.sheet.selectionPill",
                    "Acting on {count} products"
                  ).replace("{count}", String(selectedCount))
                }
              ) : null
            ] }),
            /* @__PURE__ */ jsx(DialogDescription, { children: hasSelection ? t(
              "catalog.merchandising_assistant.sheet.descriptionWithSelection",
              "Working with {count} selected products. Ask for descriptions, attribute extraction, title suggestions, or pricing analysis."
            ).replace("{count}", String(selectedCount)) : t(
              "catalog.merchandising_assistant.sheet.description",
              "Your AI merchandising copilot. Select products from the list for targeted actions, or explore your full catalog."
            ) })
          ] }),
          /* @__PURE__ */ jsx(
            MerchandisingChatBody,
            {
              activeAgent,
              pageContext,
              suggestions,
              contextItems,
              hasSelection,
              selectedCount
            }
          )
        ]
      }
    ) })
  ] });
}
function MerchandisingChatBody({
  activeAgent,
  pageContext,
  suggestions,
  contextItems,
  hasSelection,
  selectedCount
}) {
  const t = useT();
  const sessions = useAiChatSessions();
  const session = sessions.getActiveSession(activeAgent);
  React.useEffect(() => {
    if (!session) sessions.ensureSession(activeAgent);
  }, [activeAgent, session, sessions]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(ChatPaneTabs, { agentId: activeAgent, className: "border-b" }),
    /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1", "data-ai-merchandising-chat-container": "", children: session ? /* @__PURE__ */ jsx(
      AiChat,
      {
        agent: activeAgent,
        conversationId: session.conversationId,
        pageContext,
        className: "h-full",
        placeholder: t(
          "catalog.merchandising_assistant.sheet.composerPlaceholder",
          "Ask for descriptions, attributes, titles, or price ideas..."
        ),
        suggestions,
        contextItems,
        welcomeTitle: t(
          "catalog.merchandising_assistant.sheet.welcomeTitle",
          "Merchandising Assistant"
        ),
        welcomeDescription: hasSelection ? t(
          "catalog.merchandising_assistant.sheet.welcomeDescriptionSelection",
          "Ready to work with your {count} selected products. Try one of these:"
        ).replace("{count}", String(selectedCount)) : t(
          "catalog.merchandising_assistant.sheet.welcomeDescriptionAll",
          "Select products for targeted actions, or explore your catalog:"
        )
      },
      session.id
    ) : null })
  ] });
}
var MerchandisingAssistantSheet_default = MerchandisingAssistantSheet;
export {
  MERCHANDISING_AGENT_ID,
  MerchandisingAssistantSheet,
  MerchandisingAssistantSheet_default as default
};
//# sourceMappingURL=MerchandisingAssistantSheet.js.map
