import { Link } from '@tanstack/react-router';
import { cn } from '@/lib/cn';
import { teamFlag } from '@/lib/teams';
import type { Fixture, TeamSlot } from '@/lib/types';
import { fmt, useFormat, useT, type Dict } from '@/lib/i18n';
import { useTournamentStore } from '@/stores/tournamentStore';
import { TeamLabel } from './TeamLabel';

/** The model's pre-match lean for scheduled matches — the "expectation" hint. */
function ModelHint({ num }: { num: number }) {
  const t = useT();
  const pred = useTournamentStore((s) => s.model?.matches.find((m) => m.num === num));
  if (!pred) return null;
  const { home, draw, away } = pred.probs;
  const drawLikely = draw >= home && draw >= away;
  const homeFav = home >= away;
  const side = drawLikely ? null : homeFav ? pred.home : pred.away;
  const p = drawLikely ? draw : Math.max(home, away);
  return (
    <div className="mt-1.5 text-center text-[11px] text-faint">
      {t.match.modelPrefix} {side ? <>{teamFlag(side)} {side} </> : `${t.common.draw} `}
      <span className="font-semibold text-muted">{Math.round(p * 100)}%</span>
    </div>
  );
}

function tag(f: Fixture, t: Dict): string {
  if (f.stage === 'group') return fmt(t.common.group, { group: f.group ?? '' });
  return t.stage[f.stage];
}

function StatusPill({ f }: { f: Fixture }) {
  const { t, relativeKickoff } = useFormat();
  if (f.status === 'live') {
    return (
      <span className="inline-flex items-center gap-1.5 rounded-full border border-live/40 bg-live/15 px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide text-live">
        <span className="live-dot h-1.5 w-1.5 rounded-full bg-live" />
        {f.minute ? fmt(t.live.minute, { n: f.minute }) : t.status.live}
      </span>
    );
  }
  if (f.status === 'finished') {
    return <span className="text-[11px] font-bold uppercase tracking-wide text-faint">{t.common.fullTimeShort}</span>;
  }
  return <span className="text-[11px] font-semibold text-muted">{relativeKickoff(f.kickoff)}</span>;
}

/** One team row of a played match: flag · name · score, loser dimmed. */
function TeamRow({ slot, score, dim }: { slot: TeamSlot; score: number; dim: boolean }) {
  return (
    <div className="flex min-w-0 items-center gap-2.5">
      <span aria-hidden className="text-xl leading-none">{slot.team ? teamFlag(slot.team) : '·'}</span>
      <span className={cn('truncate text-[15px] font-semibold', dim ? 'text-faint' : 'text-ink')}>{slot.team ?? slot.label}</span>
      <span className={cn('tnum ml-auto shrink-0 text-base font-semibold', dim ? 'text-faint' : 'text-ink')}>{score}</span>
    </div>
  );
}

export function MatchCard({ f }: { f: Fixture }) {
  const { t } = useFormat();
  const hasScore = f.status === 'live' || f.status === 'finished';
  const hs = f.homeScore ?? 0;
  const as = f.awayScore ?? 0;
  // Dim the beaten side once the result stands; everyone stays lit while live.
  const dimHome = f.status === 'finished' && hs < as;
  const dimAway = f.status === 'finished' && as < hs;
  return (
    <Link
      to="/match/$num"
      params={{ num: String(f.num) }}
      className={cn(
        'block rounded-xl border border-line bg-panel px-4 py-3 transition-colors hover:border-line-strong hover:bg-panel-2',
        f.status === 'live' && 'border-live/40 ring-1 ring-live/30',
      )}
    >
      <div className="mb-2.5 flex items-center justify-between gap-2">
        <span className="smallcaps">{tag(f, t)}</span>
        <StatusPill f={f} />
      </div>
      {hasScore ? (
        <div className="flex flex-col gap-1.5">
          <TeamRow slot={f.home} score={hs} dim={dimHome} />
          <TeamRow slot={f.away} score={as} dim={dimAway} />
        </div>
      ) : (
        <div className="flex items-center justify-center gap-3">
          <span className="flex min-w-0 flex-1 justify-end"><TeamLabel slot={f.home} align="right" /></span>
          <span className="tnum shrink-0 text-xs text-faint">{t.common.vs}</span>
          <span className="flex min-w-0 flex-1"><TeamLabel slot={f.away} align="left" /></span>
        </div>
      )}
      {f.status === 'scheduled' && <ModelHint num={f.num} />}
      <div className="mt-1.5 truncate text-center text-xs text-faint">{f.venue}</div>
    </Link>
  );
}
