'use client';

import type { PublicState, RoundKind } from '@pintrush/engine';
import type { ComponentType } from 'react';
import { DoubleDownIcon, GridIcon, MusicIcon, SecondChanceIcon, SwapIcon, TargetIcon, TrophyIcon, UsersIcon } from '@/components/ui/icons';
import type { IconProps } from '@/components/ui/icons';
import { cn } from '@/lib/cn';
import { formatPoints } from '@/lib/tv/format';
import { useTvEnv } from '../context';
import { cssVars } from '../cssVars';
import { CountdownSeconds } from '../parts/Countdown';
import { PredictionBar } from '../parts/FinalRush';
import { roundCaption } from '../parts/TopBar';
import s from '../tv.module.css';

const TAGLINES: Record<RoundKind, string> = {
  RUSH: '9 categories plus a wildcard. Every correct answer lights a tile on your board.',
  MUSIC_MAYHEM: 'Songs, artists and charts: all trivia, no recordings, no lyrics. Lines still count.',
  POWER_ROUND: 'Power-ups take centre stage. Earn them with lines, then play them at the right moment.',
  TABLE_WARS: 'Every question is a table challenge. Smaller tables are never at a disadvantage.',
  FINAL_RUSH: 'The top five face off over five tough questions. Everyone else calls the winner.',
};

const KIND_ICON: Record<RoundKind, ComponentType<IconProps>> = {
  RUSH: GridIcon,
  MUSIC_MAYHEM: MusicIcon,
  POWER_ROUND: TargetIcon,
  TABLE_WARS: UsersIcon,
  FINAL_RUSH: TrophyIcon,
};

function Explainers({ items }: { items: { icon: ComponentType<IconProps>; title: string; body: string }[] }) {
  return (
    <ul className="grid grid-cols-3 gap-[32px]">
      {items.map(({ icon: Icon, title, body }, i) => (
        <li
          key={title}
          className={cn('flex flex-col gap-[18px] rounded-[30px] border border-line bg-surface/85 p-[36px] shadow-card', s.chipIn)}
          style={cssVars({ '--delay': `${250 + i * 140}ms` })}
        >
          <span className="grid size-[84px] place-items-center rounded-[22px] border border-violet/50 bg-violet/15 text-violet-soft">
            <Icon className="size-[44px]" />
          </span>
          <p className="font-display text-[38px] leading-tight font-bold">{title}</p>
          <p className="text-[28px] leading-snug text-muted">{body}</p>
        </li>
      ))}
    </ul>
  );
}

function CategoryGrid({ categories }: { categories: { key: string; label: string }[] }) {
  return (
    <div className="flex flex-col items-center gap-[22px]">
      <ul className="grid grid-cols-3 gap-[18px]">
        {categories.slice(0, 9).map((c, i) => (
          <li
            key={c.key}
            className={cn(
              'flex h-[112px] w-[400px] items-center justify-center rounded-[22px] border px-[20px] text-center font-display text-[34px] leading-tight font-bold',
              i === 4 ? 'border-cyan/60 bg-cyan/15 text-cyan-soft' : 'border-violet/40 bg-violet/12',
              s.chipIn,
            )}
            style={cssVars({ '--delay': `${200 + i * 70}ms` })}
          >
            {c.label}
          </li>
        ))}
      </ul>
      <p className="text-[26px] text-subtle">Everyone has all nine on their board, each in a different layout. Question 10 is the wildcard.</p>
    </div>
  );
}

function Finalists({ pub }: { pub: PublicState }) {
  const finalists = pub.round?.finalists ?? [];
  const points = new Map(pub.leaderboard.map((s) => [s.playerId, s.points]));
  return (
    <div className="flex w-full flex-col gap-[36px]">
      <ol className="grid grid-cols-5 gap-[24px]">
        {finalists.map((f, i) => (
          <li
            key={f.playerId}
            className={cn(
              'flex min-w-0 flex-col items-center gap-[14px] rounded-[30px] border px-[20px] py-[30px]',
              i === 0 ? 'border-amber/60 bg-amber/12 shadow-glow-amber' : 'border-line bg-surface/85',
              s.chipIn,
            )}
            style={cssVars({ '--delay': `${300 + i * 150}ms` })}
          >
            <span className={cn('num grid size-[64px] place-items-center rounded-full font-display text-[32px] font-extrabold', i === 0 ? 'bg-amber text-on-bright' : 'bg-raised text-muted')}>
              {i + 1}
            </span>
            <span className="line-clamp-2 w-full text-center text-[34px] leading-[1.1] font-extrabold break-words">{f.nickname}</span>
            {points.has(f.playerId) && <span className="num font-display text-[28px] font-bold text-muted">{formatPoints(points.get(f.playerId) ?? 0)}</span>}
          </li>
        ))}
      </ol>
      <PredictionBar pub={pub} />
    </div>
  );
}

/** Round title card: what kind of round is next and how it works. */
export function IntroScreen({ pub }: { pub: PublicState }) {
  const { joinCode } = useTvEnv();
  const round = pub.round;
  if (!round) return null;
  const Icon = KIND_ICON[round.kind];
  const finalRush = round.kind === 'FINAL_RUSH';

  return (
    <div className="absolute inset-0 flex flex-col items-center px-[100px] pt-[72px] pb-[56px] text-center">
      <p className="flex items-center gap-[16px] text-[30px] font-bold tracking-[0.24em] text-cyan uppercase">
        <Icon className="size-[38px]" />
        {roundCaption(pub, round)}
      </p>
      <h1 className={cn('mt-[18px] px-[20px] font-display text-[150px] leading-[1] font-extrabold tracking-[-0.045em] text-gradient-brand', s.slam)}>{round.label}</h1>
      <p className={cn('mt-[18px] max-w-[1400px] text-[36px] leading-snug text-muted', s.sceneIn)}>{TAGLINES[round.kind]}</p>

      <div className="mt-[48px] flex w-full min-h-0 flex-1 items-start justify-center">
        {round.hasBoard && round.kind !== 'POWER_ROUND' && <CategoryGrid categories={round.categories} />}
        {round.kind === 'POWER_ROUND' && (
          <Explainers
            items={[
              { icon: DoubleDownIcon, title: 'Double Down', body: 'Bet 100 before a question opens: right +200, wrong −100.' },
              { icon: SecondChanceIcon, title: 'Second Chance', body: 'Knock out one wrong option while the question is open.' },
              { icon: SwapIcon, title: 'Category Swap', body: 'Swap two unlit tiles between questions to set up a line.' },
            ]}
          />
        )}
        {round.kind === 'TABLE_WARS' && (
          <Explainers
            items={[
              { icon: UsersIcon, title: 'Team up', body: `Set your table name on your phone. Joining late? Code ${joinCode}.` },
              { icon: TargetIcon, title: 'Best accuracy wins', body: 'Each question goes to the table with the highest share of correct answers.' },
              { icon: TrophyIcon, title: '+200 each', body: 'Every member of the winning table scores 200, so team averages stay fair.' },
            ]}
          />
        )}
        {finalRush && <Finalists pub={pub} />}
      </div>

      <p className="mt-[24px] text-[30px] font-semibold text-muted">
        Starting in <CountdownSeconds endsAt={round.phaseEndsAt} className="font-display font-bold text-fg" />
      </p>
    </div>
  );
}
