"use client";

import { cn } from "@/lib/utils";

import type { DashboardChartSlice } from "./types";

export function WidgetChartLegend({
  items,
  className,
  maxItems,
}: {
  items: Array<Pick<DashboardChartSlice, "name" | "fill" | "label" | "pct">>;
  className?: string;
  /** When set, shows only the top N items plus a “+X more” row. */
  maxItems?: number;
}) {
  if (items.length === 0) return null;

  const visible = maxItems != null ? items.slice(0, maxItems) : items;
  const hiddenCount = maxItems != null ? Math.max(0, items.length - maxItems) : 0;

  return (
    <ul className={cn("min-h-0 space-y-1.5 text-xs", className)}>
      {visible.map((item) => (
        <li
          key={item.name}
          className="flex items-center gap-2.5 rounded-lg border border-border/40 bg-card/60 px-2.5 py-1.5"
        >
          <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: item.fill }} />
          <span className="min-w-0 flex-1 truncate font-medium text-foreground/85" title={item.name}>
            {item.name}
          </span>
          {item.label ? (
            <span className="shrink-0 text-right text-[11px] font-semibold tabular-nums text-foreground">
              {item.label}
            </span>
          ) : item.pct != null ? (
            <span className="shrink-0 text-right text-[11px] font-semibold tabular-nums text-foreground">
              {item.pct.toFixed(1)}%
            </span>
          ) : null}
        </li>
      ))}
      {hiddenCount > 0 ? (
        <li className="px-2.5 py-1 text-[10px] font-medium text-muted-foreground">+{hiddenCount} more</li>
      ) : null}
    </ul>
  );
}
