"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { Building2, CalendarDays, Link2, Mail, Phone } 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 normalizePersonRecord(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;
  if (!displayName) return null;
  const subtitleSource = 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() : typeof record.jobTitle === "string" && record.jobTitle.trim().length ? record.jobTitle.trim() : typeof record.job_title === "string" && record.job_title.trim().length ? record.job_title.trim() : null;
  const role = typeof record.roleValue === "string" && record.roleValue.trim().length ? record.roleValue.trim() : typeof record.role === "string" && record.role.trim().length ? record.role.trim() : null;
  const jobTitle = typeof record.jobTitle === "string" ? record.jobTitle : typeof record.job_title === "string" ? record.job_title : null;
  const alreadyLinked = record.alreadyLinked === true || record.already_linked === true || record.excludedByLink === true;
  return {
    id,
    label: displayName,
    subtitle: subtitleSource,
    meta: {
      role,
      jobTitle,
      alreadyLinked,
      primaryEmail: typeof record.primaryEmail === "string" ? record.primaryEmail : typeof record.primary_email === "string" ? record.primary_email : null,
      primaryPhone: typeof record.primaryPhone === "string" ? record.primaryPhone : typeof record.primary_phone === "string" ? record.primary_phone : null
    }
  };
}
async function fetchPersonDetails(id) {
  try {
    const payload = await readApiResultOrThrow(
      `/api/customers/people/${encodeURIComponent(id)}`
    );
    const emails = [];
    const phones = [];
    if (typeof payload.primaryEmail === "string" && payload.primaryEmail.trim().length) {
      emails.push(payload.primaryEmail.trim());
    } else if (typeof payload.primary_email === "string" && payload.primary_email.trim().length) {
      emails.push(payload.primary_email.trim());
    }
    if (typeof payload.primaryPhone === "string" && payload.primaryPhone.trim().length) {
      phones.push(payload.primaryPhone.trim());
    } else if (typeof payload.primary_phone === "string" && payload.primary_phone.trim().length) {
      phones.push(payload.primary_phone.trim());
    }
    const companies = [];
    const rawCompanies = Array.isArray(payload.companies) ? payload.companies : [];
    rawCompanies.forEach((entry) => {
      if (!entry || typeof entry !== "object") return;
      const record = entry;
      const companyId = typeof record.id === "string" ? record.id : null;
      const name = typeof record.displayName === "string" ? record.displayName : typeof record.display_name === "string" ? record.display_name : null;
      if (!companyId || !name) return;
      companies.push({ id: companyId, name, isPrimary: Boolean(record.isPrimary ?? record.is_primary) });
    });
    let recentActivity = null;
    const activities = Array.isArray(payload.interactions) ? payload.interactions : Array.isArray(payload.activities) ? payload.activities : Array.isArray(payload.plannedActivitiesPreview) ? payload.plannedActivitiesPreview : [];
    if (activities.length > 0) {
      const entry = activities[0];
      if (entry && typeof entry === "object") {
        recentActivity = {
          title: (entry.title ?? "").toString() || "Interaction",
          occurredAt: typeof entry.occurredAt === "string" ? entry.occurredAt : null,
          summary: typeof entry.summary === "string" ? entry.summary : typeof entry.description === "string" ? entry.description : null
        };
      }
    }
    return { contactEmails: emails, contactPhones: phones, linkedCompanies: companies, recentActivity };
  } catch {
    return { contactEmails: [], contactPhones: [], linkedCompanies: [], recentActivity: 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 createPersonLinkAdapter(options) {
  const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
  const roleOptions = options.roleOptions ?? [];
  const roleKeywords = new Map(
    roleOptions.map((role) => [
      role.id,
      // build keyword list: id (as words), label words, lowercased
      [
        role.id.replace(/_/g, " ").toLowerCase(),
        role.label.toLowerCase()
      ]
    ])
  );
  const filters = roleOptions.length > 0 ? {
    options: [
      { id: "all", label: "All" },
      ...roleOptions.map((role) => ({ id: role.id, label: role.label }))
    ],
    defaultId: "all",
    clientFilter: (option, filterId) => {
      if (!filterId || filterId === "all") return true;
      const meta = option.meta ?? {};
      const keywords = roleKeywords.get(filterId) ?? [];
      const fields = [
        meta.role?.toLowerCase() ?? "",
        meta.jobTitle?.toLowerCase() ?? "",
        option.subtitle?.toLowerCase() ?? ""
      ];
      return keywords.some(
        (keyword) => fields.some((field) => field.includes(keyword))
      );
    }
  } : 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.excludeLinkedCompanyId) {
      params.set("excludeLinkedCompanyId", options.excludeLinkedCompanyId);
    }
    const payload = await readApiResultOrThrow(
      `/api/customers/people?${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" ? normalizePersonRecord(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/people?${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 = normalizePersonRecord(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 rolePill = meta.role ?? meta.jobTitle ?? null;
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Avatar, { label: option.label, variant: "monochrome", size: "md" }),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [
          /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-semibold text-foreground", children: option.label }),
          rolePill ? /* @__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: rolePill }) : null
        ] }),
        option.subtitle ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: option.subtitle }) : 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 email = details?.contactEmails?.[0] ?? meta.primaryEmail ?? null;
    const phone = details?.contactPhones?.[0] ?? meta.primaryPhone ?? null;
    const companies = details?.linkedCompanies ?? [];
    const activity = details?.recentActivity ?? null;
    const subtitle = option.subtitle ?? meta.jobTitle ?? 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", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsx(Avatar, { label: option.label, variant: "monochrome", size: "lg" }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("div", { className: "truncate text-base font-bold text-foreground", children: option.label }),
          subtitle ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: subtitle }) : null
        ] })
      ] }),
      email || phone ? /* @__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: "Contact" }),
        email ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5 text-xs text-foreground", children: [
          /* @__PURE__ */ jsx(Mail, { className: "size-3.5 text-muted-foreground" }),
          /* @__PURE__ */ jsx("span", { className: "truncate", children: email })
        ] }) : null,
        phone ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5 text-xs text-foreground", children: [
          /* @__PURE__ */ jsx(Phone, { className: "size-3.5 text-muted-foreground" }),
          /* @__PURE__ */ jsx("span", { className: "truncate", children: phone })
        ] }) : null
      ] }) : null,
      companies.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: [
          "Linked companies (",
          companies.length,
          ")"
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1.5", children: companies.map((company) => /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex items-center gap-2 rounded-md bg-muted/70 px-2.5 py-1.5 text-xs font-semibold text-foreground",
            children: [
              /* @__PURE__ */ jsx(Building2, { className: "size-3 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: company.name }),
              company.isPrimary ? /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-primary px-2 py-0.5 text-xs font-bold text-primary-foreground", children: "PRIMARY" }) : null
            ]
          },
          company.id
        )) })
      ] }) : null,
      activity ? /* @__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: "Recent activity" }),
        /* @__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__ */ jsxs("div", { className: "truncate text-xs font-semibold text-foreground", children: [
              activity.title,
              activity.occurredAt ? /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
                " \xB7 ",
                formatRelative(activity.occurredAt)
              ] }) : null
            ] }),
            activity.summary ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: activity.summary }) : null
          ] })
        ] })
      ] }) : null
    ] });
  };
  const renderLinkSettings = options.showLinkSettings ? (settings, onChange) => {
    const currentRole = settings.role ?? "";
    return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
      roleOptions.length > 0 ? /* @__PURE__ */ jsxs("label", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-muted-foreground", children: "Role at company" }),
        /* @__PURE__ */ jsxs(
          "select",
          {
            value: currentRole,
            onChange: (event) => onChange({ ...settings, role: event.target.value || null }),
            className: "h-9 rounded-md border border-border bg-card px-3 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring/40",
            children: [
              /* @__PURE__ */ jsx("option", { value: "", children: "\u2014" }),
              roleOptions.map((role) => /* @__PURE__ */ jsx("option", { value: role.id, children: role.label }, role.id))
            ]
          }
        )
      ] }) : null,
      /* @__PURE__ */ jsxs("label", { className: "flex cursor-pointer items-start gap-2", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            checked: Boolean(settings.isPrimary),
            onChange: (event) => onChange({ ...settings, isPrimary: event.target.checked }),
            className: "mt-0.5 size-4 shrink-0 rounded-sm border border-border accent-foreground"
          }
        ),
        /* @__PURE__ */ jsxs("span", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("span", { className: "block text-xs font-semibold text-foreground", children: "Set as PRIMARY contact" }),
          /* @__PURE__ */ jsx("span", { className: "mt-0.5 block text-xs text-muted-foreground", children: "Will appear at the top of company contacts" })
        ] })
      ] })
    ] });
  } : void 0;
  return {
    kind: "person",
    dialogTitle: options.dialogTitle,
    dialogSubtitle: options.dialogSubtitle,
    sectionLabel: options.sectionLabel ?? "MATCHING CONTACTS",
    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,
    renderLinkSettings,
    initialLinkSettings: options.showLinkSettings ? { role: null, isPrimary: false } : void 0,
    fetchDetails: fetchPersonDetails,
    searchPage,
    fetchByIds,
    addNew: options.addNew
  };
}
export {
  createPersonLinkAdapter
};
//# sourceMappingURL=personAdapter.js.map
