"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { CheckCircle } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT, useLocale } from "@open-mercato/shared/lib/i18n/context";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { KpiCard, DeltaBadge, Sparkline } from "@open-mercato/ui/backend/charts";
import { Avatar, AvatarStack } from "@open-mercato/ui/primitives/avatar";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { PipelineStageBar } from "./kpi/PipelineStageBar.js";
const compactNumberFormatter = new Intl.NumberFormat(void 0, {
  notation: "compact",
  maximumFractionDigits: 1
});
function formatCompact(value) {
  return compactNumberFormatter.format(value);
}
function buildCurrencySuffix(code, convertedAll) {
  if (!code) return convertedAll ? "" : "\u2248";
  return convertedAll ? code : `\u2248 ${code}`;
}
const KPI_TITLE_CLASS = "text-xs font-semibold uppercase tracking-wide text-muted-foreground";
function DealKpiCard(props) {
  return /* @__PURE__ */ jsx(KpiCard, { titleClassName: KPI_TITLE_CLASS, ...props });
}
function KpiDeltaBadge({
  direction,
  value,
  unit,
  title
}) {
  if (direction === "unchanged" && value === 0) {
    return /* @__PURE__ */ jsx(
      "span",
      {
        className: "inline-flex items-center rounded-md bg-status-neutral-bg px-2 py-0.5 text-xs font-medium text-status-neutral-text",
        title,
        children: "--"
      }
    );
  }
  return /* @__PURE__ */ jsx(DeltaBadge, { direction, value, unit, title });
}
function isObject(value) {
  return typeof value === "object" && value !== null;
}
function isDealsSummaryResponse(value) {
  if (!isObject(value)) return false;
  const { pipelineValue, activeDeals, wonThisQuarter, winRate } = value;
  return isObject(pipelineValue) && Array.isArray(pipelineValue.stages) && isObject(activeDeals) && Array.isArray(activeDeals.owners) && isObject(wonThisQuarter) && isObject(winRate) && Array.isArray(winRate.series);
}
function DealsKpiStrip({
  ownerNames,
  stageDictionary,
  pipelineCount,
  className,
  scopeVersion,
  reloadToken,
  onNeedsAttentionClick
}) {
  const t = useT();
  const locale = useLocale();
  const pluralCat = React.useCallback((count) => {
    try {
      return new Intl.PluralRules(locale).select(count);
    } catch {
      return count === 1 ? "one" : "other";
    }
  }, [locale]);
  const pf = React.useCallback((base, count) => {
    const cat = pluralCat(count);
    const key = `${base}.${cat}`;
    const out = t(key, { count });
    return out === key ? t(`${base}.other`, { count }) : out;
  }, [t, pluralCat]);
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [retryToken, setRetryToken] = React.useState(0);
  const previousScopeVersionRef = React.useRef(scopeVersion);
  const retry = React.useCallback(() => {
    setRetryToken((token) => token + 1);
  }, []);
  React.useEffect(() => {
    let cancelled = false;
    const scopeChanged = previousScopeVersionRef.current !== scopeVersion;
    previousScopeVersionRef.current = scopeVersion;
    if (scopeChanged) setData(null);
    setLoading(true);
    setError(null);
    apiCall("/api/customers/deals/summary").then((call) => {
      if (cancelled) return;
      if (!call.ok || !isDealsSummaryResponse(call.result)) {
        setError(t("customers.deals.list.kpi.error"));
        return;
      }
      setData(call.result);
    }).catch(() => {
      if (cancelled) return;
      setError(t("customers.deals.list.kpi.error"));
    }).finally(() => {
      if (!cancelled) setLoading(false);
    });
    return () => {
      cancelled = true;
    };
  }, [t, scopeVersion, reloadToken, retryToken]);
  const wrapperClassName = cn("space-y-2", className);
  const gridClassName = "grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4";
  if (loading && !data) {
    return /* @__PURE__ */ jsx("div", { className: wrapperClassName, children: /* @__PURE__ */ jsxs("div", { className: gridClassName, children: [
      /* @__PURE__ */ jsx(DealKpiCard, { loading: true, title: t("customers.deals.list.kpi.pipelineValue"), value: null }),
      /* @__PURE__ */ jsx(DealKpiCard, { loading: true, title: t("customers.deals.list.kpi.activeDeals"), value: null }),
      /* @__PURE__ */ jsx(DealKpiCard, { loading: true, title: t("customers.deals.list.kpi.wonThisQuarter"), value: null }),
      /* @__PURE__ */ jsx(DealKpiCard, { loading: true, title: t("customers.deals.list.kpi.winRate"), value: null })
    ] }) });
  }
  if (!data) {
    const errorMessage = error ?? t("customers.deals.list.kpi.error");
    return /* @__PURE__ */ jsx("div", { className: wrapperClassName, children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-4", children: [
      /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errorMessage }),
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "destructive-outline", size: "sm", onClick: retry, children: t("customers.deals.list.kpi.retry") })
    ] }) });
  }
  const currencySuffix = buildCurrencySuffix(data.baseCurrencyCode, data.convertedAll);
  const unassignedLabel = t("customers.deals.list.kpi.unassignedStage");
  const deltaTooltip = t("customers.deals.list.kpi.deltaTooltip");
  const deltaUnavailableTooltip = t("customers.deals.list.kpi.deltaUnavailable");
  const scopeLabel = t("customers.deals.list.kpi.scopeAllPipelinesThisQuarter");
  const unknownOwner = t("customers.deals.list.unknownOwner");
  const currencyHint = !data.convertedAll ? data.baseCurrencyCode ? t("customers.deals.list.kpi.currencyApproxMissing", {
    currencies: data.missingRateCurrencies.length ? data.missingRateCurrencies.join(", ") : currencySuffix
  }) : t("customers.deals.list.kpi.currencyApproxNoBase") : null;
  const attentionLabel = pf("customers.deals.list.kpi.frag.needAttention", data.activeDeals.needAttention);
  return /* @__PURE__ */ jsxs("div", { className: wrapperClassName, children: [
    error ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2", children: [
      /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error }),
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "destructive-outline", size: "2xs", onClick: retry, children: t("customers.deals.list.kpi.retry") })
    ] }) : null,
    loading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 text-xs text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-3 w-3" }),
      /* @__PURE__ */ jsx("span", { children: t("customers.deals.list.kpi.updating") })
    ] }) : null,
    /* @__PURE__ */ jsxs("div", { className: gridClassName, children: [
      /* @__PURE__ */ jsx(
        DealKpiCard,
        {
          title: t("customers.deals.list.kpi.pipelineValue"),
          value: data.pipelineValue.value,
          formatValue: formatCompact,
          suffix: currencySuffix,
          headerAction: /* @__PURE__ */ jsx(
            KpiDeltaBadge,
            {
              direction: data.pipelineValue.delta.direction,
              value: data.pipelineValue.delta.value,
              title: data.pipelineValue.delta.direction === "unchanged" && data.pipelineValue.delta.value === 0 ? deltaUnavailableTooltip : deltaTooltip
            }
          ),
          footer: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: scopeLabel }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.deals.list.kpi.activeAcrossPipelines", {
              deals: pf("customers.deals.list.kpi.frag.activeDeals", data.activeDeals.value),
              pipelines: pf("customers.deals.list.kpi.frag.pipelines", pipelineCount)
            }) }),
            currencyHint ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: currencyHint }) : null,
            /* @__PURE__ */ jsx(
              PipelineStageBar,
              {
                stages: data.pipelineValue.stages,
                stageDictionary,
                unassignedLabel
              }
            )
          ] })
        }
      ),
      /* @__PURE__ */ jsx(
        DealKpiCard,
        {
          title: t("customers.deals.list.kpi.activeDeals"),
          value: data.activeDeals.value,
          formatValue: formatCompact,
          headerAction: /* @__PURE__ */ jsx(
            KpiDeltaBadge,
            {
              direction: data.activeDeals.delta.direction,
              value: data.activeDeals.delta.value,
              title: data.activeDeals.delta.direction === "unchanged" && data.activeDeals.delta.value === 0 ? deltaUnavailableTooltip : deltaTooltip
            }
          ),
          footer: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: scopeLabel }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx("span", { children: pf("customers.deals.list.kpi.frag.owners", data.activeDeals.ownersCount) }),
              /* @__PURE__ */ jsx("span", { "aria-hidden": "true", children: "\xB7" }),
              onNeedsAttentionClick && data.activeDeals.needAttention > 0 ? /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "link",
                  size: "2xs",
                  className: "h-auto p-0 text-xs",
                  onClick: onNeedsAttentionClick,
                  children: attentionLabel
                }
              ) : /* @__PURE__ */ jsx("span", { children: attentionLabel })
            ] }),
            data.activeDeals.owners.length > 0 ? /* @__PURE__ */ jsx(AvatarStack, { max: 4, size: "sm", overflowCount: data.activeDeals.ownersOverflow, children: data.activeDeals.owners.map((owner) => {
              const ownerLabel = ownerNames[owner.id]?.trim() || unknownOwner;
              return /* @__PURE__ */ jsx(Avatar, { label: ownerLabel, size: "sm" }, owner.id);
            }) }) : null
          ] })
        }
      ),
      /* @__PURE__ */ jsx(
        DealKpiCard,
        {
          title: t("customers.deals.list.kpi.wonThisQuarter"),
          value: data.wonThisQuarter.value,
          formatValue: formatCompact,
          suffix: currencySuffix,
          headerAction: /* @__PURE__ */ jsx(
            KpiDeltaBadge,
            {
              direction: data.wonThisQuarter.delta.direction,
              value: data.wonThisQuarter.delta.value,
              title: data.wonThisQuarter.delta.direction === "unchanged" && data.wonThisQuarter.delta.value === 0 ? deltaUnavailableTooltip : deltaTooltip
            }
          ),
          footer: /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: scopeLabel }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx(CheckCircle, { className: "h-4 w-4 text-status-success-text", "aria-hidden": true }),
              /* @__PURE__ */ jsx("span", { children: pf("customers.deals.list.kpi.frag.dealsClosed", data.wonThisQuarter.dealsClosed) })
            ] }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.deals.list.kpi.avgDeal", {
              value: `${formatCompact(data.wonThisQuarter.avgDeal)}${currencySuffix ? ` ${currencySuffix}` : ""}`
            }) }),
            currencyHint ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: currencyHint }) : null
          ] })
        }
      ),
      /* @__PURE__ */ jsx(
        DealKpiCard,
        {
          title: t("customers.deals.list.kpi.winRate"),
          value: data.winRate.value,
          suffix: "%",
          headerAction: /* @__PURE__ */ jsx(
            KpiDeltaBadge,
            {
              direction: data.winRate.direction,
              value: Math.abs(data.winRate.deltaPp),
              unit: "pp",
              title: data.winRate.previousValue === 0 ? deltaUnavailableTooltip : deltaTooltip
            }
          ),
          footer: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: scopeLabel }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.deals.list.kpi.fromLastQuarter", { value: data.winRate.previousValue }) }),
            /* @__PURE__ */ jsx("div", { className: "text-primary", children: /* @__PURE__ */ jsx(
              Sparkline,
              {
                values: data.winRate.series.map((point) => point.rate),
                ariaLabel: t("customers.deals.list.kpi.winRate")
              }
            ) })
          ] })
        }
      )
    ] })
  ] });
}
var DealsKpiStrip_default = DealsKpiStrip;
export {
  DealsKpiStrip,
  DealsKpiStrip_default as default
};
//# sourceMappingURL=DealsKpiStrip.js.map
