"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)" },
];

/* For chart aggregation, collapse בל"מ variants back to their parent
 * domain — building_permit / betterment_levy / compensation_197. The
 * dedicated בל"מ filter in the cases table handles the cross-cutting view. */
function collapseBlam(s: AppealSubtype): AppealSubtype {
  if (s === "extension_request_building_permit")  return "building_permit";
  if (s === "extension_request_betterment_levy")  return "betterment_levy";
  if (s === "extension_request_compensation")     return "compensation_197";
  return s;
}

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

export function AppealTypeBars({ cases }: { cases?: Case[] }) {
  /* All seven subtypes initialized to 0 — subtypeOf() collapses בל"מ
   * variants back to their parent domain, so the extension_request_*
   * counters will remain 0 in practice; they exist here to satisfy the
   * Record<AppealSubtype, number> type. */
  const counts: Record<AppealSubtype, number> = {
    building_permit: 0,
    betterment_levy: 0,
    compensation_197: 0,
    extension_request_building_permit: 0,
    extension_request_betterment_levy: 0,
    extension_request_compensation: 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>
  );
}
