"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useDroppable } from "@dnd-kit/core";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { DealCard } from "./DealCard.js";
import { DashedTileButton } from "./DashedTileButton.js";
import { LANE_WIDTH_PX } from "./constants.js";
import { LaneCurrencyBreakdown } from "./LaneCurrencyBreakdown.js";
import { LaneResizeHandle } from "./LaneResizeHandle.js";
const ACCENT_TONE_CLASS = {
  success: "bg-status-success-icon",
  error: "bg-status-error-icon",
  warning: "bg-status-warning-icon",
  info: "bg-status-info-icon",
  neutral: "bg-status-neutral-icon",
  brand: "bg-brand-violet",
  pink: "bg-status-pink-icon"
};
const COUNT_BADGE_TONE_CLASS = {
  success: "bg-status-success-bg text-status-success-text",
  error: "bg-status-error-bg text-status-error-text",
  warning: "bg-status-warning-bg text-status-warning-text",
  info: "bg-status-info-bg text-status-info-text",
  neutral: "bg-status-neutral-bg text-status-neutral-text",
  brand: "bg-brand-violet/14 text-brand-violet",
  pink: "bg-status-pink-bg text-status-pink-text"
};
function getAccentClass(tone) {
  if (tone && tone in ACCENT_TONE_CLASS) return ACCENT_TONE_CLASS[tone];
  return "bg-border";
}
function getCountBadgeClass(tone) {
  if (tone && tone in COUNT_BADGE_TONE_CLASS) return COUNT_BADGE_TONE_CLASS[tone];
  return "bg-muted text-muted-foreground";
}
function compactCurrency(amount) {
  if (amount >= 1e6) {
    const value = amount / 1e6;
    return value >= 100 ? `${Math.round(value)}M` : `${value.toFixed(1).replace(/\.0$/, "")}M`;
  }
  if (amount >= 1e3) {
    const value = amount / 1e3;
    return value >= 100 ? `${Math.round(value)}k` : `${value.toFixed(1).replace(/\.0$/, "")}k`;
  }
  return String(Math.round(amount));
}
function buildLaneStats(deals, aggregate) {
  if (aggregate) {
    const rows2 = aggregate.byCurrency;
    const headline = rows2.length > 0 ? rows2[0] : null;
    return {
      count: aggregate.count,
      primaryAmount: headline ? headline.total : 0,
      primaryCurrency: headline ? headline.currency : null,
      rows: rows2,
      totalInBaseCurrency: aggregate.totalInBaseCurrency,
      baseCurrencyCode: aggregate.baseCurrencyCode,
      convertedAll: aggregate.convertedAll,
      missingRateCurrencies: aggregate.missingRateCurrencies
    };
  }
  const totalsByCurrency = /* @__PURE__ */ new Map();
  for (const deal of deals) {
    if (typeof deal.valueAmount !== "number" || !Number.isFinite(deal.valueAmount)) continue;
    const code = deal.valueCurrency && deal.valueCurrency.length === 3 ? deal.valueCurrency.toUpperCase() : "USD";
    const entry = totalsByCurrency.get(code) ?? { total: 0, count: 0 };
    entry.total += deal.valueAmount;
    entry.count += 1;
    totalsByCurrency.set(code, entry);
  }
  const rows = Array.from(totalsByCurrency.entries()).map(([currency, value]) => ({ currency, total: value.total, count: value.count })).sort((a, b) => b.total - a.total);
  if (rows.length === 0) {
    return {
      count: deals.length,
      primaryAmount: 0,
      primaryCurrency: null,
      rows,
      totalInBaseCurrency: 0,
      baseCurrencyCode: null,
      convertedAll: true,
      missingRateCurrencies: []
    };
  }
  return {
    count: deals.length,
    primaryAmount: rows[0].total,
    primaryCurrency: rows[0].currency,
    rows,
    totalInBaseCurrency: 0,
    baseCurrencyCode: null,
    // We don't have rates client-side; mark as "not converted" only when there are
    // multiple currencies so the popover can show a "configure FX rates" hint.
    convertedAll: rows.length === 1,
    missingRateCurrencies: rows.length > 1 ? rows.slice(1).map((row) => row.currency) : []
  };
}
function LaneImpl({
  stage,
  deals,
  aggregate,
  selectedDealIds,
  buildMenuItems,
  activeDragDealId,
  isLoadingMore = false,
  width,
  onToggleSelect,
  onComposeActivity,
  onOpenDetail,
  onQuickAddClick,
  onLoadMore,
  onResize,
  onResizeEnd,
  onResetWidth
}) {
  const t = useT();
  const { setNodeRef, isOver } = useDroppable({
    id: `lane:${stage.id}`,
    data: { type: "lane", stageId: stage.id }
  });
  const isDragActive = !!activeDragDealId;
  const sourceLane = isDragActive && deals.some((deal) => deal.id === activeDragDealId);
  const showDropHighlight = isOver || isDragActive && !sourceLane;
  const stats = React.useMemo(() => buildLaneStats(deals, aggregate), [deals, aggregate]);
  const bulkSelectionActive = selectedDealIds.size > 0;
  const totalLabel = stats.primaryAmount > 0 && stats.primaryCurrency ? `${compactCurrency(stats.primaryAmount)} ${stats.primaryCurrency}` : null;
  const visibleCount = deals.length;
  const totalCount = stats.count;
  const hasMoreDeals = totalCount > visibleCount;
  const accentClass = getAccentClass(stage.tone);
  const countBadgeClass = getCountBadgeClass(stage.tone);
  const handleQuickAdd = React.useCallback(() => {
    onQuickAddClick(stage.id);
  }, [onQuickAddClick, stage.id]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "relative flex flex-none flex-col gap-3",
      style: { width: typeof width === "number" && Number.isFinite(width) ? `${width}px` : `${LANE_WIDTH_PX}px` },
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2.5 overflow-clip rounded-lg bg-muted/40 px-4 py-3.5", children: [
          /* @__PURE__ */ jsx("div", { className: `h-1.5 w-full rounded-sm ${accentClass}`, "aria-hidden": "true" }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-center gap-2.5", children: [
              /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-bold uppercase leading-normal text-foreground", children: stage.label }),
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: `inline-flex shrink-0 items-center rounded-full px-2 py-1 text-xs font-bold leading-normal ${countBadgeClass}`,
                  title: hasMoreDeals ? translateWithFallback(
                    t,
                    "customers.deals.kanban.lane.aria.partialCount",
                    "Showing {visible} of {total}",
                    { visible: visibleCount, total: totalCount }
                  ) : void 0,
                  children: totalCount
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
              totalLabel ? /* @__PURE__ */ jsx("span", { className: "text-sm font-bold leading-normal text-foreground", children: totalLabel }) : null,
              stats.rows.length > 1 ? /* @__PURE__ */ jsx(
                LaneCurrencyBreakdown,
                {
                  rows: stats.rows,
                  baseCurrencyCode: stats.baseCurrencyCode,
                  totalInBaseCurrency: stats.totalInBaseCurrency,
                  convertedAll: stats.convertedAll,
                  missingRateCurrencies: stats.missingRateCurrencies,
                  triggerLabel: `+${stats.rows.length - 1}`,
                  headingLabel: stage.label.toUpperCase(),
                  headingCount: totalCount
                }
              ) : null
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs(
          DashedTileButton,
          {
            onClick: handleQuickAdd,
            className: "h-11",
            ariaLabel: translateWithFallback(
              t,
              "customers.deals.kanban.lane.aria.quickAdd",
              "Quickly add a deal to {stage}",
              { stage: stage.label }
            ),
            children: [
              /* @__PURE__ */ jsx("span", { className: "text-base font-bold leading-none", children: "+" }),
              /* @__PURE__ */ jsx("span", { children: translateWithFallback(t, "customers.deals.kanban.cta.quickDeal", "Quick deal") })
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          "div",
          {
            ref: setNodeRef,
            className: `flex min-h-[40vh] flex-col gap-3 rounded-lg p-1.5 ${isOver ? "bg-accent-indigo/10 outline-dashed outline-2 outline-accent-indigo -outline-offset-[2px]" : showDropHighlight ? "bg-muted/40 outline-dashed outline-1 outline-muted-foreground/40 -outline-offset-[2px]" : ""}`,
            children: [
              deals.length === 0 ? /* @__PURE__ */ jsx(
                EmptyState,
                {
                  size: "sm",
                  title: translateWithFallback(
                    t,
                    "customers.deals.kanban.lane.empty",
                    "No deals in this stage yet."
                  )
                }
              ) : deals.map((deal) => /* @__PURE__ */ jsx(
                DealCard,
                {
                  deal,
                  selected: selectedDealIds.has(deal.id),
                  bulkSelectionActive,
                  buildMenuItems,
                  isActiveDrag: activeDragDealId === deal.id,
                  onToggleSelect,
                  onComposeActivity,
                  onOpenDetail
                },
                deal.id
              )),
              hasMoreDeals && onLoadMore ? /* @__PURE__ */ jsx(
                DashedTileButton,
                {
                  onClick: () => onLoadMore(stage.id),
                  disabled: isLoadingMore,
                  className: "mt-0.75 px-3 py-2.5 text-muted-foreground",
                  ariaLabel: translateWithFallback(
                    t,
                    "customers.deals.kanban.lane.aria.loadMore",
                    "Load more deals in {stage}",
                    { stage: stage.label }
                  ),
                  children: isLoadingMore ? translateWithFallback(t, "customers.deals.kanban.lane.loadingMore", "Loading\u2026") : translateWithFallback(
                    t,
                    "customers.deals.kanban.lane.loadMore",
                    "Show more ({remaining})",
                    { remaining: totalCount - visibleCount }
                  )
                }
              ) : null
            ]
          }
        ),
        onResize ? /* @__PURE__ */ jsx(
          LaneResizeHandle,
          {
            onResize: (delta) => onResize(stage.id, delta),
            onResizeEnd: () => onResizeEnd?.(stage.id),
            onReset: () => onResetWidth?.(stage.id)
          }
        ) : null
      ]
    }
  );
}
const Lane = React.memo(LaneImpl, (prev, next) => {
  if (prev.stage !== next.stage) return false;
  if (prev.deals !== next.deals) return false;
  if (prev.aggregate !== next.aggregate) return false;
  if (prev.selectedDealIds !== next.selectedDealIds) return false;
  if (prev.buildMenuItems !== next.buildMenuItems) return false;
  if (prev.activeDragDealId !== next.activeDragDealId) return false;
  if (prev.isLoadingMore !== next.isLoadingMore) return false;
  if (prev.width !== next.width) return false;
  return true;
});
var Lane_default = Lane;
export {
  Lane,
  Lane_default as default
};
//# sourceMappingURL=Lane.js.map
