'use client';

import type { PublicState, Standing } from '@pintrush/engine';
import type { ReactNode } from 'react';
import { BoltIcon, CheckIcon, TrophyIcon, UsersIcon } from '@/components/ui/icons';
import { cn } from '@/lib/cn';
import { formatSeconds } from '@/lib/tv/format';
import { challengeWinnerNames, distributionRows, promptFontSize, REVEAL_PROMPT_SIZES } from '@/lib/tv/results';
import { cssVars } from '../cssVars';
import { FinalistsRace } from '../parts/FinalRush';
import { Leaderboard } from '../parts/Leaderboard';
import { TopBar } from '../parts/TopBar';
import { QuestionChips } from './QuestionScreen';
import s from '../tv.module.css';

function Card({ title, icon, children, className }: { title: string; icon: ReactNode; children: ReactNode; className?: string }) {
  return (
    <section aria-label={title} className={cn('flex flex-col gap-[16px] rounded-[30px] border border-line bg-surface/85 p-[28px] shadow-card', className)}>
      <h2 className="flex items-center gap-[12px] text-[22px] font-bold tracking-[0.2em] text-subtle uppercase">
        {icon}
        {title}
      </h2>
      {children}
    </section>
  );
}

/**
 * REVEALED: the correct option (check icon + "Correct" label, not colour alone), how the room voted,
 * the fastest correct answers and the leaderboard shuffling into its new order.
 */
export function RevealScreen({ pub, previousStandings }: { pub: PublicState; previousStandings: readonly Standing[] | null }) {
  const q = pub.question;
  const round = pub.round;
  const reveal = pub.reveal;
  if (!q || !round || !reveal || !q.options || !q.prompt) return null;
  const rows = distributionRows(q.options, reveal);
  const winners = round.kind === 'TABLE_WARS' ? challengeWinnerNames(pub, reveal.challengeWinners) : [];
  const correctText = rows.find((r) => r.correct);
  // Left column is 1168 px wide; 864 px tall minus chips, summary line and the answer rows (104 px + 14 px gaps).
  const promptHeight = 864 - 148 - (rows.length * 104 + Math.max(0, rows.length - 1) * 14);

  return (
    <div className="absolute inset-0 flex flex-col px-[72px] pt-[48px] pb-[48px]">
      <TopBar pub={pub} />
      <div className="mt-[32px] grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_560px] gap-[48px]">
        <div className="flex min-w-0 flex-col">
          <QuestionChips q={q} kind={round.kind} />
          <h1 className="mt-[18px] font-display leading-[1.1] font-bold tracking-[-0.02em] text-balance" style={{ fontSize: promptFontSize(q.prompt, { width: 1168, height: promptHeight }, REVEAL_PROMPT_SIZES) }}>
            {q.prompt}
          </h1>
          <ul className="mt-auto flex flex-col gap-[14px]" aria-label="How the room answered">
            {rows.map((row, i) => (
              <li
                key={row.id}
                className={cn(
                  'relative flex h-[104px] items-center overflow-hidden rounded-[24px] border-2',
                  row.correct ? 'border-lime bg-lime/8 shadow-glow-lime' : 'border-line bg-raised/40',
                )}
              >
                <div
                  aria-hidden="true"
                  className={cn('absolute inset-y-0 left-0', row.correct ? 'bg-lime/30' : 'bg-line/80', s.barFill)}
                  style={cssVars({ '--delay': `${200 + i * 90}ms` }, { width: `${row.percent}%` })}
                />
                <div className="relative flex w-full items-center gap-[24px] px-[22px]">
                  <span
                    className={cn(
                      'grid size-[68px] shrink-0 place-items-center rounded-[18px] font-display text-[36px] font-extrabold',
                      row.correct ? 'bg-lime text-on-bright' : 'bg-raised text-muted',
                    )}
                  >
                    {row.correct ? <CheckIcon className="size-[40px]" strokeWidth={3} /> : row.letter}
                  </span>
                  <span className={cn('min-w-0 flex-1 truncate text-[38px] font-semibold', row.correct ? 'text-fg' : 'text-muted')}>
                    {row.correct && <span className="sr-only">Correct answer: </span>}
                    {row.text}
                  </span>
                  {row.correct && (
                    <span className={cn('shrink-0 rounded-full bg-lime px-[18px] py-[6px] font-display text-[22px] font-extrabold tracking-[0.12em] text-on-bright uppercase', s.chipIn)}>
                      Correct
                    </span>
                  )}
                  <span className="num shrink-0 text-right text-[30px] text-muted">
                    {row.count} <span className="sr-only">answers,</span>
                  </span>
                  <span className={cn('num w-[150px] shrink-0 text-right font-display text-[40px] font-bold', row.correct && 'text-lime-soft')}>{row.percent}%</span>
                </div>
              </li>
            ))}
          </ul>
          <p className="mt-[20px] text-[30px] text-muted">
            <span className="font-display font-bold text-fg">{reveal.correctCount}</span> of {reveal.answeredCount} got it right
            {correctText && (
              <>
                {' · '}
                <span className="font-semibold text-lime-soft">
                  {correctText.letter}. {correctText.text}
                </span>
              </>
            )}
          </p>
        </div>

        <div className="flex min-h-0 flex-col gap-[24px]">
          {round.kind === 'TABLE_WARS' && (
            <Card title="Challenge won by" icon={<UsersIcon className="size-[28px] text-amber" />} className="border-amber/50 bg-amber/10">
              {winners.length > 0 ? (
                <>
                  <ul className="flex flex-col gap-[6px]">
                    {winners.map((name) => (
                      <li key={name} className={cn('truncate text-[36px] leading-tight font-extrabold text-amber-soft', s.chipIn)}>
                        {name}
                      </li>
                    ))}
                  </ul>
                  <p className="num text-[24px] text-muted">+200 for every member</p>
                </>
              ) : (
                <p className="text-[28px] text-muted">No table got this one.</p>
              )}
            </Card>
          )}

          <Card title="Fastest correct" icon={<BoltIcon className="size-[28px] text-cyan" />}>
            {reveal.fastest.length > 0 ? (
              <ol className="flex flex-col gap-[10px]">
                {reveal.fastest.map((f, i) => (
                  <li
                    key={f.playerId}
                    className={cn('flex h-[66px] items-center gap-[16px] rounded-[16px] bg-raised/60 px-[16px]', s.chipIn)}
                    style={cssVars({ '--delay': `${400 + i * 120}ms` })}
                  >
                    <span className={cn('num grid size-[44px] place-items-center rounded-full font-display text-[24px] font-bold', i === 0 ? 'bg-amber text-on-bright' : 'bg-raised text-muted')}>
                      {i + 1}
                    </span>
                    <span className="min-w-0 flex-1 truncate text-[30px] font-semibold">{f.nickname}</span>
                    <span className="num font-display text-[30px] font-bold text-cyan-soft">{formatSeconds(f.elapsedMs)}</span>
                  </li>
                ))}
              </ol>
            ) : (
              <p className="text-[28px] text-muted">Nobody got this one. Tough crowd!</p>
            )}
          </Card>

          {round.kind === 'FINAL_RUSH' ? (
            <FinalistsRace pub={pub} compact className="rounded-[30px] border border-line bg-surface/85 p-[28px]" />
          ) : (
            <Card title={pub.mode === 'CHAMPIONSHIP' ? 'Standings' : 'Tonight'} icon={<TrophyIcon className="size-[28px] text-amber" />} className="min-h-0 flex-1">
              <Leaderboard
                standings={pub.leaderboard}
                previous={previousStandings}
                limit={round.kind === 'TABLE_WARS' ? 3 : 5}
                size="mini"
                label="Leaderboard"
              />
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
