"use client";

import { deriveSubtype } from "@/lib/practice-area";
import type { AppealSubtype } from "@/lib/practice-area";
import type { Case } from "@/lib/api/cases";

type Bucket = { key: AppealSubtype; label: string; color: string };

const BUCKETS: Bucket[] = [
  { key: "building_permit",  label: "רישוי ובנייה",  color: "var(--color-info)" },
  { key: "betterment_levy",  label: "היטל השבחה",     color: "var(--color-gold)" },
  { key: "compensation_197", label: "פיצויים (ס׳ 197)", color: "var(--color-warn)" },
];

export function subtypeOf(c: Case): AppealSubtype {
  return c.appeal_subtype && c.appeal_subtype !== "unknown"
    ? c.appeal_subtype
    : deriveSubtype(c.case_number);
}

export function AppealTypeBars({ cases }: { cases?: Case[] }) {
  const counts: Record<AppealSubtype, number> = {
    building_permit: 0,
    betterment_levy: 0,
    compensation_197: 0,
    unknown: 0,
  };
  (cases ?? []).forEach((c) => {
    counts[subtypeOf(c)] += 1;
  });
  const max = Math.max(1, ...BUCKETS.map((b) => counts[b.key]));

  return (
    <ul className="flex flex-col gap-3">
      {BUCKETS.map((b) => {
        const n = counts[b.key];
        const widthPct = (n / max) * 100;
        return (
          <li key={b.key} className="space-y-1.5">
            <div className="flex items-baseline justify-between gap-2 text-sm">
              <span className="text-ink-soft truncate">{b.label}</span>
              <span className="text-ink font-semibold tabular-nums">{n}</span>
            </div>
            <div className="h-2 rounded-full bg-rule-soft/60 overflow-hidden">
              <div
                className="h-full rounded-full transition-[width] duration-500"
                style={{ width: `${widthPct}%`, background: b.color }}
              />
            </div>
          </li>
        );
      })}
    </ul>
  );
}
