const SLICE_COLORS = [
  "var(--brand-cyan)",
  "var(--brand-purple)",
  "var(--brand-magenta)",
  "var(--brand-blue)",
  "var(--success)",
  "var(--muted-foreground)",
];

/**
 * Category breakdown as a CSS conic-gradient ring — no charting library
 * needed for a single static ring. Percentages are computed server-side in
 * getDashboardCategories() from a live product count, never hardcoded here.
 * The legend list carries the same data in text form for anyone who can't
 * perceive the ring itself (color-blind or non-visual).
 */
export function CategoryDistribution({
  categories,
  total,
  otherLabel,
  totalLabel,
  emptyLabel,
}: {
  categories: { category: string; count: number; percent: number }[];
  total: number;
  otherLabel: string;
  totalLabel: string;
  emptyLabel: string;
}) {
  if (categories.length === 0 || total === 0) {
    return <p className="text-sm text-muted-foreground">{emptyLabel}</p>;
  }

  // Cumulative percent boundaries, computed without mutating any render-scoped
  // variable (each reduce step returns a new array).
  const cumulative = categories.reduce<number[]>(
    (acc, slice) => [...acc, (acc[acc.length - 1] ?? 0) + slice.percent],
    [],
  );
  const stops = categories.map((_, i) => {
    const start = i === 0 ? 0 : cumulative[i - 1];
    const end = cumulative[i];
    return `${SLICE_COLORS[i % SLICE_COLORS.length]} ${start}% ${end}%`;
  });

  return (
    <div className="flex min-w-0 items-center gap-6">
      <div
        className="relative size-36 shrink-0 rounded-full"
        style={{ background: `conic-gradient(${stops.join(", ")})` }}
        role="img"
        aria-label={`${totalLabel}: ${new Intl.NumberFormat().format(total)}`}
      >
        <div className="absolute inset-4 flex flex-col items-center justify-center rounded-full bg-background text-center">
          <span className="text-xl font-semibold text-foreground">{new Intl.NumberFormat().format(total)}</span>
          <span className="text-[10px] text-muted-foreground">{totalLabel}</span>
        </div>
      </div>
      <ul className="flex min-w-0 flex-1 flex-col gap-1.5 text-sm">
        {categories.map((slice, i) => (
          <li key={slice.category} className="flex items-center justify-between gap-2">
            <span className="flex min-w-0 items-center gap-2">
              <span
                className="size-2 shrink-0 rounded-full"
                style={{ backgroundColor: SLICE_COLORS[i % SLICE_COLORS.length] }}
                aria-hidden="true"
              />
              <span className="truncate text-foreground">
                {slice.category === "other" ? otherLabel : slice.category}
              </span>
            </span>
            <span className="shrink-0 tabular-nums text-muted-foreground">{slice.percent}%</span>
          </li>
        ))}
      </ul>
    </div>
  );
}
