"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ArrowUpRight, EyeOff, Handshake } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { formatCurrency } from "./utils.js";
function ActiveDealCard({ deals, onHide }) {
  const t = useT();
  const [pipelineStages, setPipelineStages] = React.useState([]);
  const activeDeals = React.useMemo(
    () => deals.filter((d) => d.status !== "won" && d.status !== "lost" && d.status !== "closed"),
    [deals]
  );
  const topDeal = React.useMemo(() => {
    if (activeDeals.length === 0) return null;
    return [...activeDeals].sort((a, b) => {
      const va = typeof a.valueAmount === "number" ? a.valueAmount : parseFloat(String(a.valueAmount ?? "0"));
      const vb = typeof b.valueAmount === "number" ? b.valueAmount : parseFloat(String(b.valueAmount ?? "0"));
      return vb - va;
    })[0];
  }, [activeDeals]);
  React.useEffect(() => {
    let active = true;
    if (!topDeal?.pipelineId) {
      setPipelineStages([]);
      return () => {
        active = false;
      };
    }
    readApiResultOrThrow(
      `/api/customers/pipeline-stages?pipelineId=${encodeURIComponent(topDeal.pipelineId)}`
    ).then((payload) => {
      if (!active) return;
      const nextStages = (Array.isArray(payload?.items) ? payload.items : []).map((item) => {
        const id = typeof item.id === "string" ? item.id : null;
        const label = typeof item.label === "string" ? item.label.trim() : "";
        if (!id || label.length === 0) return null;
        return { id, label };
      }).filter((stage) => stage !== null);
      setPipelineStages(nextStages);
    }).catch(() => {
      if (!active) return;
      setPipelineStages([]);
    });
    return () => {
      active = false;
    };
  }, [topDeal?.pipelineId]);
  if (!topDeal) {
    return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-5", children: [
      /* @__PURE__ */ jsxs("h3", { className: "flex items-center gap-2 text-sm font-semibold text-foreground", children: [
        /* @__PURE__ */ jsx(Handshake, { className: "size-4" }),
        t("customers.companies.dashboard.activeDeal", "Active deal")
      ] }),
      /* @__PURE__ */ jsx("p", { className: "mt-3 text-sm text-muted-foreground", children: t("customers.companies.dashboard.noDeals", "No active deals") })
    ] });
  }
  const amount = typeof topDeal.valueAmount === "number" ? topDeal.valueAmount : parseFloat(String(topDeal.valueAmount ?? "0"));
  const currentStage = topDeal.pipelineStage ?? null;
  const stageIndex = topDeal.pipelineStageId && pipelineStages.length > 0 ? pipelineStages.findIndex((stage) => stage.id === topDeal.pipelineStageId) : currentStage ? pipelineStages.findIndex((stage) => stage.label.toLowerCase() === currentStage.toLowerCase()) : -1;
  const hasPipelineProgress = pipelineStages.length > 0 && stageIndex >= 0;
  return /* @__PURE__ */ jsxs("div", { className: "group relative rounded-lg border bg-card p-5", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxs("h3", { className: "flex items-center gap-2 text-sm font-semibold text-foreground", children: [
        /* @__PURE__ */ jsx(Handshake, { className: "size-4" }),
        t("customers.companies.dashboard.activeDeal", "Active deal")
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
        onHide && /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "ghost",
            size: "xs",
            onClick: onHide,
            className: "opacity-0 transition-opacity group-hover:opacity-60",
            "aria-label": t("customers.companies.dashboard.hideTile", "Hide tile"),
            children: /* @__PURE__ */ jsx(EyeOff, { className: "size-3.5" })
          }
        ),
        /* @__PURE__ */ jsx(ArrowUpRight, { className: "size-4 text-muted-foreground" })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
      /* @__PURE__ */ jsx("p", { className: "font-semibold text-foreground", children: topDeal.title }),
      topDeal.createdAt && /* @__PURE__ */ jsxs("p", { className: "mt-0.5 text-xs text-muted-foreground", children: [
        t("customers.companies.dashboard.created", "Created"),
        " ",
        new Date(topDeal.createdAt).toLocaleDateString()
      ] }),
      currentStage && hasPipelineProgress && /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx("div", { className: "flex gap-1", children: pipelineStages.map((stage, idx) => /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: cn(
              "h-1.5 rounded-full",
              idx <= stageIndex ? "bg-primary" : "bg-muted"
            )
          }
        ),
        /* @__PURE__ */ jsx("p", { className: cn(
          "mt-1 text-xs",
          idx <= stageIndex ? "font-medium text-foreground" : "text-muted-foreground"
        ), children: stage.label })
      ] }, stage.id)) }) }),
      currentStage && !hasPipelineProgress && /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: currentStage }) }),
      Number.isFinite(amount) && amount > 0 && /* @__PURE__ */ jsxs("p", { className: "mt-2 text-lg font-bold text-foreground", children: [
        formatCurrency(amount, topDeal.valueCurrency),
        /* @__PURE__ */ jsx("span", { className: "ml-1.5 text-xs font-normal text-muted-foreground", children: t("customers.companies.dashboard.potentialValue", "potential value") })
      ] })
    ] })
  ] });
}
export {
  ActiveDealCard
};
//# sourceMappingURL=ActiveDealCard.js.map
