import { Link } from '@tanstack/react-router';
import { teamFlag } from '@/lib/teams';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n';
import type { TeamOdds } from '@/lib/types';

// Column order; labels come from the dictionary (t.predict.oddsTable.*).
const colKeys = [
  'winGroup',
  'qualify',
  'reachR16',
  'reachQF',
  'reachSF',
  'reachFinal',
  'champion',
] as const satisfies readonly (keyof Omit<TeamOdds, 'team'>)[];

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

// Lower-value columns make way on phones; Team/QF/SF/Final/Champion stay.
const HIDE_ON_PHONE = new Set<(typeof colKeys)[number]>(['winGroup', 'qualify', 'reachR16']);

/** Heat-shaded cell: stronger odds → more accent (or gold for the title) tint. */
function Cell({ x, accent = false, hideOnPhone = false }: { x: number; accent?: boolean; hideOnPhone?: boolean }) {
  return (
    <td
      className={cn(
        'py-1.5 text-center text-sm tabular-nums',
        x < 0.005 ? 'text-faint' : 'text-ink',
        hideOnPhone && 'hidden sm:table-cell',
      )}
      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[] }) {
  const t = useT();
  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="sticky left-0 z-10 bg-panel px-3 py-2 text-left font-semibold">{t.predict.oddsTable.team}</th>
            {colKeys.map((key) => (
              <th key={key} className={cn('px-2 py-2 text-center font-semibold', HIDE_ON_PHONE.has(key) && 'hidden sm:table-cell')}>
                {t.predict.oddsTable[key]}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {odds.map((o) => (
            <tr key={o.team} className="border-t border-line/60">
              <td className="sticky left-0 z-10 bg-panel px-3 py-1.5">
                <Link to="/team/$name" params={{ name: o.team }} className="flex items-center gap-2 hover:text-accent">
                  <span aria-hidden className="text-base leading-none">{teamFlag(o.team)}</span>
                  <span className="truncate text-sm font-medium text-ink">{o.team}</span>
                </Link>
              </td>
              {colKeys.map((key) => (
                <Cell key={key} x={o[key]} accent={key === 'champion'} hideOnPhone={HIDE_ON_PHONE.has(key)} />
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
