"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { AlertTriangle, Briefcase, CalendarDays, Link2 } from "lucide-react";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { cn } from "@open-mercato/shared/lib/utils";
const DEFAULT_PAGE_SIZE = 20;
function parseStatusFilter(filterId) {
  if (!filterId || filterId === "all" || filterId === "orphan") return null;
  return filterId;
}
function asRecord(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
}
function readTrimmedString(record, ...keys) {
  if (!record) return null;
  for (const key of keys) {
    const value = record[key];
    if (typeof value === "string" && value.trim().length) {
      return value.trim();
    }
  }
  return null;
}
function readDecimalValue(record, ...keys) {
  if (!record) return null;
  for (const key of keys) {
    const value = record[key];
    if (typeof value === "string" && value.trim().length) {
      return value.trim();
    }
    if (typeof value === "number" && Number.isFinite(value)) {
      return String(value);
    }
  }
  return null;
}
function normalizeAssociationRecord(entry) {
  const record = asRecord(entry);
  const id = readTrimmedString(record, "id");
  if (!id) return null;
  return {
    id,
    label: readTrimmedString(record, "label", "displayName", "display_name", "name", "title") ?? id,
    subtitle: readTrimmedString(record, "subtitle", "role", "roleLabel")
  };
}
function normalizeDealRecord(record) {
  const id = typeof record.id === "string" ? record.id : null;
  if (!id) return null;
  const title = typeof record.title === "string" && record.title.trim().length ? record.title.trim() : typeof record.name === "string" && record.name.trim().length ? record.name.trim() : null;
  const label = title ?? id;
  const code = typeof record.code === "string" ? record.code : typeof record.reference === "string" ? record.reference : null;
  const valueAmount = typeof record.valueAmount === "string" ? record.valueAmount : typeof record.value_amount === "string" ? record.value_amount : typeof record.value === "number" ? String(record.value) : null;
  const valueCurrency = typeof record.valueCurrency === "string" ? record.valueCurrency : typeof record.value_currency === "string" ? record.value_currency : null;
  const stage = typeof record.pipelineStage === "string" ? record.pipelineStage : typeof record.pipeline_stage === "string" ? record.pipeline_stage : typeof record.status === "string" ? record.status : null;
  const updatedAt = typeof record.updatedAt === "string" ? record.updatedAt : typeof record.updated_at === "string" ? record.updated_at : typeof record.createdAt === "string" ? record.createdAt : typeof record.created_at === "string" ? record.created_at : null;
  const anchorCompanies = typeof record.companies?.length === "number" ? record.companies.length : typeof record.companyCount === "number" ? record.companyCount : null;
  const isOrphan = anchorCompanies !== null ? anchorCompanies === 0 : void 0;
  const companyName = typeof record.companyName === "string" ? record.companyName : Array.isArray(record.companies) && record.companies.length > 0 ? normalizeAssociationRecord(record.companies[0])?.label ?? null : null;
  return {
    id,
    label,
    subtitle: null,
    meta: {
      code,
      valueAmount,
      valueCurrency,
      stage,
      updatedAt,
      isOrphan,
      companyName: typeof companyName === "string" ? companyName : null
    }
  };
}
async function fetchDealDetails(id, contextEntityId) {
  try {
    const payload = await readApiResultOrThrow(
      `/api/customers/deals/${encodeURIComponent(id)}`
    );
    const rootRecord = asRecord(payload);
    const dealRecord = asRecord(rootRecord?.deal) ?? rootRecord;
    const title = readTrimmedString(dealRecord, "title", "name") ?? id;
    const code = readTrimmedString(dealRecord, "code", "reference");
    const createdAt = readTrimmedString(dealRecord, "createdAt", "created_at");
    const valueAmount = readDecimalValue(dealRecord, "valueAmount", "value_amount", "value");
    const valueCurrency = readTrimmedString(
      dealRecord,
      "valueCurrency",
      "value_currency",
      "currency"
    );
    const stage = readTrimmedString(dealRecord, "pipelineStage", "pipeline_stage", "status");
    const companies = Array.isArray(rootRecord?.companies) ? rootRecord.companies.map((entry) => normalizeAssociationRecord(entry)).filter((entry) => entry !== null) : [];
    const people = Array.isArray(rootRecord?.people) ? rootRecord.people.map((entry) => normalizeAssociationRecord(entry)).filter((entry) => entry !== null) : [];
    const companiesCount = companies.filter((entry) => {
      return !contextEntityId || entry.id !== contextEntityId;
    }).length;
    const peopleCount = people.filter((entry) => {
      return !contextEntityId || entry.id !== contextEntityId;
    }).length;
    const keyPeople = people.slice(0, 3).map((entry) => ({
      id: entry.id,
      name: entry.label,
      role: entry.subtitle
    }));
    return {
      id,
      title,
      code,
      createdAt,
      stage,
      value: valueAmount ? { amount: valueAmount, currency: valueCurrency ?? null } : null,
      nextStep: null,
      keyPeople,
      anchors: { companies: companiesCount, people: peopleCount }
    };
  } catch {
    return {
      id,
      title: id,
      code: null,
      createdAt: null,
      stage: null,
      value: null,
      nextStep: null,
      keyPeople: [],
      anchors: { companies: 0, people: 0 }
    };
  }
}
function formatValue(amount, currency) {
  if (!amount) return null;
  const parsed = parseFloat(amount);
  if (!Number.isFinite(parsed)) return amount;
  const formatted = parsed.toLocaleString(void 0, { maximumFractionDigits: 2 });
  return currency ? `${formatted} ${currency}` : formatted;
}
function formatRelative(dateString) {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    const now = Date.now();
    const diffMs = now - date.getTime();
    const diffDays = Math.floor(diffMs / 864e5);
    if (diffDays <= 0) return "today";
    if (diffDays === 1) return "yesterday";
    if (diffDays < 30) return `${diffDays} days ago`;
    if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`;
    return `${Math.floor(diffDays / 365)} years ago`;
  } catch {
    return "";
  }
}
function createDealLinkAdapter(options) {
  const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
  const filters = {
    options: [
      { id: "all", label: "All" },
      { id: "open", label: "Open" },
      { id: "win", label: "Won" },
      { id: "loose", label: "Lost" },
      {
        id: "orphan",
        label: "Orphan",
        dotColor: "#eb9426"
        /* TODO(ds-review): #eb9426 — requires LinkEntityDialog to support semantic token classNames */
      }
    ],
    defaultId: "all",
    clientFilter: (option, filterId) => {
      if (!filterId || filterId === "all") return true;
      const meta = option.meta ?? {};
      if (filterId === "orphan") return meta.isOrphan === true;
      if (filterId === "open" || filterId === "win" || filterId === "loose") {
        return (meta.stage ?? "").toLowerCase().includes(filterId) || true;
      }
      return true;
    }
  };
  const searchPage = async (query, page, filterId) => {
    const params = new URLSearchParams({
      page: String(page),
      pageSize: String(pageSize)
    });
    if (query.trim().length > 0) {
      params.set("search", query.trim());
    }
    const status = parseStatusFilter(filterId);
    if (status) {
      params.set("status", status);
    }
    const payload = await readApiResultOrThrow(
      `/api/customers/deals?${params.toString()}`
    );
    const rawItems = Array.isArray(payload.items) ? payload.items : [];
    const exclude = new Set(options.excludeIds ?? []);
    let items = rawItems.map(
      (candidate) => candidate && typeof candidate === "object" ? normalizeDealRecord(candidate) : null
    ).filter((entry) => entry !== null && !exclude.has(entry.id));
    if (filterId === "orphan") {
      items = items.filter((item) => item.meta.isOrphan === true);
    }
    const totalPages = typeof payload.totalPages === "number" ? payload.totalPages : 1;
    const total = typeof payload.total === "number" ? payload.total : void 0;
    return { items, totalPages, total };
  };
  const fetchByIds = async (ids) => {
    const uniqueIds = Array.from(new Set(ids.map((value) => value.trim()).filter(Boolean)));
    if (!uniqueIds.length) return [];
    const params = new URLSearchParams({
      ids: uniqueIds.join(","),
      pageSize: String(Math.max(uniqueIds.length, 1))
    });
    try {
      const payload = await readApiResultOrThrow(
        `/api/customers/deals?${params.toString()}`
      );
      const rawItems = Array.isArray(payload.items) ? payload.items : [];
      const byId = /* @__PURE__ */ new Map();
      rawItems.forEach((record) => {
        if (!record || typeof record !== "object") return;
        const option = normalizeDealRecord(record);
        if (option) byId.set(option.id, option);
      });
      return uniqueIds.map((id) => byId.get(id) ?? { id, label: id, subtitle: null });
    } catch {
      return uniqueIds.map((id) => ({ id, label: id, subtitle: null }));
    }
  };
  const renderRow = (option, ctx) => {
    const meta = option.meta ?? {};
    const formattedValue = formatValue(meta.valueAmount ?? null, meta.valueCurrency ?? null);
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx("span", { className: "flex size-9 shrink-0 items-center justify-center rounded-md bg-muted/80 text-muted-foreground", children: /* @__PURE__ */ jsx(Briefcase, { className: "size-4" }) }),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-1.5", children: [
          /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-semibold text-foreground", children: option.label }),
          meta.code ? /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-sm bg-muted px-1.5 py-0.5 text-xs font-semibold uppercase text-muted-foreground", children: meta.code }) : null,
          meta.isOrphan ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 rounded-full bg-status-warning-bg px-2 py-0.5 text-xs font-semibold text-status-warning-text", children: [
            /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "inline-block size-1.5 rounded-full bg-status-warning-icon" }),
            "no company"
          ] }) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-0.5 flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground", children: [
          formattedValue ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: formattedValue }) : null,
          meta.stage ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "inline-block size-1 rounded-full bg-muted-foreground" }),
            /* @__PURE__ */ jsx("span", { children: meta.stage })
          ] }) : null,
          meta.companyName ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "inline-block size-1 rounded-full bg-muted-foreground" }),
            /* @__PURE__ */ jsx("span", { className: "truncate", children: meta.companyName })
          ] }) : null,
          meta.updatedAt ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "inline-block size-1 rounded-full bg-muted-foreground" }),
            /* @__PURE__ */ jsx("span", { children: formatRelative(meta.updatedAt) })
          ] }) : null
        ] })
      ] }),
      /* @__PURE__ */ jsx(
        "span",
        {
          role: "checkbox",
          "aria-checked": ctx.selected,
          "aria-label": `Select ${option.label}`,
          className: cn(
            "inline-flex size-5 shrink-0 items-center justify-center rounded-full border",
            ctx.selected ? "border-foreground bg-foreground text-background" : "border-border bg-background"
          ),
          children: ctx.selected ? /* @__PURE__ */ jsx("svg", { viewBox: "0 0 12 12", className: "size-3", fill: "none", stroke: "currentColor", strokeWidth: 2.5, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M2.5 6.5l2.5 2.5 4.5-5" }) }) : null
        }
      )
    ] });
  };
  const renderPreview = (option, details) => {
    const meta = option.meta ?? {};
    const derived = details ?? {
      id: option.id,
      title: option.label,
      code: meta.code ?? null,
      createdAt: null,
      stage: null,
      value: meta.valueAmount ? { amount: meta.valueAmount, currency: meta.valueCurrency ?? null } : null,
      nextStep: null,
      keyPeople: [],
      anchors: void 0
    };
    const isOrphan = meta.isOrphan || (derived.anchors ? derived.anchors.companies === 0 : false);
    const formattedValue = derived.value ? formatValue(derived.value.amount, derived.value.currency) : null;
    const createdRel = derived.createdAt ? `Created ${formatRelative(derived.createdAt)}` : null;
    return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3.5 rounded-xl border border-border/70 bg-card p-4", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("div", { className: "text-base font-bold text-foreground", children: derived.title }),
        /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-1.5 text-xs text-muted-foreground", children: [
          derived.code ? /* @__PURE__ */ jsx("span", { children: derived.code }) : null,
          derived.code && createdRel ? /* @__PURE__ */ jsx("span", { children: "\xB7" }) : null,
          createdRel ? /* @__PURE__ */ jsx("span", { children: createdRel }) : null
        ] })
      ] }),
      isOrphan ? /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2 rounded-md bg-status-warning-bg px-3 py-2.5", children: [
        /* @__PURE__ */ jsx(AlertTriangle, { className: "mt-0.5 size-3.5 text-status-warning-icon" }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("div", { className: "text-xs font-semibold text-status-warning-text", children: options.orphanWarningTitle }),
          /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: options.orphanWarningMessage })
        ] })
      ] }) : null,
      formattedValue ? /* @__PURE__ */ jsxs("div", { className: "flex items-baseline gap-3", children: [
        /* @__PURE__ */ jsx("div", { className: "text-2xl font-bold text-foreground", children: formattedValue }),
        /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: "potential value" })
      ] }) : null,
      derived.stage ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "text-overline font-semibold uppercase tracking-wide text-muted-foreground", children: "Stage" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
          /* @__PURE__ */ jsx("span", { className: "inline-block size-2 rounded-full bg-foreground" }),
          /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-foreground", children: derived.stage })
        ] })
      ] }) : null,
      derived.nextStep ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "h-px w-full bg-border/70" }),
        /* @__PURE__ */ jsx("div", { className: "text-overline font-semibold uppercase tracking-wide text-muted-foreground", children: "Next step" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
          /* @__PURE__ */ jsx(CalendarDays, { className: "mt-0.5 size-3 text-muted-foreground" }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            /* @__PURE__ */ jsx("div", { className: "truncate text-xs font-semibold text-foreground", children: derived.nextStep.title }),
            derived.nextStep.assignee ? /* @__PURE__ */ jsxs("div", { className: "mt-0.5 text-xs text-muted-foreground", children: [
              "Assigned: ",
              derived.nextStep.assignee
            ] }) : null
          ] })
        ] })
      ] }) : null,
      derived.keyPeople && derived.keyPeople.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "h-px w-full bg-border/70" }),
        /* @__PURE__ */ jsxs("div", { className: "text-overline font-semibold uppercase tracking-wide text-muted-foreground", children: [
          "Key people (",
          derived.keyPeople.length,
          ")"
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1.5", children: derived.keyPeople.map((person) => /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex items-center gap-2 rounded-md bg-muted/60 px-2.5 py-1.5",
            children: [
              /* @__PURE__ */ jsx(Avatar, { label: person.name, variant: "monochrome", size: "sm" }),
              /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-foreground", children: person.name }),
              person.role ? /* @__PURE__ */ jsx("span", { className: "ml-auto inline-flex items-center rounded-sm border border-border px-1.5 py-0.5 text-xs font-semibold text-muted-foreground", children: person.role }) : null
            ]
          },
          person.id || person.name
        )) })
      ] }) : null
    ] });
  };
  const computeOrphanWarning = async (option) => {
    const details = await fetchDealDetails(option.id, options.contextEntityId);
    const anchors = details.anchors ?? { companies: 0, people: 0 };
    return anchors.companies + anchors.people < 1 ? options.orphanWarningMessage : null;
  };
  return {
    kind: "deal",
    dialogTitle: options.dialogTitle,
    dialogSubtitle: options.dialogSubtitle,
    sectionLabel: options.sectionLabel ?? "MATCHING DEALS",
    searchPlaceholder: options.searchPlaceholder,
    searchEmptyHint: options.searchEmptyHint,
    selectedEmptyHint: options.selectedEmptyHint,
    confirmButtonLabel: options.confirmButtonLabel,
    defaultAvatarIcon: options.defaultAvatarIcon,
    headerIcon: options.headerIcon ?? /* @__PURE__ */ jsx(Link2, { className: "size-5" }),
    filters,
    renderRow,
    renderPreview,
    fetchDetails: (id) => fetchDealDetails(id, options.contextEntityId),
    searchPage,
    fetchByIds,
    computeOrphanWarning,
    addNew: options.addNew
  };
}
export {
  createDealLinkAdapter
};
//# sourceMappingURL=dealAdapter.js.map
