"use client";

import { getEpcColorClass } from "@/app/utils";
import { EpcChip } from "./primitives";
import { EPC_BANDS } from "@/lib/epc/bands";
import type { EpcBandCount } from "../types";

/**
 * Horizontal EPC ladder in statutory band colours (Screen A/B). The
 * estimated share is the lighter tail of each bar; the scenario overlay,
 * when present, is a navy sub-bar beneath the current bar per band.
 * Clicking a band opens the drill-down shelf.
 */
export function EpcLadder({
  bands,
  scenarioBands,
  onSelectBand,
  selectedBand,
}: {
  bands: EpcBandCount[];
  scenarioBands?: Record<string, number>;
  onSelectBand?: (band: string) => void;
  selectedBand?: string | null;
}) {
  const byBand = new Map(bands.map((b) => [b.epc, b]));
  const order = EPC_BANDS.filter(
    (b) => byBand.has(b) || (scenarioBands?.[b] ?? 0) > 0,
  );

  const max = Math.max(
    1,
    ...order.map((b) => {
      const d = byBand.get(b);
      const base = (d?.actual ?? 0) + (d?.estimated ?? 0);
      return Math.max(base, scenarioBands?.[b] ?? 0);
    }),
  );

  return (
    <div className="flex flex-col gap-2.5">
      {order.map((band) => {
        const d = byBand.get(band);
        const actual = d?.actual ?? 0;
        const estimated = d?.estimated ?? 0;
        const total = actual + estimated;
        const scenario = scenarioBands?.[band];
        const bar = getEpcColorClass(band);
        const selected = selectedBand === band;

        // Each band is one focusable button that is itself a 3-column grid,
        // so the fixed template keeps columns aligned across rows while the
        // focus box lands on a real element (not display:contents).
        return (
          <button
            key={band}
            type="button"
            onClick={() => onSelectBand?.(band)}
            aria-pressed={selected}
            className={`grid grid-cols-[24px_1fr_108px] items-center gap-x-3 rounded px-1 py-0.5 text-left hover:bg-gray-50 ${
              selected ? "outline outline-2 outline-offset-1 outline-midblue" : ""
            }`}
            aria-label={`${total} homes in band ${band}`}
          >
            <EpcChip band={band} size="sm" />
            <span className="flex flex-col gap-[3px]">
              <span className="flex h-[18px] overflow-hidden rounded">
                <span
                  className={`h-full ${bar}`}
                  style={{ width: `${(actual / max) * 100}%` }}
                />
                <span
                  className={`h-full ${bar} opacity-40`}
                  style={{ width: `${(estimated / max) * 100}%` }}
                />
              </span>
              {scenario !== undefined && (
                <span className="flex h-[7px] overflow-hidden rounded">
                  <span
                    className="h-full rounded-sm bg-brandblue"
                    style={{ width: `${(scenario / max) * 100}%` }}
                  />
                </span>
              )}
            </span>
            <span className="text-right text-[0.78rem] tabular-nums text-gray-600">
              {scenario !== undefined ? (
                <>
                  {total} → <b className="font-semibold text-gray-900">{scenario}</b>
                </>
              ) : (
                <>
                  <b className="font-semibold text-gray-900">{total}</b>
                  {estimated > 0 && ` · ${estimated} est`}
                </>
              )}
            </span>
          </button>
        );
      })}
    </div>
  );
}
