"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { Building2, CalendarDays, Globe, Link2, Users } from "lucide-react";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { cn } from "@open-mercato/shared/lib/utils";
const DEFAULT_PAGE_SIZE = 20;
function normalizeCompanyRecord(record) {
  const id = typeof record.id === "string" ? record.id : null;
  if (!id) return null;
  const displayName = typeof record.displayName === "string" && record.displayName.trim().length ? record.displayName.trim() : typeof record.display_name === "string" && record.display_name.trim().length ? record.display_name.trim() : null;
  const industry = typeof record.industry === "string" && record.industry.trim().length ? record.industry.trim() : null;
  const domain = typeof record.domain === "string" && record.domain.trim().length ? record.domain.trim() : typeof record.websiteUrl === "string" && record.websiteUrl.trim().length ? record.websiteUrl.trim() : typeof record.website_url === "string" && record.website_url.trim().length ? record.website_url.trim() : typeof record.primaryEmail === "string" && record.primaryEmail.trim().length ? record.primaryEmail.trim() : typeof record.primary_email === "string" && record.primary_email.trim().length ? record.primary_email.trim() : null;
  const label = displayName ?? domain ?? id;
  const subtitle = domain && domain !== label ? domain : null;
  return {
    id,
    label,
    subtitle,
    meta: {
      industry,
      domain
    }
  };
}
async function fetchCompanyDetails(id) {
  try {
    const payload = await readApiResultOrThrow(
      `/api/customers/companies/${encodeURIComponent(id)}`
    );
    const industry = typeof payload.industry === "string" ? payload.industry : null;
    const domain = typeof payload.domain === "string" ? payload.domain : typeof payload.websiteUrl === "string" ? payload.websiteUrl : typeof payload.website_url === "string" ? payload.website_url : null;
    const websiteUrl = typeof payload.websiteUrl === "string" ? payload.websiteUrl : typeof payload.website_url === "string" ? payload.website_url : null;
    const peopleRaw = Array.isArray(payload.people) ? payload.people : [];
    const recentPeople = peopleRaw.slice(0, 3).map((entry) => {
      const record = entry;
      const personId = typeof record.id === "string" ? record.id : "";
      const name = typeof record.displayName === "string" ? record.displayName : typeof record.display_name === "string" ? record.display_name : personId;
      const role = typeof record.roleValue === "string" ? record.roleValue : typeof record.role === "string" ? record.role : null;
      return { id: personId, name, role };
    });
    return {
      industry,
      domain,
      websiteUrl,
      peopleCount: peopleRaw.length,
      recentPeople,
      lastContactAt: typeof payload.lastContactAt === "string" ? payload.lastContactAt : typeof payload.last_contact_at === "string" ? payload.last_contact_at : null
    };
  } catch {
    return {
      industry: null,
      domain: null,
      websiteUrl: null,
      peopleCount: 0,
      recentPeople: [],
      lastContactAt: null
    };
  }
}
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 createCompanyLinkAdapter(options) {
  const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
  const industryOptions = options.industryOptions ?? [];
  const filters = industryOptions.length > 0 ? {
    options: [{ id: "all", label: "All" }, ...industryOptions],
    defaultId: "all",
    clientFilter: (option, filterId) => {
      if (!filterId || filterId === "all") return true;
      const meta = option.meta ?? {};
      return (meta.industry ?? "").toLowerCase() === filterId.toLowerCase();
    }
  } : void 0;
  const searchPage = async (query, page, filterId) => {
    const params = new URLSearchParams({
      page: String(page),
      pageSize: String(pageSize),
      sortField: "name",
      sortDir: "asc"
    });
    if (query.trim().length > 0) {
      params.set("search", query.trim());
    }
    if (options.excludeLinkedPersonId) {
      params.set("excludeLinkedPersonId", options.excludeLinkedPersonId);
    }
    if (filterId && filterId !== "all") {
      params.set("industry", filterId);
    }
    const payload = await readApiResultOrThrow(
      `/api/customers/companies?${params.toString()}`
    );
    const rawItems = Array.isArray(payload.items) ? payload.items : [];
    const exclude = new Set(options.excludeIds ?? []);
    const items = rawItems.map(
      (candidate) => candidate && typeof candidate === "object" ? normalizeCompanyRecord(candidate) : null
    ).filter((entry) => entry !== null && !exclude.has(entry.id));
    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/companies?${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 = normalizeCompanyRecord(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 ?? {};
    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(Building2, { 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.industry ? /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-sm bg-muted px-1.5 py-0.5 text-xs font-semibold text-muted-foreground", children: meta.industry }) : null
        ] }),
        meta.domain ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: meta.domain }) : 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 industry = details?.industry ?? meta.industry ?? null;
    const domain = details?.domain ?? meta.domain ?? null;
    const websiteUrl = details?.websiteUrl ?? null;
    const people = details?.recentPeople ?? [];
    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", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsx("span", { className: "flex size-12 shrink-0 items-center justify-center rounded-lg bg-muted/80 text-muted-foreground", children: /* @__PURE__ */ jsx(Building2, { className: "size-5" }) }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("div", { className: "truncate text-base font-bold text-foreground", children: option.label }),
          industry ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: industry }) : null
        ] })
      ] }),
      domain || websiteUrl ? /* @__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: "Web" }),
        websiteUrl ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5 text-xs text-foreground", children: [
          /* @__PURE__ */ jsx(Globe, { className: "size-3.5 text-muted-foreground" }),
          /* @__PURE__ */ jsx(
            "a",
            {
              href: websiteUrl.startsWith("http") ? websiteUrl : `https://${websiteUrl}`,
              target: "_blank",
              rel: "noreferrer",
              className: "truncate hover:underline",
              children: websiteUrl
            }
          )
        ] }) : domain ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5 text-xs text-foreground", children: [
          /* @__PURE__ */ jsx(Globe, { className: "size-3.5 text-muted-foreground" }),
          /* @__PURE__ */ jsx("span", { className: "truncate", children: domain })
        ] }) : null
      ] }) : null,
      people.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: [
          "People (",
          details?.peopleCount ?? people.length,
          ")"
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1.5", children: people.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(Users, { className: "size-3 text-muted-foreground" }),
              /* @__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,
      details?.lastContactAt ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "h-px w-full bg-border/70" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsx(CalendarDays, { className: "size-3" }),
          "Last contact ",
          formatRelative(details.lastContactAt)
        ] })
      ] }) : null
    ] });
  };
  return {
    kind: "company",
    dialogTitle: options.dialogTitle,
    dialogSubtitle: options.dialogSubtitle,
    sectionLabel: options.sectionLabel ?? "MATCHING COMPANIES",
    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: fetchCompanyDetails,
    searchPage,
    fetchByIds,
    addNew: options.addNew
  };
}
export {
  createCompanyLinkAdapter
};
//# sourceMappingURL=companyAdapter.js.map
