'use client';

import type { PublicState } from '@pintrush/engine';
import type { RoomSnapshot } from '@pintrush/protocol';
import { LogoMark } from '@/components/brand/Logo';
import { TrophyIcon, UsersIcon } from '@/components/ui/icons';
import { cn } from '@/lib/cn';
import { formatEventTime } from '@/lib/tv/format';
import { useTvEnv } from '../context';
import { cssVars } from '../cssVars';
import { PointsTicker } from '../parts/Leaderboard';
import { JoinQr } from '../parts/JoinQr';
import s from '../tv.module.css';

/** Championship lobby: get everyone in, show who just joined and which tables are forming. */
export function LobbyScreen({ pub, snapshot }: { pub: PublicState; snapshot: RoomSnapshot | null }) {
  const { joinCode, joinUrlText, venueName, timeZone, conn } = useTvEnv();
  const name = snapshot?.activeEventName ?? 'Championship';
  const scheduled = snapshot?.attract.nextChampionship;
  const startsAt = scheduled && scheduled.eventId === pub.eventId ? scheduled.scheduledAt : null;
  const teams = pub.teamLeaderboard.filter((t) => !t.isSolo);
  const joins = pub.recentJoins;
  // A handful of names fits on one line; more scroll as a marquee, duplicated so it loops seamlessly.
  const scroll = joins.length >= 4;
  const ticker = scroll ? [...joins, ...joins] : joins;

  return (
    <div className="absolute inset-0 flex flex-col px-[80px] pt-[60px] pb-[56px]">
      <header className="flex items-center justify-between gap-[40px]">
        <div className="flex min-w-0 items-center gap-[24px]">
          <LogoMark className="size-[84px]" />
          <div className="min-w-0">
            <p className="flex items-center gap-[12px] text-[24px] font-bold tracking-[0.22em] text-amber uppercase">
              <TrophyIcon className="size-[30px]" />
              Championship · {venueName}
            </p>
            <h1 className="mt-[8px] truncate font-display text-[76px] leading-none font-extrabold tracking-[-0.03em]">{name}</h1>
          </div>
        </div>
        <div className="flex shrink-0 flex-col items-end gap-[10px]">
          <span className={cn('rounded-full bg-lime px-[30px] py-[12px] font-display text-[30px] font-extrabold tracking-[0.06em] text-on-bright uppercase', s.urgent)}>
            Starting soon
          </span>
          {startsAt && conn && <span className="text-[26px] font-semibold text-muted">{formatEventTime(startsAt, conn.serverNow(), timeZone)}</span>}
        </div>
      </header>

      <div className="mt-[52px] grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_760px] gap-[64px]">
        <div className="flex min-w-0 items-center gap-[56px]">
          <JoinQr size={460} />
          <div className="flex min-w-0 flex-col gap-[24px]">
            <h2 className="font-display text-[86px] leading-[0.98] font-extrabold tracking-[-0.04em]">
              Scan to
              <br />
              <span className="text-gradient-brand">join in</span>
            </h2>
            <p className="text-[34px] leading-snug text-muted">Pick a nickname, then set your table name to play as a team.</p>
            <p className="text-[28px] text-subtle">
              <span className="font-semibold text-fg">{joinUrlText}</span> · code <span className="font-display font-bold text-amber">{joinCode}</span>
            </p>
          </div>
        </div>

        <div className="flex min-h-0 flex-col gap-[28px]">
          <div className="flex items-end justify-between rounded-[32px] border border-violet/50 bg-violet/15 px-[40px] py-[28px] shadow-glow-violet">
            <div>
              <p className="flex items-center gap-[12px] text-[24px] font-bold tracking-[0.2em] text-violet-soft uppercase">
                <UsersIcon className="size-[30px]" />
                Players in
              </p>
              {pub.plan && (
                <p className="mt-[10px] text-[26px] text-muted">
                  {pub.plan.total} rounds{pub.plan.label ? ` · opens with ${pub.plan.label}` : ''}
                </p>
              )}
            </div>
            <PointsTicker value={pub.playerCount} className="font-display text-[150px] leading-[0.85] font-extrabold" />
          </div>

          <section aria-label="Tables" className="flex min-h-0 flex-1 flex-col rounded-[32px] border border-line bg-surface/85 p-[32px]">
            <h3 className="text-[22px] font-bold tracking-[0.2em] text-cyan-soft uppercase">Tables</h3>
            {teams.length > 0 ? (
              <ul className="mt-[18px] grid grid-cols-2 gap-[14px]">
                {teams.slice(0, 8).map((t, i) => (
                  <li key={t.teamId} className={cn('flex min-w-0 items-center justify-between gap-[12px] rounded-[16px] bg-raised/60 px-[18px] py-[14px]', s.chipIn)} style={cssVars({ '--delay': `${i * 60}ms` })}>
                    <span className="min-w-0 truncate text-[28px] font-semibold">{t.name}</span>
                    <span className="num shrink-0 rounded-full bg-cyan/15 px-[12px] py-[2px] text-[22px] font-bold text-cyan-soft">{t.members}</span>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="mt-[18px] text-[30px] leading-snug text-muted">No tables yet. Set a table name on your phone to team up with your friends.</p>
            )}
          </section>
        </div>
      </div>

      <section aria-label="Just joined" className="mt-[40px] flex h-[92px] items-center gap-[28px] overflow-hidden rounded-full border border-line bg-surface/80 pr-[12px] pl-[36px]">
        <p className="shrink-0 text-[24px] font-bold tracking-[0.2em] text-lime uppercase">Just joined</p>
        {ticker.length > 0 ? (
          <div className="mask-fade-x min-w-0 flex-1 overflow-hidden">
            <ul className={cn('flex w-max', scroll && s.ticker)} style={cssVars({ '--duration': `${Math.max(16, joins.length * 4)}s` })}>
              {ticker.map((n, i) => (
                <li key={`${n}-${i}`} aria-hidden={i >= joins.length} className="mr-[16px] shrink-0 rounded-full bg-raised px-[24px] py-[10px] text-[28px] font-semibold whitespace-nowrap">
                  {n}
                </li>
              ))}
            </ul>
          </div>
        ) : (
          <p className="text-[28px] text-muted">Be the first one in.</p>
        )}
      </section>
    </div>
  );
}
