// BEGIN CHANGE: shop history cell - offer name + item icons + serial pairing
"use client";

import { ItemIcon } from "@/components/ItemIcon";

export type ShopHistoryItem = {
  itemId: number;
  count: number;
  name: string;
};

type Props = {
  kind: string;
  itemName: string;
  days?: number;
  premiumDaysLabel?: string;
  items?: ShopHistoryItem[];
  /** CSV from z_shop_history_item.serial_item - paired under icons when counts match */
  serialItem?: string;
  className?: string;
};

export function parseShopSerials(raw?: string | null): string[] {
  if (!raw) {
    return [];
  }
  return String(raw)
    .split(",")
    .map((s) => s.trim())
    .filter((s) => s.length > 0);
}

/** Vertical list of serials for the Serial column (combo/set friendly). */
export function ShopHistorySerials({
  serialItem,
  empty = "-",
  className = "",
}: {
  serialItem?: string | null;
  empty?: string;
  className?: string;
}) {
  const list = parseShopSerials(serialItem);
  if (list.length === 0) {
    return <span className={`text-muted ${className}`.trim()}>{empty}</span>;
  }
  return (
    <ul className={`flex max-w-[14rem] flex-col gap-1 ${className}`.trim()}>
      {list.map((s) => (
        <li key={s} className="break-all font-mono text-[11px] leading-snug text-muted">
          {s}
        </li>
      ))}
    </ul>
  );
}

export function ShopHistoryWhat({
  kind,
  itemName,
  days = 0,
  premiumDaysLabel = "premium days",
  items = [],
  serialItem = "",
  className = "",
}: Props) {
  if (kind === "pacc") {
    return (
      <div className={className}>
        <span className="font-medium">
          {days} {premiumDaysLabel}
        </span>
      </div>
    );
  }

  const showIcons = items.length > 0;
  const serials = parseShopSerials(serialItem);
  // Only pair when 1:1 - avoids mis-labeling when stackables skip serial
  const paired = showIcons && serials.length > 0 && items.length === serials.length;

  return (
    <div className={className}>
      <div className="font-medium leading-snug">{itemName || "-"}</div>
      {showIcons ? (
        <ul className="mt-1.5 flex flex-col gap-1.5">
          {items.slice(0, 8).map((it, idx) => (
            <li key={`${it.itemId}-${it.count}-${idx}`} className="flex items-start gap-2 text-xs text-muted">
              <ItemIcon id={it.itemId} size={24} alt={it.name} />
              <div className="min-w-0 leading-snug">
                <div>
                  {it.name}
                  {it.count > 1 ? ` x${it.count}` : ""}
                </div>
                {paired ? (
                  <div className="mt-0.5 break-all font-mono text-[10px] text-muted/90">{serials[idx]}</div>
                ) : null}
              </div>
            </li>
          ))}
          {items.length > 8 ? (
            <li className="text-xs text-muted">+{items.length - 8}</li>
          ) : null}
        </ul>
      ) : null}
    </div>
  );
}
// END CHANGE
