import type { PublicState } from '@pintrush/engine';
import { cn } from '@/lib/cn';
import { formatPoints } from '@/lib/tv/format';
import { finalistLanes, predictionRows } from '@/lib/tv/results';
import { cssVars } from '../cssVars';
import s from '../tv.module.css';

// Finalist colours carry no meaning on their own: every lane also prints the name and number.
const LANE_COLORS = ['var(--color-amber)', 'var(--color-violet-soft)', 'var(--color-cyan)', 'var(--color-lime)', 'var(--color-danger-soft)'] as const;

function laneColor(i: number): string {
  return LANE_COLORS[i % LANE_COLORS.length] ?? 'var(--color-violet-soft)';
}

/** Crowd predictions for the Final Rush: one stacked bar plus a labelled legend. */
export function PredictionBar({ pub, className }: { pub: PublicState; className?: string }) {
  const rows = predictionRows(pub.round?.finalists, pub.predictions);
  if (rows.length === 0) return null;
  const anyVotes = rows.some((r) => r.percent > 0);
  return (
    <section aria-label="Crowd predictions" className={cn('flex flex-col gap-[16px]', className)}>
      <div className="flex items-baseline justify-between">
        <h3 className="text-[24px] font-bold tracking-[0.18em] text-amber-soft uppercase">Who will win? The crowd says…</h3>
        {!anyVotes && <p className="text-[22px] text-muted">Make your pick on your phone</p>}
      </div>
      <div aria-hidden="true" className="flex h-[40px] overflow-hidden rounded-full bg-line/70">
        {rows.map((r, i) =>
          r.percent > 0 ? (
            <div key={r.playerId} className="h-full transition-[width] duration-700 ease-out" style={{ width: `${r.percent}%`, background: laneColor(i) }} />
          ) : null,
        )}
      </div>
      <ul className="grid grid-cols-5 gap-x-[36px] gap-y-[10px]">
        {rows.map((r, i) => (
          <li key={r.playerId} className="flex min-w-0 items-center gap-[10px]">
            <span aria-hidden="true" className="size-[18px] shrink-0 rounded-full" style={{ background: laneColor(i) }} />
            <span className="min-w-0 flex-1 truncate text-[24px] font-semibold">{r.nickname}</span>
            <span className="num font-display text-[24px] font-bold">{r.percent}%</span>
          </li>
        ))}
      </ul>
    </section>
  );
}

/** Finalists' race: horizontal lanes scaled to the leader's points. */
export function FinalistsRace({ pub, className, compact = false }: { pub: PublicState; className?: string; compact?: boolean }) {
  const lanes = finalistLanes(pub.round?.finalists, pub.leaderboard);
  if (lanes.length === 0) return null;
  const seedOf = new Map((pub.round?.finalists ?? []).map((f, i) => [f.playerId, i]));
  return (
    <section aria-label="Final Rush race" className={cn('flex flex-col gap-[12px]', className)}>
      <h3 className="text-[22px] font-bold tracking-[0.18em] text-amber-soft uppercase">Final Rush race</h3>
      <ol className="flex flex-col gap-[10px]">
        {lanes.map((lane, i) => {
          const color = laneColor(seedOf.get(lane.playerId) ?? i);
          return (
            <li key={lane.playerId} className={cn('relative overflow-hidden rounded-[14px] bg-raised/50', compact ? 'h-[60px]' : 'h-[72px]')}>
              <div
                aria-hidden="true"
                className={cn('absolute inset-y-0 left-0 opacity-35', s.barFill)}
                style={cssVars({ '--delay': `${i * 90}ms` }, { width: `${Math.max(6, lane.progress * 100)}%`, background: color })}
              />
              <div className="relative flex h-full items-center gap-[14px] px-[16px]">
                <span className="num grid size-[40px] shrink-0 place-items-center rounded-full font-display text-[22px] font-bold text-on-bright" style={{ background: color }}>
                  {i + 1}
                </span>
                <span className={cn('min-w-0 flex-1 truncate font-semibold', compact ? 'text-[26px]' : 'text-[30px]')}>{lane.nickname}</span>
                <span className={cn('num font-display font-bold', compact ? 'text-[26px]' : 'text-[30px]')}>{formatPoints(lane.points)}</span>
              </div>
            </li>
          );
        })}
      </ol>
    </section>
  );
}
