import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Logo, LogoMark } from '@/components/brand/Logo';
import { cn } from '@/lib/cn';
import { JoinBackdrop } from '../_lib/JoinBackdrop';
import { findJoinVenue } from '../_lib/venue';
import { JoinForm } from './JoinForm';

type SearchParams = Record<string, string | string[] | undefined>;
interface Props {
  params: Promise<{ venueCode: string }>;
  searchParams: Promise<SearchParams>;
}

const first = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const venue = await findJoinVenue((await params).venueCode);
  return {
    title: venue ? `Join the game at ${venue.name}` : 'Venue not found',
    description: venue ? `Play live trivia at ${venue.name}. Nickname only — no app, no account.` : undefined,
    // Join links are venue-specific and short-lived in purpose; keep them out of search results.
    robots: { index: false, follow: false },
  };
}

export default async function JoinPage({ params, searchParams }: Props) {
  const [{ venueCode }, query] = await Promise.all([params, searchParams]);
  const venue = await findJoinVenue(venueCode);
  if (!venue) notFound();

  // ?room= must belong to this venue; anything else falls back to the venue's first active room.
  const roomParam = first(query.room);
  const room = venue.rooms.find((r) => r.id === roomParam) ?? venue.rooms[0] ?? null;
  // ?embed=1: inside the /demo page's phone frame — compact, and no links out of the game.
  const embed = first(query.embed) === '1';

  return (
    <main id="main" tabIndex={-1} className="relative isolate flex min-h-dvh flex-col outline-none">
      <JoinBackdrop />
      {!embed && (
        <div className="mx-auto flex h-14 w-full max-w-md items-center px-4">
          <Link href="/" className="-m-1 rounded-lg p-1" aria-label="PintRush home">
            <Logo size="sm" />
          </Link>
        </div>
      )}
      <div className={cn('mx-auto flex w-full max-w-md flex-1 flex-col px-4 pb-[max(1.25rem,env(safe-area-inset-bottom))]', embed ? 'pt-5' : 'pt-4')}>
        <header className={cn('flex flex-col items-center text-center', embed ? 'gap-1.5' : 'gap-2')}>
          <LogoMark className={cn('motion-safe:animate-float', embed ? 'size-12' : 'size-16')} />
          <p className="text-sm text-muted">You’re joining</p>
          <h1 className={cn('font-display leading-tight font-bold text-balance', embed ? 'text-2xl' : 'text-[clamp(1.75rem,7vw,2.25rem)]')}>
            {venue.name}
          </h1>
          {room && venue.rooms.length > 1 && <p className="text-sm font-semibold text-violet-soft">{room.name}</p>}
        </header>

        {room ? (
          <JoinForm venueCode={venue.joinCode} venueName={venue.name} roomId={room.id} embed={embed} />
        ) : (
          <div role="status" className="mt-8 rounded-card border border-line bg-surface/85 p-6 text-center shadow-card">
            <p className="font-display text-lg font-bold">No game rooms open</p>
            <p className="mt-2 text-muted">{venue.name} isn’t running PintRush right now. Check back on game night!</p>
          </div>
        )}
      </div>
    </main>
  );
}
