"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useDraggable } from "@dnd-kit/core";
import { AlertTriangle, Building2, Calendar, Clock, Mail, Phone, StickyNote } from "lucide-react";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { SimpleTooltip } from "@open-mercato/ui/primitives/tooltip";
import { DealCardMenu } from "./DealCardMenu.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
const ACTIVITY_BADGE_CAP = 9;
const ACTIVITY_BADGE_WARNING_THRESHOLD = 9;
const AVATAR_STACK_MAX = 3;
const AVATAR_ACCENT_CLASSES = [
  "bg-status-info-icon text-white",
  "bg-brand-violet text-brand-violet-foreground",
  "bg-status-warning-icon text-white",
  "bg-status-neutral-icon text-white",
  "bg-status-success-icon text-white",
  "bg-status-pink-icon text-white"
];
function hashAccent(seed) {
  let h = 0;
  for (let i = 0; i < seed.length; i += 1) {
    h = (h << 5) - h + seed.charCodeAt(i) | 0;
  }
  const idx = Math.abs(h) % AVATAR_ACCENT_CLASSES.length;
  return AVATAR_ACCENT_CLASSES[idx];
}
function splitCurrencyAmount(amount, currency) {
  const code = currency && currency.length === 3 ? currency.toUpperCase() : null;
  try {
    const formatter = new Intl.NumberFormat(void 0, {
      style: "decimal",
      maximumFractionDigits: 0,
      useGrouping: true
    });
    return { display: formatter.format(amount), code };
  } catch {
    return { display: String(Math.round(amount)), code };
  }
}
function formatProbability(value) {
  if (typeof value !== "number" || Number.isNaN(value)) return null;
  return `${Math.min(Math.max(Math.round(value), 0), 100)}%`;
}
const shortDateFormatter = new Intl.DateTimeFormat(void 0, {
  month: "short",
  day: "2-digit"
});
function formatShortDate(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return shortDateFormatter.format(date);
}
function shortDealRef(id) {
  return `DEAL-${id.slice(0, 6).toUpperCase()}`;
}
function DealCardImpl({
  deal,
  selected,
  bulkSelectionActive = false,
  buildMenuItems,
  extraCompaniesCount = 0,
  extraOwners,
  isActiveDrag = false,
  onToggleSelect,
  onComposeActivity,
  onOpenDetail
}) {
  const menuItems = React.useMemo(() => buildMenuItems(deal), [buildMenuItems, deal]);
  const t = useT();
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
    id: deal.id,
    data: { type: "deal" }
  });
  const dimmed = isActiveDrag || isDragging;
  const style = {};
  const activityCount = deal.pipelineState.openActivitiesCount;
  const activityBadgeLabel = activityCount > 0 ? activityCount > ACTIVITY_BADGE_CAP ? `${ACTIVITY_BADGE_CAP}+` : String(activityCount) : null;
  const activityWarning = activityCount >= ACTIVITY_BADGE_WARNING_THRESHOLD;
  const probabilityLabel = formatProbability(deal.probability);
  const dateLabel = formatShortDate(deal.expectedCloseAt ?? deal.createdAt);
  const stageDaysLabel = deal.pipelineState.isOverdue ? translateWithFallback(t, "customers.deals.kanban.card.overdueLabel", "Overdue") : translateWithFallback(t, "customers.deals.kanban.card.daysInStage", "in {days}d", {
    days: deal.pipelineState.daysInCurrentStage
  });
  const showOverdue = deal.pipelineState.isOverdue;
  const showStuck = !showOverdue && deal.pipelineState.isStuck;
  const handleSelectChange = (next) => {
    if (typeof next === "boolean" && next !== selected) {
      onToggleSelect(deal.id);
    }
  };
  const handleCardClick = (event) => {
    const target = event.target;
    if (target.closest('[data-card-action="true"]')) return;
    if (bulkSelectionActive) {
      onToggleSelect(deal.id);
      return;
    }
    onOpenDetail(deal.id);
  };
  const handleActionClick = (type) => (event) => {
    event.stopPropagation();
    onComposeActivity(deal.id, type);
  };
  const stopPointerDown = React.useCallback((event) => {
    event.stopPropagation();
  }, []);
  const ariaLabel = translateWithFallback(t, "customers.deals.kanban.card.aria", "Deal: {title}", {
    title: deal.title
  });
  const ariaRoleDescription = translateWithFallback(
    t,
    "customers.deals.kanban.card.aria.roledescription",
    "deal card"
  );
  const valuePieces = deal.valueAmount !== null && Number.isFinite(deal.valueAmount) ? splitCurrencyAmount(deal.valueAmount, deal.valueCurrency) : null;
  const probabilityValue = typeof deal.probability === "number" ? deal.probability : null;
  const probabilityPillClass = probabilityValue !== null && probabilityValue >= 70 ? "bg-muted text-foreground" : probabilityValue !== null && probabilityValue >= 40 ? "bg-status-warning-bg text-status-warning-text" : "bg-muted text-muted-foreground";
  const activityBadgeClass = activityWarning ? "bg-status-warning-bg text-status-warning-text" : "bg-muted text-foreground";
  const ownersStack = React.useMemo(() => {
    if (!deal.owner) return extraOwners ?? [];
    return [deal.owner, ...extraOwners ?? []];
  }, [deal.owner, extraOwners]);
  const visibleOwners = ownersStack.slice(0, AVATAR_STACK_MAX);
  const ownerOverflow = ownersStack.length - visibleOwners.length;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setNodeRef,
      style,
      ...attributes,
      ...listeners,
      "aria-label": ariaLabel,
      "aria-roledescription": ariaRoleDescription,
      onClick: handleCardClick,
      className: `group relative flex w-full flex-col gap-3 rounded-lg border border-border bg-card px-4 py-3.5 shadow-xs transition-shadow ${dimmed ? "cursor-grabbing opacity-30" : bulkSelectionActive ? "cursor-pointer hover:shadow-sm" : "cursor-grab hover:shadow-sm active:cursor-grabbing"} ${selected ? "ring-2 ring-accent-indigo" : ""}`,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2.5", children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              "data-card-action": "true",
              className: `mr-0.5 mt-0.5 flex shrink-0 transition-opacity ${selected || bulkSelectionActive ? "opacity-100" : "opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto [@media(hover:none)]:opacity-100 [@media(hover:none)]:pointer-events-auto"}`,
              onClick: (event) => event.stopPropagation(),
              onPointerDown: stopPointerDown,
              children: /* @__PURE__ */ jsx(
                Checkbox,
                {
                  checked: selected,
                  onCheckedChange: handleSelectChange,
                  "aria-label": translateWithFallback(t, "customers.deals.kanban.card.aria.select", "Select deal")
                }
              )
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [
            /* @__PURE__ */ jsx("h3", { className: "line-clamp-2 text-base font-semibold leading-normal text-foreground", children: deal.title }),
            /* @__PURE__ */ jsx("span", { className: "text-xs leading-normal text-muted-foreground", children: shortDealRef(deal.id) })
          ] }),
          /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex shrink-0 items-center gap-2",
              "data-card-action": "true",
              onClick: (event) => event.stopPropagation(),
              onPointerDown: stopPointerDown,
              children: [
                activityBadgeLabel ? /* @__PURE__ */ jsx(
                  "span",
                  {
                    className: `inline-flex items-center justify-center rounded-full px-2 py-px text-xs font-bold leading-normal ${activityBadgeClass}`,
                    "aria-label": translateWithFallback(
                      t,
                      "customers.deals.kanban.card.aria.openActivities",
                      "{count} open activities",
                      { count: activityCount }
                    ),
                    children: activityBadgeLabel
                  }
                ) : null,
                /* @__PURE__ */ jsx(
                  DealCardMenu,
                  {
                    items: menuItems,
                    ariaLabel: translateWithFallback(
                      t,
                      "customers.deals.kanban.card.aria.menu",
                      "Deal actions"
                    )
                  }
                )
              ]
            }
          )
        ] }),
        showOverdue || showStuck ? /* @__PURE__ */ jsx("div", { children: showOverdue ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 rounded-md bg-status-error-bg px-2.5 py-1 text-xs font-semibold leading-normal text-status-error-text", children: [
          /* @__PURE__ */ jsx(AlertTriangle, { className: "size-3.5", "aria-hidden": "true" }),
          translateWithFallback(t, "customers.deals.kanban.card.statusOverdue", "OVERDUE")
        ] }) : /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 rounded-md bg-status-warning-bg px-2.5 py-1 text-xs font-semibold leading-normal text-status-warning-text", children: [
          /* @__PURE__ */ jsx(Clock, { className: "size-3.5", "aria-hidden": "true" }),
          translateWithFallback(t, "customers.deals.kanban.card.statusStuck", "STUCK")
        ] }) }) : null,
        /* @__PURE__ */ jsx(
          "div",
          {
            "data-card-action": "true",
            className: "flex items-center justify-center gap-2 opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto [@media(hover:none)]:opacity-100 [@media(hover:none)]:pointer-events-auto",
            onClick: (event) => event.stopPropagation(),
            onPointerDown: stopPointerDown,
            children: (() => {
              const disabled = !deal.primaryCompany;
              const disabledTooltip = disabled ? translateWithFallback(
                t,
                "customers.deals.kanban.card.action.disabledNoCompany",
                "Link a company to this deal before logging activities."
              ) : void 0;
              const renderActionButton = (type, label, icon) => {
                const button = /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    variant: "ghost",
                    size: "default",
                    onClick: handleActionClick(type),
                    disabled,
                    "aria-disabled": disabled || void 0,
                    "aria-label": label,
                    className: "shrink-0 text-muted-foreground hover:text-foreground",
                    children: icon
                  }
                );
                if (!disabled) {
                  return /* @__PURE__ */ jsx(SimpleTooltip, { content: label, size: "sm", children: button }, type);
                }
                return /* @__PURE__ */ jsx(SimpleTooltip, { content: disabledTooltip, size: "sm", children: /* @__PURE__ */ jsx(
                  "span",
                  {
                    className: "inline-flex shrink-0 rounded-md focus-visible:outline-none focus-visible:shadow-focus",
                    tabIndex: 0,
                    "aria-label": `${label}: ${disabledTooltip}`,
                    children: button
                  }
                ) }, type);
              };
              return /* @__PURE__ */ jsxs(Fragment, { children: [
                renderActionButton(
                  "call",
                  translateWithFallback(t, "customers.deals.kanban.card.action.call", "Call"),
                  /* @__PURE__ */ jsx(Phone, { className: "size-5", "aria-hidden": "true" })
                ),
                renderActionButton(
                  "email",
                  translateWithFallback(t, "customers.deals.kanban.card.action.email", "Email"),
                  /* @__PURE__ */ jsx(Mail, { className: "size-5", "aria-hidden": "true" })
                ),
                renderActionButton(
                  "note",
                  translateWithFallback(t, "customers.deals.kanban.card.action.note", "Note"),
                  /* @__PURE__ */ jsx(StickyNote, { className: "size-5", "aria-hidden": "true" })
                )
              ] });
            })()
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2.5", children: [
          valuePieces ? /* @__PURE__ */ jsxs("div", { className: "flex items-baseline gap-1.5", children: [
            /* @__PURE__ */ jsx("span", { className: "text-lg font-bold leading-normal text-foreground", children: valuePieces.display }),
            valuePieces.code ? /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold leading-normal text-muted-foreground", children: valuePieces.code }) : null
          ] }) : /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: translateWithFallback(t, "customers.deals.kanban.card.noValue", "No value") }),
          probabilityLabel ? /* @__PURE__ */ jsx(
            "span",
            {
              className: `inline-flex items-center rounded-md px-2.5 py-1 text-sm font-semibold leading-normal ${probabilityPillClass}`,
              "aria-label": translateWithFallback(
                t,
                "customers.deals.kanban.card.aria.probability",
                "Probability: {value}",
                { value: probabilityLabel }
              ),
              children: probabilityLabel
            }
          ) : null
        ] }),
        deal.primaryCompany || extraCompaniesCount > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
          deal.primaryCompany ? /* @__PURE__ */ jsxs("span", { className: "inline-flex max-w-full items-center gap-1.5 overflow-hidden rounded-md bg-muted px-2.5 py-1 text-sm font-semibold leading-normal text-foreground", children: [
            /* @__PURE__ */ jsx(Building2, { className: "size-3.5 shrink-0 text-muted-foreground", "aria-hidden": "true" }),
            /* @__PURE__ */ jsx("span", { className: "truncate", children: deal.primaryCompany.label })
          ] }) : null,
          extraCompaniesCount > 0 ? /* @__PURE__ */ jsxs(
            "span",
            {
              className: "inline-flex shrink-0 items-center rounded-md bg-muted px-2.5 py-1 text-sm font-semibold leading-normal text-muted-foreground",
              "aria-label": translateWithFallback(
                t,
                "customers.deals.kanban.card.aria.moreCompanies",
                "{count} more companies",
                { count: extraCompaniesCount }
              ),
              children: [
                "+",
                extraCompaniesCount
              ]
            }
          ) : null
        ] }) : null,
        /* @__PURE__ */ jsx("div", { className: "h-px w-full bg-border", "aria-hidden": "true" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2.5", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm leading-normal", children: [
            dateLabel ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                Calendar,
                {
                  className: `size-3.5 ${showOverdue ? "text-status-error-icon" : "text-muted-foreground"}`,
                  "aria-hidden": "true"
                }
              ),
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: showOverdue ? "font-semibold text-status-error-text" : "font-semibold text-foreground",
                  children: dateLabel
                }
              )
            ] }) : null,
            /* @__PURE__ */ jsx(
              "span",
              {
                className: showOverdue ? "font-semibold text-status-error-text" : "font-normal text-muted-foreground",
                children: stageDaysLabel
              }
            )
          ] }),
          ownersStack.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex items-center", children: [
            visibleOwners.map((owner, idx) => {
              const accentClass = hashAccent(owner.userId);
              return /* @__PURE__ */ jsx(
                Avatar,
                {
                  label: owner.label || owner.userId.slice(0, 2).toUpperCase(),
                  size: "sm",
                  className: `size-7 text-xs font-bold ring-2 ring-card ${accentClass} ${idx > 0 ? "-ml-2.5" : ""}`
                },
                `${owner.userId}-${idx}`
              );
            }),
            ownerOverflow > 0 ? /* @__PURE__ */ jsx(
              Avatar,
              {
                label: `+${ownerOverflow}`,
                size: "sm",
                variant: "monochrome",
                className: "size-7 -ml-2.5 text-xs font-bold ring-2 ring-card"
              }
            ) : null
          ] }) : null
        ] })
      ]
    }
  );
}
const DealCard = React.memo(DealCardImpl, (prev, next) => {
  if (prev.deal !== next.deal) return false;
  if (prev.selected !== next.selected) return false;
  if (prev.bulkSelectionActive !== next.bulkSelectionActive) return false;
  if (prev.isActiveDrag !== next.isActiveDrag) return false;
  if (prev.buildMenuItems !== next.buildMenuItems) return false;
  if (prev.extraCompaniesCount !== next.extraCompaniesCount) return false;
  if (prev.extraOwners !== next.extraOwners) return false;
  return true;
});
var DealCard_default = DealCard;
export {
  DealCard,
  DealCard_default as default
};
//# sourceMappingURL=DealCard.js.map
