import { useEffect, useMemo, useState } from 'react';
import { Link } from '@tanstack/react-router';
import { Award } from 'lucide-react';
import { PageHeader } from '@/components/ui/PageHeader';
import { Card, CardBody, CardHeader } from '@/components/ui/Card';
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)}%`);

interface BootRow { player: string; team: string; goals: number }

/** Live Golden Boot standings from structured ESPN scoring plays. */
function GoldenBoot() {
  const t = useT();
  const [players, setPlayers] = useState<BootRow[] | null>(null);

  useEffect(() => {
    let alive = true;
    fetch('/api/goldenboot')
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((d: { players: BootRow[] }) => alive && setPlayers(d.players))
      .catch(() => alive && setPlayers([]));
    return () => { alive = false; };
  }, []);

  if (!players || players.length === 0) return null;
  const top = players.slice(0, 10);
  const max = top[0]?.goals ?? 1;

  return (
    <Card className="mb-5">
      <CardHeader className="flex items-center gap-2">
        <Award size={16} className="text-gold" />
        <span className="font-display font-bold text-ink">{t.teams.goldenBoot}</span>
      </CardHeader>
      <CardBody>
        <ol className="space-y-1.5">
          {top.map((p, i) => (
            <li key={`${p.player}|${p.team}`} className="flex items-center gap-2.5 text-sm">
              <span className="w-4 shrink-0 text-right text-xs font-bold tabular-nums text-faint">{i + 1}</span>
              <span aria-hidden className="shrink-0">{p.team ? teamFlag(p.team) : ''}</span>
              <span className="truncate font-medium text-ink">{p.player}</span>
              <div className="ml-auto flex h-2 w-24 shrink-0 overflow-hidden rounded-full bg-elevated sm:w-40">
                <div className="bg-gradient-to-r from-gold/60 to-gold" style={{ width: `${(p.goals / max) * 100}%` }} />
              </div>
              <span className="tnum w-5 shrink-0 text-right font-bold text-ink">{p.goals}</span>
            </li>
          ))}
        </ol>
        <p className="mt-2 text-[11px] text-faint">{t.teams.goldenBootNote}</p>
      </CardBody>
    </Card>
  );
}

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} />
      <GoldenBoot />
      {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>
  );
}
