"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Building2, ChevronDown, Handshake, PanelRightOpen, Search, Users } 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 { 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 CUSTOMERS_AI_INJECT_AGENT_ID = "customers.account_assistant";
function computeCustomersAiInjectPageContext(context) {
  return buildPageContext(context);
}
function readString(value) {
  return typeof value === "string" ? value : "";
}
function readNumber(value) {
  if (typeof value === "number" && Number.isFinite(value)) return value;
  if (typeof value === "string") {
    const parsed = Number.parseInt(value, 10);
    if (Number.isFinite(parsed)) return parsed;
  }
  return 0;
}
function resolveView(tableId) {
  if (typeof tableId === "string") {
    if (tableId.includes("deals")) return "customers.deals.list";
    if (tableId.includes("companies")) return "customers.companies.list";
  }
  return "customers.people.list";
}
function buildPageContext(context) {
  const selectedIdsRaw = Array.isArray(context?.selectedRowIds) ? context?.selectedRowIds ?? [] : [];
  const selectedIds = selectedIdsRaw.map(readString).filter((id) => id.length > 0);
  const selectedCount = selectedIds.length > 0 ? selectedIds.length : readNumber(context?.selectedCount);
  const totalMatching = readNumber(context?.totalMatching ?? context?.total ?? context?.rowCount);
  const recordId = selectedIds.length > 0 ? selectedIds.join(",") : null;
  return {
    view: resolveView(context?.tableId),
    recordType: null,
    recordId,
    extra: {
      selectedCount,
      totalMatching
    }
  };
}
function useCustomerSuggestions(view, hasSelection, selectedCount) {
  const t = useT();
  return React.useMemo(() => {
    if (view === "customers.deals.list") {
      if (hasSelection) {
        return [
          {
            label: t(
              "customers.ai_assistant.suggestions.summarizeSelectedDeals",
              "Summarize selected deals"
            ),
            prompt: `Give me a summary of my ${selectedCount} selected deals \u2014 stage, value, and close date`,
            icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
          },
          {
            label: t(
              "customers.ai_assistant.suggestions.atRiskSelectedDeals",
              "Selected deals at risk"
            ),
            prompt: `Of my ${selectedCount} selected deals, which look at risk of slipping their close date?`,
            icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
          },
          {
            label: t(
              "customers.ai_assistant.suggestions.companiesForSelectedDeals",
              "Companies on selected deals"
            ),
            prompt: `List the companies associated with my ${selectedCount} selected deals`,
            icon: /* @__PURE__ */ jsx(Building2, { className: "size-4" })
          }
        ];
      }
      return [
        {
          label: t(
            "customers.ai_assistant.suggestions.dealsClosingThisMonth",
            "Deals closing this month"
          ),
          prompt: "Which deals are closing this month?",
          icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.dealsAtRisk",
            "Deals at risk of slipping"
          ),
          prompt: "Show me deals at risk of slipping their close date",
          icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.totalOpenDealValue",
            "Total open deal value"
          ),
          prompt: "What's the total value of open deals across the pipeline?",
          icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.topDealsByValue",
            "Top deals by value"
          ),
          prompt: "Show me the top 5 deals by value",
          icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.searchDeals",
            "Search for a deal"
          ),
          prompt: "Search for deals by title, company, or stage",
          icon: /* @__PURE__ */ jsx(Search, { className: "size-4" })
        }
      ];
    }
    if (view === "customers.companies.list") {
      if (hasSelection) {
        return [
          {
            label: t(
              "customers.ai_assistant.suggestions.summarizeSelectedCompanies",
              "Summarize selected companies"
            ),
            prompt: `Give me a summary of my ${selectedCount} selected companies \u2014 size, industry, and recent activity`,
            icon: /* @__PURE__ */ jsx(Building2, { className: "size-4" })
          },
          {
            label: t(
              "customers.ai_assistant.suggestions.dealsForSelectedCompanies",
              "Show deals for selected companies"
            ),
            prompt: `Show me all deals associated with my ${selectedCount} selected companies`,
            icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
          },
          {
            label: t(
              "customers.ai_assistant.suggestions.peopleAtSelectedCompanies",
              "List people at selected companies"
            ),
            prompt: `List the contacts (people) associated with my ${selectedCount} selected companies`,
            icon: /* @__PURE__ */ jsx(Users, { className: "size-4" })
          }
        ];
      }
      return [
        {
          label: t(
            "customers.ai_assistant.suggestions.searchCompanies",
            "Search for a company"
          ),
          prompt: "Search for companies by name, industry, or tax ID",
          icon: /* @__PURE__ */ jsx(Search, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.topCompaniesByDeals",
            "Top companies by deal value"
          ),
          prompt: "Show me the companies with the highest open deal value",
          icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.companiesWithoutContacts",
            "Companies missing contacts"
          ),
          prompt: "Find companies that have no associated people yet",
          icon: /* @__PURE__ */ jsx(Users, { className: "size-4" })
        },
        {
          label: t(
            "customers.ai_assistant.suggestions.companiesActivityOverview",
            "Activity overview"
          ),
          prompt: "Give me an overview of recent company-level activities and interactions",
          icon: /* @__PURE__ */ jsx(Building2, { className: "size-4" })
        }
      ];
    }
    if (hasSelection) {
      return [
        {
          label: t("customers.ai_assistant.suggestions.summarizeSelected", "Summarize selected contacts"),
          prompt: `Give me a summary of my ${selectedCount} selected contacts \u2014 key details and recent activity`,
          icon: /* @__PURE__ */ jsx(Users, { className: "size-4" })
        },
        {
          label: t("customers.ai_assistant.suggestions.findDeals", "Show deals for selected people"),
          prompt: `Show me all deals associated with my ${selectedCount} selected contacts`,
          icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
        },
        {
          label: t("customers.ai_assistant.suggestions.findCompanies", "Find related companies"),
          prompt: `Find companies related to my ${selectedCount} selected contacts`,
          icon: /* @__PURE__ */ jsx(Building2, { className: "size-4" })
        }
      ];
    }
    return [
      {
        label: t("customers.ai_assistant.suggestions.searchPeople", "Search for a contact"),
        prompt: "Search for contacts by name, email, or company",
        icon: /* @__PURE__ */ jsx(Search, { className: "size-4" })
      },
      {
        label: t("customers.ai_assistant.suggestions.recentDeals", "Show recent deals"),
        prompt: "Show me the most recent deals and their current stages",
        icon: /* @__PURE__ */ jsx(Handshake, { className: "size-4" })
      },
      {
        label: t("customers.ai_assistant.suggestions.topCompanies", "List top companies"),
        prompt: "List companies with the most associated contacts and deals",
        icon: /* @__PURE__ */ jsx(Building2, { className: "size-4" })
      },
      {
        label: t("customers.ai_assistant.suggestions.activityOverview", "Activity overview"),
        prompt: "Give me an overview of recent customer activities and interactions",
        icon: /* @__PURE__ */ jsx(Users, { className: "size-4" })
      }
    ];
  }, [view, hasSelection, selectedCount, t]);
}
function useCustomerContextItems(pageContext) {
  const t = useT();
  return React.useMemo(() => {
    const items = [];
    const { selectedCount, totalMatching } = pageContext.extra;
    const view = pageContext.view;
    let selectedKey = "customers.ai_assistant.context.selectedPeople";
    let selectedFallback = "{count} contacts selected";
    let matchingKey = "customers.ai_assistant.context.matchingPeople";
    let matchingFallback = "{count} contacts in view";
    if (view === "customers.companies.list") {
      selectedKey = "customers.ai_assistant.context.selectedCompanies";
      selectedFallback = "{count} companies selected";
      matchingKey = "customers.ai_assistant.context.matchingCompanies";
      matchingFallback = "{count} companies in view";
    } else if (view === "customers.deals.list") {
      selectedKey = "customers.ai_assistant.context.selectedDeals";
      selectedFallback = "{count} deals selected";
      matchingKey = "customers.ai_assistant.context.matchingDeals";
      matchingFallback = "{count} deals in view";
    }
    if (selectedCount > 0) {
      items.push({ label: t(selectedKey, selectedFallback).replace("{count}", String(selectedCount)) });
    } else if (totalMatching > 0) {
      items.push({ label: t(matchingKey, matchingFallback).replace("{count}", String(totalMatching)) });
    }
    return items;
  }, [pageContext, t]);
}
function useViewCopy(view, selectedCount) {
  const t = useT();
  return React.useMemo(() => {
    const replaceCount = (s) => s.replace("{count}", String(selectedCount));
    if (view === "customers.deals.list") {
      return {
        welcomeDescriptionAll: t(
          "customers.ai_assistant.sheet.welcomeDescriptionAllDeals",
          "Ask about deals, pipeline, or close dates:"
        ),
        welcomeDescriptionSelection: replaceCount(
          t(
            "customers.ai_assistant.sheet.welcomeDescriptionSelectionDeals",
            "Ready to explore your {count} selected deals:"
          )
        ),
        descriptionWithSelection: replaceCount(
          t(
            "customers.ai_assistant.sheet.descriptionWithSelectionDeals",
            "Working with {count} selected deals. Ask about their stage, value, and close dates."
          )
        ),
        triggerAriaLabel: t(
          "customers.ai_assistant.trigger.ariaLabelDeals",
          "Open AI assistant for deals"
        )
      };
    }
    if (view === "customers.companies.list") {
      return {
        welcomeDescriptionAll: t(
          "customers.ai_assistant.sheet.welcomeDescriptionAllCompanies",
          "Ask me anything about your companies, deals, and activities:"
        ),
        welcomeDescriptionSelection: replaceCount(
          t(
            "customers.ai_assistant.sheet.welcomeDescriptionSelectionCompanies",
            "Ready to explore your {count} selected companies:"
          )
        ),
        descriptionWithSelection: replaceCount(
          t(
            "customers.ai_assistant.sheet.descriptionWithSelectionCompanies",
            "Working with {count} selected companies. Ask about their deals, contacts, and activities."
          )
        ),
        triggerAriaLabel: t(
          "customers.ai_assistant.trigger.ariaLabelCompanies",
          "Open AI assistant for companies"
        )
      };
    }
    return {
      welcomeDescriptionAll: t(
        "customers.ai_assistant.sheet.welcomeDescriptionAll",
        "Ask me anything about your customers, companies, and deals:"
      ),
      welcomeDescriptionSelection: replaceCount(
        t(
          "customers.ai_assistant.sheet.welcomeDescriptionSelection",
          "Ready to explore your {count} selected contacts:"
        )
      ),
      descriptionWithSelection: replaceCount(
        t(
          "customers.ai_assistant.sheet.descriptionWithSelection",
          "Working with {count} selected contacts. Ask about their details, deals, companies, and activities."
        )
      ),
      triggerAriaLabel: t(
        "customers.ai_assistant.trigger.ariaLabel",
        "Open AI assistant for people"
      )
    };
  }, [view, selectedCount, t]);
}
function useCustomerAgents() {
  const t = useT();
  return React.useMemo(
    () => [
      {
        id: CUSTOMERS_AI_INJECT_AGENT_ID,
        label: t("customers.ai_assistant.agents.account.label", "CRM Assistant"),
        description: t(
          "customers.ai_assistant.agents.account.description",
          "Explore people, companies, deals, and activities."
        ),
        icon: /* @__PURE__ */ jsx(AiIcon, { className: "size-4" })
      }
    ],
    [t]
  );
}
function AiAssistantTriggerWidget({ context }) {
  const t = useT();
  const dock = useAiDock();
  const [open, setOpen] = React.useState(false);
  const [popoverOpen, setPopoverOpen] = React.useState(false);
  const [activeAgent, setActiveAgent] = React.useState(CUSTOMERS_AI_INJECT_AGENT_ID);
  const [lastAgent, setLastAgent] = React.useState(null);
  const pageContext = React.useMemo(() => buildPageContext(context), [context]);
  const agents = useCustomerAgents();
  const selectedCount = pageContext.extra.selectedCount;
  const hasSelection = selectedCount > 0;
  const suggestions = useCustomerSuggestions(pageContext.view, hasSelection, selectedCount);
  const contextItems = useCustomerContextItems(pageContext);
  const viewCopy = useViewCopy(pageContext.view, selectedCount);
  const openAgent = React.useCallback((agentId) => {
    setActiveAgent(agentId);
    setLastAgent(agentId);
    setPopoverOpen(false);
    if (dock.state.assistant?.agent === agentId) {
      dock.dock(dock.state.assistant);
      setOpen(false);
      return;
    }
    setOpen(true);
  }, [dock]);
  const handleSelectAgent = React.useCallback((agentId) => {
    openAgent(agentId);
  }, [openAgent]);
  const handleMainTriggerClick = React.useCallback(() => {
    if (agents.length === 1) {
      openAgent(agents[0].id);
      return;
    }
    if (lastAgent && agents.some((a) => a.id === lastAgent)) {
      openAgent(lastAgent);
      return;
    }
    setPopoverOpen(true);
  }, [agents, lastAgent, openAgent]);
  const handleDock = React.useCallback(() => {
    const agent = agents.find((a) => a.id === activeAgent) ?? agents[0];
    if (!agent) return;
    dock.dock({
      agent: agent.id,
      label: agent.label,
      description: t("customers.ai_assistant.dock.subtitle", "Customers"),
      pageContext,
      placeholder: t(
        "customers.ai_assistant.sheet.composerPlaceholder",
        "Ask about people, companies, deals..."
      ),
      suggestions,
      contextItems,
      welcomeTitle: t("customers.ai_assistant.sheet.welcomeTitle", "CRM Assistant"),
      welcomeDescription: hasSelection ? viewCopy.welcomeDescriptionSelection : viewCopy.welcomeDescriptionAll
    });
    setOpen(false);
  }, [
    activeAgent,
    agents,
    contextItems,
    dock,
    hasSelection,
    pageContext,
    suggestions,
    t,
    viewCopy
  ]);
  const triggerLabel = viewCopy.triggerAriaLabel;
  const labelText = t("customers.ai_assistant.trigger.label", "AI");
  const moreAgentsLabel = t(
    "customers.ai_assistant.trigger.moreAgentsAriaLabel",
    "Choose an AI assistant"
  );
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(ButtonGroup, { children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: handleMainTriggerClick,
          "data-ai-customers-inject-trigger": "",
          "aria-label": triggerLabel,
          title: triggerLabel,
          className: cn("relative", "hover:bg-brand-violet/10"),
          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-customers-inject-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-customers-inject-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("customers.ai_assistant.popover.heading", "AI assistants") }),
          /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-0.5", children: agents.map((agent) => /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              onClick: () => handleSelectAgent(agent.id),
              "data-ai-customers-inject-agent-option": agent.id,
              className: "flex items-start 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",
              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 (no rounded corners, fills the
          // viewport). Desktop (≥sm): right-anchored side sheet.
          // The Dialog primitive ships a centering transform at the sm
          // breakpoint (`sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2
          // sm:-translate-y-1/2 sm:inset-auto`); each must be overridden
          // at the same `sm:` 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-customers-inject-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("customers.ai_assistant.sheet.dock", "Dock to side"),
                  title: t("customers.ai_assistant.sheet.dock", "Dock to side"),
                  onClick: handleDock,
                  "data-ai-customers-inject-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("customers.ai_assistant.sheet.title", "Customers AI 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-customers-inject-selection-pill": "",
                  "data-ai-customers-inject-selected-count": selectedCount,
                  children: t(
                    "customers.ai_assistant.sheet.selectionPill",
                    "Acting on {count} selected"
                  ).replace("{count}", String(selectedCount))
                }
              ) : null
            ] }),
            /* @__PURE__ */ jsx(DialogDescription, { children: hasSelection ? viewCopy.descriptionWithSelection : t(
              "customers.ai_assistant.sheet.description",
              "Your CRM assistant. Ask about people, companies, deals, and activities."
            ) })
          ] }),
          /* @__PURE__ */ jsx(
            CustomersChatBody,
            {
              activeAgent,
              pageContext,
              suggestions,
              contextItems,
              hasSelection,
              selectedCount,
              viewCopy
            }
          )
        ]
      }
    ) })
  ] });
}
function CustomersChatBody({
  activeAgent,
  pageContext,
  suggestions,
  contextItems,
  hasSelection,
  selectedCount,
  viewCopy
}) {
  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-customers-inject-chat-container": "", children: session ? /* @__PURE__ */ jsx(
      AiChat,
      {
        agent: activeAgent,
        conversationId: session.conversationId,
        pageContext,
        className: "h-full",
        placeholder: t(
          "customers.ai_assistant.sheet.composerPlaceholder",
          "Ask about people, companies, deals..."
        ),
        suggestions,
        contextItems,
        welcomeTitle: t("customers.ai_assistant.sheet.welcomeTitle", "CRM Assistant"),
        welcomeDescription: hasSelection ? viewCopy.welcomeDescriptionSelection : viewCopy.welcomeDescriptionAll
      },
      session.id
    ) : null })
  ] });
}
export {
  CUSTOMERS_AI_INJECT_AGENT_ID,
  computeCustomersAiInjectPageContext,
  AiAssistantTriggerWidget as default
};
//# sourceMappingURL=widget.client.js.map
