"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import Link from "next/link";
import {
  Building2,
  Clock,
  Copy,
  CreditCard,
  ExternalLink,
  FileText,
  Hash,
  Link2Off,
  MapPin,
  TrendingUp,
  Zap,
  Tag as TagIcon,
  Users
} from "lucide-react";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { renderDictionaryIcon } from "../../../dictionaries/components/dictionaryAppearance.js";
import { formatFallbackLabel } from "./utils.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
function copyToClipboard(text, t) {
  navigator.clipboard.writeText(text).then(() => {
    flash(t("customers.companies.detail.copied", "Copied to clipboard"), "success");
  }).catch((err) => logger.warn("clipboard write failed", { component: "CompanyCard", err }));
}
function formatRelativeTime(isoDate, t) {
  const date = new Date(isoDate);
  const now = /* @__PURE__ */ new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffDays = Math.floor(diffMs / (1e3 * 60 * 60 * 24));
  if (diffDays === 0) {
    return `${t("customers.companies.detail.relativeTime.today", "today")}, ${date.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" })}`;
  }
  if (diffDays === 1) return t("customers.companies.detail.relativeTime.oneDayAgo", "1 day ago");
  if (diffDays < 7) return t("customers.companies.detail.relativeTime.daysAgo", "{{days}} days ago", { days: diffDays });
  if (diffDays < 30) return t("customers.companies.detail.relativeTime.weeksAgo", "{{weeks}} wk. ago", { weeks: Math.floor(diffDays / 7) });
  return t("customers.companies.detail.relativeTime.monthsAgo", "{{months}} mo. ago", { months: Math.floor(diffDays / 30) });
}
function formatCurrency(amount, currency) {
  try {
    return new Intl.NumberFormat(void 0, {
      style: "currency",
      currency,
      maximumFractionDigits: 0,
      notation: amount >= 1e6 ? "compact" : "standard"
    }).format(amount);
  } catch {
    if (amount >= 1e6) return `${(amount / 1e6).toFixed(2)} M ${currency}`;
    if (amount >= 1e3) return `${Math.round(amount / 1e3)}k ${currency}`;
    return `${amount} ${currency}`;
  }
}
function ColorBadge({
  value,
  map,
  fallbackIcon
}) {
  const entry = map?.[value];
  const color = entry?.color ?? null;
  const icon = entry?.icon ?? null;
  const label = entry?.label ?? formatFallbackLabel(value);
  const colorStyle = color ? { color, borderColor: color, backgroundColor: `${color}1A` } : void 0;
  return /* @__PURE__ */ jsxs(
    Badge,
    {
      variant: "outline",
      className: "rounded-sm gap-1.5 text-xs font-medium",
      style: colorStyle,
      children: [
        icon ? renderDictionaryIcon(icon, "size-2.5") : fallbackIcon ?? null,
        label
      ]
    }
  );
}
function StatusDotBadge({
  value,
  map
}) {
  const entry = map?.[value];
  const color = entry?.color ?? null;
  const label = entry?.label ?? formatFallbackLabel(value);
  const colorStyle = color ? { color, borderColor: color, backgroundColor: `${color}1A` } : void 0;
  return /* @__PURE__ */ jsxs(
    Badge,
    {
      variant: "outline",
      className: "rounded-sm gap-1.5 text-xs font-medium",
      style: colorStyle,
      children: [
        /* @__PURE__ */ jsx(
          "span",
          {
            className: "size-1.5 rounded-full",
            style: color ? { backgroundColor: color } : void 0
          }
        ),
        label
      ]
    }
  );
}
function BillingRow({
  icon: Icon,
  label,
  value,
  showCopy = true,
  showDottedLine = true,
  t
}) {
  return /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-1.5 min-h-[22px]", children: [
    /* @__PURE__ */ jsx(Icon, { className: "size-3 shrink-0 text-muted-foreground" }),
    /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground font-medium shrink-0", children: [
      label,
      ":"
    ] }),
    showDottedLine && /* @__PURE__ */ jsx("div", { className: "mx-1 hidden flex-1 border-b border-dotted border-border/50 sm:block" }),
    /* @__PURE__ */ jsx("span", { className: "min-w-0 break-words text-xs font-medium text-foreground", children: value }),
    showCopy && /* @__PURE__ */ jsx(
      IconButton,
      {
        type: "button",
        variant: "ghost",
        size: "sm",
        className: "h-auto shrink-0 text-muted-foreground hover:text-foreground transition-colors p-0",
        onClick: () => copyToClipboard(value, t),
        "aria-label": t("customers.companies.detail.copy", "Copy"),
        children: /* @__PURE__ */ jsx(Copy, { className: "size-2.5" })
      }
    )
  ] });
}
function CompanyCard({
  data,
  personName,
  statusMap,
  lifecycleMap,
  temperatureMap,
  renewalQuarterMap,
  roleMap,
  onUnlink,
  unlinkLabel,
  unlinkDisabled
}) {
  const t = useT();
  const resolvedUnlinkLabel = unlinkLabel ?? t("customers.people.detail.companies.unlinkAction", "Unlink");
  const hasBillingSection = data.profile?.legalName || data.primaryAddress?.formatted || data.billing?.bankName || data.billing?.bankAccountMasked || data.billing?.paymentTerms || data.billing?.preferredCurrency;
  const dealValue = data.activeDeal?.valueAmount && data.activeDeal?.valueCurrency ? `${data.activeDeal.valueAmount} ${data.activeDeal.valueCurrency}` : null;
  return /* @__PURE__ */ jsxs("div", { className: "min-w-0 overflow-hidden rounded-2xl border border-border/60 bg-card", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 px-5 py-5 sm:flex-row sm:items-center", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-3", children: [
        /* @__PURE__ */ jsx("div", { className: "flex size-12 shrink-0 items-center justify-center rounded-xl bg-muted", children: /* @__PURE__ */ jsx(Building2, { className: "size-5 text-muted-foreground" }) }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
            /* @__PURE__ */ jsx("span", { className: "break-words text-base font-bold", children: data.displayName }),
            data.isPrimary && /* @__PURE__ */ jsx(
              StatusBadge,
              {
                variant: "info",
                className: "rounded-sm px-1.5 py-0 text-overline font-bold uppercase tracking-wider",
                children: t("customers.people.detail.companies.primaryBadge", "Primary")
              }
            )
          ] }),
          data.subtitle && /* @__PURE__ */ jsx("p", { className: "break-words text-sm text-muted-foreground", children: data.subtitle })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 self-start sm:self-auto", children: [
        onUnlink ? /* @__PURE__ */ jsx(
          IconButton,
          {
            variant: "ghost",
            size: "sm",
            type: "button",
            "aria-label": resolvedUnlinkLabel,
            disabled: unlinkDisabled,
            onClick: () => {
              void onUnlink();
            },
            children: /* @__PURE__ */ jsx(Link2Off, { className: "size-4" })
          }
        ) : null,
        /* @__PURE__ */ jsx(Link, { href: `/backend/customers/companies-v2/${data.companyId}`, children: /* @__PURE__ */ jsx(IconButton, { variant: "ghost", size: "sm", type: "button", children: /* @__PURE__ */ jsx(ExternalLink, { className: "size-4" }) }) })
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "border-t border-border/60" }),
    /* @__PURE__ */ jsxs("div", { className: "px-5 py-4 space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1.5", children: [
        data.profile?.industry && /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "rounded-sm gap-1.5 text-xs font-medium", children: [
          /* @__PURE__ */ jsx(TagIcon, { className: "size-2.5" }),
          data.profile.industry
        ] }),
        data.profile?.sizeBucket && /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "rounded-sm gap-1.5 text-xs font-medium", children: [
          /* @__PURE__ */ jsx(Users, { className: "size-2.5" }),
          data.profile.sizeBucket,
          " ",
          t("customers.companies.detail.employees", "employees")
        ] }),
        data.status && /* @__PURE__ */ jsx(StatusDotBadge, { value: data.status, map: statusMap }),
        data.renewalQuarter && /* @__PURE__ */ jsx(
          ColorBadge,
          {
            value: data.renewalQuarter,
            map: renewalQuarterMap,
            fallbackIcon: /* @__PURE__ */ jsx(Clock, { className: "size-2.5" })
          }
        ),
        data.temperature && /* @__PURE__ */ jsx(
          ColorBadge,
          {
            value: data.temperature,
            map: temperatureMap,
            fallbackIcon: /* @__PURE__ */ jsx(Zap, { className: "size-2.5" })
          }
        )
      ] }),
      data.roles.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx("span", { className: "text-overline font-bold uppercase tracking-wider text-muted-foreground", children: t("customers.companies.detail.roleInCompany", "ROLE OF {{name}} IN THIS COMPANY", { name: personName.toUpperCase() }) }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: data.roles.map((role) => /* @__PURE__ */ jsx(
          ColorBadge,
          {
            value: role.roleValue,
            map: roleMap
          },
          role.id
        )) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "border-t border-border/60" }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("span", { className: "text-overline font-bold uppercase tracking-wider text-muted-foreground block mb-1", children: t("customers.companies.detail.activeDeal", "ACTIVE DEAL") }),
          /* @__PURE__ */ jsx("span", { className: "flex min-w-0 items-center gap-1 text-xs font-medium text-foreground", children: data.activeDeal ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(Building2, { className: "size-3 shrink-0" }),
            /* @__PURE__ */ jsxs("span", { className: "min-w-0 break-words", children: [
              data.activeDeal.title,
              dealValue ? ` \xB7 ${dealValue}` : ""
            ] })
          ] }) : "\u2014" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("span", { className: "text-overline font-bold uppercase tracking-wider text-muted-foreground block mb-1", children: t("customers.companies.detail.lastContact", "LAST CONTACT") }),
          /* @__PURE__ */ jsx("span", { className: "flex min-w-0 items-center gap-1 break-words text-xs font-medium text-foreground", children: data.lastContactAt ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(Clock, { className: "size-3 shrink-0" }),
            formatRelativeTime(data.lastContactAt, t)
          ] }) : "\u2014" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
          /* @__PURE__ */ jsx("span", { className: "text-overline font-bold uppercase tracking-wider text-muted-foreground block mb-1", children: "CLV" }),
          /* @__PURE__ */ jsx("span", { className: "flex min-w-0 items-center gap-1 break-words text-xs font-medium text-foreground", children: data.clv ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(TrendingUp, { className: "size-3 shrink-0" }),
            formatCurrency(data.clv.amount, data.clv.currency)
          ] }) : "\u2014" })
        ] })
      ] }),
      hasBillingSection && /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "border-t border-border/60" }),
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg bg-muted/40 border border-border/40 px-3.5 py-3 space-y-1.5", children: [
          data.profile?.legalName && /* @__PURE__ */ jsx(BillingRow, { icon: FileText, label: t("customers.companies.detail.billing.name", "Name"), value: data.profile.legalName, t }),
          data.primaryAddress?.formatted && /* @__PURE__ */ jsx(
            BillingRow,
            {
              icon: MapPin,
              label: t("customers.companies.detail.billing.address", "Address"),
              value: data.primaryAddress.formatted,
              t
            }
          ),
          (data.billing?.bankName || data.billing?.bankAccountMasked) && /* @__PURE__ */ jsx(
            BillingRow,
            {
              icon: CreditCard,
              label: t("customers.fields.bankIban", "Bank / IBAN"),
              value: [data.billing?.bankName, data.billing?.bankAccountMasked].filter(Boolean).join(" \xB7 "),
              t
            }
          ),
          data.billing?.paymentTerms && /* @__PURE__ */ jsx(
            BillingRow,
            {
              icon: Clock,
              label: t("customers.companies.detail.billing.paymentTerms", "Payment terms"),
              value: data.billing.paymentTerms,
              showCopy: false,
              showDottedLine: false,
              t
            }
          ),
          data.billing?.preferredCurrency && /* @__PURE__ */ jsx(
            BillingRow,
            {
              icon: Hash,
              label: t("customers.companies.detail.billing.currency", "Currency"),
              value: data.billing.preferredCurrency,
              showCopy: false,
              showDottedLine: false,
              t
            }
          )
        ] })
      ] })
    ] })
  ] });
}
export {
  CompanyCard
};
//# sourceMappingURL=CompanyCard.js.map
