import type { Metadata } from 'next';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import { Logo, LogoMark } from '@/components/brand/Logo';
import { CodeForm } from './_lib/CodeForm';
import { JoinBackdrop } from './_lib/JoinBackdrop';
import { isJoinCode } from './_lib/venue';

export const metadata: Metadata = {
  title: 'Join a game',
  description: 'Type the game code from the TV to play PintRush. Nickname only — no app, no account.',
};

/** pintrush.com/join: enter the code from the TV (for guests who can't or won't scan). */
export default async function JoinCodePage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const raw = (await searchParams).code;
  const code = (Array.isArray(raw) ? raw[0] : raw)?.trim() ?? '';
  if (code && isJoinCode(code)) redirect(`/join/${encodeURIComponent(code.toUpperCase())}`);
  const invalid = code.length > 0;

  return (
    <main id="main" tabIndex={-1} className="relative isolate flex min-h-dvh flex-col outline-none">
      <JoinBackdrop />
      <div className="mx-auto flex h-14 w-full max-w-md items-center px-4">
        <Link href="/" prefetch={false} className="-m-1 rounded-lg p-1" aria-label="PintRush home">
          <Logo size="sm" />
        </Link>
      </div>
      <div className="mx-auto flex w-full max-w-md flex-1 flex-col px-4 pt-8 pb-[max(1.5rem,env(safe-area-inset-bottom))]">
        <LogoMark className="mx-auto size-16 motion-safe:animate-float" />
        <h1 className="mt-5 text-center font-display text-3xl font-bold">Join the game</h1>
        <p className="mt-3 text-center text-muted">Scan the QR code on the TV — or type the game code below.</p>
        {invalid && (
          <p role="alert" className="mt-6 rounded-xl border border-danger/50 bg-danger/10 px-4 py-3 text-sm font-medium text-danger-soft">
            Game codes are 2–12 letters or numbers. Check the TV and try again.
          </p>
        )}
        <div className="mt-8">
          <CodeForm defaultValue={invalid ? code.slice(0, 12) : ''} autoFocus />
        </div>
      </div>
    </main>
  );
}
