// Camembert SVG en pure code. Chaque segment est un cercle complet avec
// stroke-dasharray pour découper sa portion, et stroke-dashoffset pour le
// positionner. Pas de path arc → math triviale + cohérent avec Sparkline.

type Segment = {
  label: string;
  value: number;
  /** Couleur du segment (CSS color ou var(--token)). Si non fourni : palette par défaut. */
  color?: string;
};

type Props = {
  segments: Segment[];
  /** Largeur/hauteur du SVG (carré). */
  size?: number;
  /** Épaisseur de l'anneau. */
  strokeWidth?: number;
  /** Position de la légende. "none" pour ne rien afficher. */
  legend?: "right" | "bottom" | "none";
  /** Contenu central optionnel (KPI, label) — placé via foreignObject. */
  centerLabel?: string;
  centerValue?: string;
  className?: string;
};

const DEFAULT_PALETTE = [
  "var(--accent)",
  "var(--success)",
  "var(--warning)",
  "var(--danger)",
  "#a78bfa", // violet
  "#06b6d4", // cyan
  "#64748b", // slate
  "#f97316", // orange
];

export function DonutChart({
  segments,
  size = 160,
  strokeWidth = 22,
  legend = "right",
  centerLabel,
  centerValue,
  className = "",
}: Props) {
  const total = segments.reduce((sum, s) => sum + Math.max(0, s.value), 0);
  const cx = size / 2;
  const cy = size / 2;
  const r = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * r;

  let cumulative = 0;
  const renderedSegments = segments
    .filter((s) => s.value > 0)
    .map((s, i) => {
      const fraction = total > 0 ? s.value / total : 0;
      const length = fraction * circumference;
      const offset = -cumulative;
      cumulative += length;
      const color = s.color ?? DEFAULT_PALETTE[i % DEFAULT_PALETTE.length];
      return { ...s, color, length, offset, fraction };
    });

  const isEmpty = total === 0;

  const svg = (
    <svg
      width={size}
      height={size}
      viewBox={`0 0 ${size} ${size}`}
      className="shrink-0"
      aria-hidden={isEmpty}
    >
      {/* Anneau de fond (visible si vide ou pour combler les arrondis). */}
      <circle
        cx={cx}
        cy={cy}
        r={r}
        fill="none"
        stroke="var(--surface-2, #e5e7eb)"
        strokeWidth={strokeWidth}
      />
      {!isEmpty &&
        renderedSegments.map((s, i) => (
          <circle
            key={i}
            cx={cx}
            cy={cy}
            r={r}
            fill="none"
            stroke={s.color}
            strokeWidth={strokeWidth}
            strokeDasharray={`${s.length} ${circumference - s.length}`}
            strokeDashoffset={s.offset}
            transform={`rotate(-90 ${cx} ${cy})`}
          />
        ))}
      {(centerLabel || centerValue) && (
        <foreignObject x={0} y={0} width={size} height={size}>
          <div className="flex h-full w-full flex-col items-center justify-center text-center">
            {centerValue && (
              <span className="text-xl font-semibold tabular-nums leading-none">
                {centerValue}
              </span>
            )}
            {centerLabel && (
              <span className="mt-1 text-[10px] uppercase tracking-wider text-muted-foreground">
                {centerLabel}
              </span>
            )}
          </div>
        </foreignObject>
      )}
    </svg>
  );

  if (legend === "none") {
    return <div className={className}>{svg}</div>;
  }

  const legendItems = (
    <ul
      className={`flex gap-x-4 gap-y-1.5 ${
        legend === "right" ? "flex-col" : "flex-row flex-wrap justify-center"
      }`}
    >
      {(isEmpty ? segments : renderedSegments).map((s, i) => {
        const color =
          "color" in s && s.color
            ? s.color
            : DEFAULT_PALETTE[i % DEFAULT_PALETTE.length];
        const pct = total > 0 ? Math.round((s.value / total) * 100) : 0;
        return (
          <li key={i} className="flex items-center gap-2 text-xs">
            <span
              className="inline-block size-2.5 shrink-0 rounded-sm"
              style={{ background: color }}
              aria-hidden="true"
            />
            <span className="truncate text-muted-foreground">{s.label}</span>
            <span className="ml-auto whitespace-nowrap font-medium tabular-nums">
              {s.value} {total > 0 && <span className="text-muted-foreground">({pct}%)</span>}
            </span>
          </li>
        );
      })}
    </ul>
  );

  return (
    <div
      className={`flex items-center ${
        legend === "right" ? "gap-5" : "flex-col gap-3"
      } ${className}`}
    >
      {svg}
      <div className={legend === "right" ? "flex-1 min-w-0" : "w-full"}>
        {legendItems}
      </div>
    </div>
  );
}
