'use client';

import type { PublicState } from '@pintrush/engine';
import { LogoMark } from '@/components/brand/Logo';
import { cn } from '@/lib/cn';
import { useTvEnv } from '../context';

type Round = NonNullable<PublicState['round']>;

/** "Round 3 of 9" in a championship, "Round 4 tonight" in always-on play ("Round 4 complete" when done). */
export function roundCaption(pub: Pick<PublicState, 'plan'>, round: Pick<Round, 'index'>, state: 'live' | 'complete' = 'live'): string {
  const base = pub.plan ? `Round ${Math.min(pub.plan.index + 1, pub.plan.total)} of ${pub.plan.total}` : `Round ${round.index + 1}`;
  if (state === 'complete') return `${base} complete`;
  return pub.plan ? base : `${base} tonight`;
}

/** One pip per question; the wildcard (last question of a board round) gets a star. */
function QuestionPips({ round }: { round: Round }) {
  const current = round.qIndex;
  return (
    <div className="flex items-center gap-[18px]">
      <ol className="flex items-center gap-[10px]" aria-hidden="true">
        {Array.from({ length: round.questionCount }, (_, i) => {
          const wildcard = round.hasBoard && i === round.questionCount - 1;
          const done = i < current || (i === current && round.phase === 'REVEALED') || round.phase === 'ROUND_OVER';
          const active = i === current && round.phase !== 'ROUND_OVER';
          return (
            <li
              key={i}
              className={cn(
                'grid place-items-center rounded-full transition-all duration-500',
                active ? 'size-[30px] bg-cyan shadow-glow-cyan' : 'size-[18px]',
                !active && done && 'bg-violet-soft',
                !active && !done && 'border-2 border-line-strong bg-transparent',
              )}
            >
              {wildcard && (
                <svg viewBox="0 0 24 24" className={cn(active ? 'size-[20px] text-on-bright' : 'size-[12px]', !active && (done ? 'text-night' : 'text-amber'))}>
                  <path fill="currentColor" d="m12 2 2.9 6.6 7.1.6-5.4 4.7 1.6 7L12 17.3 5.8 21l1.6-7L2 9.2l7.1-.6L12 2Z" />
                </svg>
              )}
            </li>
          );
        })}
      </ol>
      {current >= 0 && round.phase !== 'ROUND_OVER' && (
        <span className="num font-display text-[26px] font-bold text-muted">
          Q{current + 1}
          <span className="text-subtle">/{round.questionCount}</span>
        </span>
      )}
    </div>
  );
}

/** Broadcast header: brand + round, question progress, and how to join. */
export function TopBar({ pub, showPips = true }: { pub: PublicState; showPips?: boolean }) {
  const { joinCode, joinUrlText } = useTvEnv();
  const round = pub.round;
  return (
    <header className="flex h-[88px] items-center justify-between gap-[40px]">
      <div className="flex min-w-0 items-center gap-[20px]">
        <LogoMark className="size-[68px]" />
        <div className="min-w-0">
          <p className="truncate font-display text-[34px] leading-none font-bold tracking-[-0.02em] uppercase">{round?.label ?? 'PintRush'}</p>
          {round && <p className="mt-[8px] text-[22px] leading-none font-semibold text-muted">{roundCaption(pub, round)}</p>}
        </div>
      </div>
      {showPips && round && round.questionCount > 0 && <QuestionPips round={round} />}
      <div className="flex shrink-0 items-center gap-[16px] rounded-full border border-line bg-surface/80 py-[10px] pr-[12px] pl-[26px]">
        <span className="text-[22px] font-semibold text-muted">{joinUrlText}</span>
        <span className="rounded-full bg-amber px-[18px] py-[6px] font-display text-[24px] font-bold tracking-[0.04em] text-on-bright">{joinCode}</span>
      </div>
    </header>
  );
}
