import { useMemo } from 'react';
import { Link } from '@tanstack/react-router';
import { PageHeader } from '@/components/ui/PageHeader';
import { teamFlag } from '@/lib/teams';
import { useTournamentStore } from '@/stores/tournamentStore';
import { fmt, useT } from '@/lib/i18n';

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

export function TeamsPage() {
  const t = useT();
  const model = useTournamentStore((s) => s.model);
  const snapshot = useTournamentStore((s) => s.snapshot);

  const teams = useMemo(() => {
    const groupOf = new Map<string, string>();
    for (const [g, rows] of Object.entries(snapshot?.tables ?? {})) for (const r of rows) groupOf.set(r.team, g);
    return (model?.odds ?? []).map((o) => ({ ...o, group: groupOf.get(o.team) ?? null }));
  }, [model, snapshot]);

  return (
    <div>
      <PageHeader title={t.teams.title} subtitle={t.teams.subtitle} />
      {teams.length ? (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {teams.map((team, i) => (
            <Link
              key={team.team}
              to="/team/$name"
              params={{ name: team.team }}
              className="flex items-center gap-3 rounded-xl border border-line bg-panel px-4 py-3 transition-colors hover:border-line-strong hover:bg-panel-2"
            >
              <span className="w-5 text-right text-xs font-bold tabular-nums text-faint">{i + 1}</span>
              <span aria-hidden className="text-2xl leading-none">{teamFlag(team.team)}</span>
              <div className="min-w-0">
                <div className="truncate font-semibold text-ink">{team.team}</div>
                <div className="text-[11px] text-faint">{team.group ? fmt(t.common.group, { group: team.group }) : ''}</div>
              </div>
              <div className="ml-auto text-right">
                <div className="tnum text-sm font-bold text-gold">{pct(team.champion)}</div>
                <div className="text-[11px] text-faint">{fmt(t.teams.advanceShort, { pct: pct(team.qualify) })}</div>
              </div>
            </Link>
          ))}
        </div>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {Array.from({ length: 9 }).map((_, i) => <div key={i} className="h-16 animate-pulse rounded-xl border border-line bg-panel" />)}
        </div>
      )}
    </div>
  );
}
