'use client';

import type { PublicState } from '@pintrush/engine';
import type { RoomSnapshot } from '@pintrush/protocol';
import { TrophyIcon } from '@/components/ui/icons';
import { cn } from '@/lib/cn';
import { formatPoints, formatTeamScore } from '@/lib/tv/format';
import { fitDisplaySize } from '@/lib/tv/results';
import { cssVars } from '../cssVars';
import { Leaderboard } from '../parts/Leaderboard';
import { TIE_BREAK_NOTE } from './RoundOverScreen';
import s from '../tv.module.css';

const CONFETTI_COLORS = ['var(--color-amber)', 'var(--color-lime)', 'var(--color-violet-soft)', 'var(--color-cyan)', 'var(--color-amber-soft)'] as const;

// Deterministic pseudo-random layout so server and client render the same pieces.
const CONFETTI = Array.from({ length: 64 }, (_, i) => {
  const r = (n: number) => ((Math.sin(i * 12.9898 + n * 78.233) * 43758.5453) % 1 + 1) % 1;
  return {
    left: `${(r(1) * 100).toFixed(2)}%`,
    // Negative delays: every piece is already mid-fall on the first frame (no row parked at the top).
    delay: `${(-r(2) * 7).toFixed(2)}s`,
    fall: `${(4 + r(3) * 3).toFixed(2)}s`,
    drift: `${Math.round((r(4) - 0.5) * 260)}px`,
    spin: `${Math.round(360 + r(5) * 720)}deg`,
    width: 10 + Math.round(r(6) * 12),
    height: 16 + Math.round(r(7) * 14),
    color: CONFETTI_COLORS[i % CONFETTI_COLORS.length] ?? 'var(--color-amber)',
  };
});

function Confetti() {
  return (
    <div aria-hidden="true" className={cn('pointer-events-none absolute inset-0 overflow-hidden', s.confetti)}>
      {CONFETTI.map((c, i) => (
        <span
          key={i}
          className={cn('absolute top-0 rounded-[3px]', s.confettiPiece)}
          style={cssVars({ '--delay': c.delay, '--fall': c.fall, '--drift': c.drift, '--spin': c.spin }, { left: c.left, width: c.width, height: c.height, background: c.color })}
        />
      ))}
    </div>
  );
}

/** Event complete: crown the champion (confetti only with motion allowed) and show final standings. */
export function CompleteScreen({ pub, snapshot }: { pub: PublicState; snapshot: RoomSnapshot | null }) {
  const champion = pub.leaderboard[0] ?? null;
  const topTeam = pub.teamLeaderboard.find((t) => !t.isSolo) ?? null;
  const eventName = snapshot?.activeEventName ?? (pub.mode === 'CHAMPIONSHIP' ? 'Championship' : 'Tonight');

  return (
    <div className="absolute inset-0">
      <Confetti />
      <div className="relative grid size-full grid-cols-[minmax(0,1fr)_720px] gap-[64px] px-[80px] py-[64px]">
        <div className="relative flex min-w-0 flex-col items-center justify-center text-center">
          <div
            aria-hidden="true"
            className={cn(
              'absolute top-1/2 left-1/2 size-[1100px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-[repeating-conic-gradient(rgb(255_176_32/0.10)_0deg_8deg,transparent_8deg_20deg)] [mask-image:radial-gradient(closest-side,#000,transparent)]',
              s.rays,
            )}
          />
          <p className="relative text-[32px] font-bold tracking-[0.3em] text-amber uppercase">{eventName} · Champion</p>
          {champion ? (
            <>
              <TrophyIcon className={cn('relative mt-[36px] size-[200px] text-amber drop-shadow-[0_0_60px_rgb(255_176_32/0.7)]', s.lockBeat)} />
              {/* Left column is 976 px wide: the name shrinks to fit on one line instead of truncating. */}
              <h1
                className={cn('relative mt-[28px] max-w-full font-display leading-[1.08] font-extrabold tracking-[-0.045em] whitespace-nowrap text-gradient-gold', s.slam)}
                style={{ fontSize: fitDisplaySize(champion.nickname, 940, 150, 64) }}
              >
                {champion.nickname}
              </h1>
              <p className="num relative mt-[18px] font-display text-[64px] font-bold">{formatPoints(champion.points)} points</p>
              <p className="relative mt-[12px] text-[30px] text-muted">
                {champion.correct} correct · {champion.lines} {champion.lines === 1 ? 'line' : 'lines'}
              </p>
              {topTeam && (
                <p className="relative mt-[36px] rounded-full border border-cyan/50 bg-cyan/12 px-[32px] py-[14px] text-[32px] font-semibold text-cyan-soft">
                  Top table: <span className="font-display font-bold text-fg">{topTeam.name}</span> · {formatTeamScore(topTeam.score)}
                </p>
              )}
            </>
          ) : (
            <h1 className="relative mt-[36px] font-display text-[110px] leading-none font-extrabold">Thanks for playing!</h1>
          )}
        </div>
        <section aria-label="Final standings" className="flex min-h-0 flex-col rounded-[36px] border border-line bg-surface/90 p-[40px] shadow-card">
          <h2 className="mb-[20px] text-[26px] font-bold tracking-[0.2em] text-subtle uppercase">Final standings</h2>
          <Leaderboard standings={pub.leaderboard} label="Final standings" size="mini" />
          <p className="mt-auto pt-[16px] text-[20px] text-subtle">{TIE_BREAK_NOTE}</p>
        </section>
      </div>
    </div>
  );
}
