import { teamFlag } from '@/lib/teams';
import { cn } from '@/lib/cn';
import type { TeamOdds } from '@/lib/types';

const cols: { key: keyof Omit<TeamOdds, 'team'>; label: string }[] = [
  { key: 'winGroup', label: 'Win grp' },
  { key: 'qualify', label: 'Qualify' },
  { key: 'reachR16', label: 'R16' },
  { key: 'reachQF', label: 'QF' },
  { key: 'reachSF', label: 'SF' },
  { key: 'reachFinal', label: 'Final' },
  { key: 'champion', label: 'Champion' },
];

const pct = (x: number) => (x >= 0.995 ? '>99%' : x < 0.005 ? '—' : `${Math.round(x * 100)}%`);

/** Heat-shaded cell: stronger odds → more accent (or gold for the title) tint. */
function Cell({ x, accent = false }: { x: number; accent?: boolean }) {
  return (
    <td
      className={cn('py-1.5 text-center text-sm tabular-nums', x < 0.005 ? 'text-faint' : 'text-ink')}
      style={x >= 0.005 ? { background: `color-mix(in oklab, var(--app-${accent ? 'gold' : 'accent'}) ${Math.round(x * 60)}%, transparent)` } : undefined}
    >
      {pct(x)}
    </td>
  );
}

export function OddsTable({ odds }: { odds: TeamOdds[] }) {
  return (
    <div className="overflow-x-auto rounded-xl border border-line bg-panel">
      <table className="w-full border-collapse">
        <thead>
          <tr className="border-b border-line text-[11px] uppercase tracking-wide text-faint">
            <th className="px-3 py-2 text-left font-semibold">Team</th>
            {cols.map((c) => (
              <th key={c.key} className="px-2 py-2 text-center font-semibold">{c.label}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {odds.map((o) => (
            <tr key={o.team} className="border-t border-line/60">
              <td className="px-3 py-1.5">
                <span className="flex items-center gap-2">
                  <span aria-hidden className="text-base leading-none">{teamFlag(o.team)}</span>
                  <span className="truncate text-sm font-medium text-ink">{o.team}</span>
                </span>
              </td>
              {cols.map((c) => (
                <Cell key={c.key} x={o[c.key]} accent={c.key === 'champion'} />
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
