import { connection } from 'next/server';
import type { ComponentType } from 'react';
import { Backdrop } from '@/components/marketing/Backdrop';
import { HeroStage } from '@/components/marketing/HeroStage';
import { DemoPhone, DemoTv } from '@/components/tv/demo/DemoDevices';
import { Badge } from '@/components/ui/Badge';
import { ButtonLink } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Heading, Kicker, SectionHeader } from '@/components/ui/Heading';
import { ArrowRightIcon, BoltIcon, CheckIcon, ClockIcon, GridIcon, TrophyIcon, TvIcon, UsersIcon } from '@/components/ui/icons';
import type { IconProps } from '@/components/ui/icons';
import { QrCode } from '@/components/ui/QrCode';
import { Container, Section } from '@/components/ui/Section';
import { joinUrl, signTvToken } from '@/lib/server/tokens';
import { pageMetadata, siteUrl } from '@/lib/site';
import { gameServerHealthy } from '@/lib/tv/health';
import { findDemoRoom } from '@/lib/tv/room';

export const metadata = pageMetadata({
  title: 'Live demo',
  description:
    'Play a live round of The Rush against our house bots: the bar TV and a phone side by side, running right now. No app, no sign-up.',
  path: '/demo',
});

const screenGuide: { title: string; body: string; icon: ComponentType<IconProps>; tone: string }[] = [
  {
    title: 'Up next',
    body: 'Each question is teased by its category for a few seconds first. On the phone, that’s the moment to play Double Down or Category Swap.',
    icon: BoltIcon,
    tone: 'border-cyan/40 bg-cyan/10 text-cyan',
  },
  {
    title: 'Countdown ring',
    body: '15 seconds to answer, 20 for hard questions and the wildcard. Correct answers earn up to +50 for speed.',
    icon: ClockIcon,
    tone: 'border-violet/45 bg-violet/15 text-violet-soft',
  },
  {
    title: '“N of M answered”',
    body: 'A live count, never who picked what. When everyone is in, the question locks early.',
    icon: UsersIcon,
    tone: 'border-cyan/40 bg-cyan/10 text-cyan',
  },
  {
    title: 'The reveal',
    body: 'Only after answers lock: the right answer with a check mark, how the room voted, and the three fastest correct answers.',
    icon: CheckIcon,
    tone: 'border-lime/40 bg-lime/10 text-lime',
  },
  {
    title: 'Leaderboard',
    body: 'Scores move at each reveal. Ties go to more correct answers, then the faster total answer time.',
    icon: TrophyIcon,
    tone: 'border-amber/45 bg-amber/10 text-amber',
  },
  {
    title: 'Your board',
    body: 'On the phone, every correct answer lights a category tile. Each line is +250, a full board +500. Question 10 is the wildcard.',
    icon: GridIcon,
    tone: 'border-violet/45 bg-violet/15 text-violet-soft',
  },
];

/**
 * /demo — the public demo bar, live: the real TV display and a real phone, both playing in the demo
 * room where house bots answer around the clock. Rendered per request because it mints a TV link.
 */
export default async function DemoPage() {
  await connection();
  const [demo, healthy] = await Promise.all([findDemoRoom(), gameServerHealthy()]);
  const live = demo !== null && healthy;
  const tvSrc = live ? `/tv/${demo.roomId}?t=${encodeURIComponent(await signTvToken({ roomId: demo.roomId, venueId: demo.venueId, v: demo.tvTokenVersion }))}` : null;
  const phoneSrc = live ? `/join/${encodeURIComponent(demo.joinCode)}?room=${demo.roomId}&embed=1` : null;
  const ownPhoneUrl = live ? joinUrl(siteUrl.toString(), demo.joinCode, demo.roomId) : null;

  return (
    <>
      <section className="relative isolate overflow-hidden border-b border-line/60" aria-labelledby="demo-title">
        <Backdrop intensity="soft" />
        <Container className="flex flex-col items-center gap-5 pt-14 pb-10 text-center sm:pt-20">
          {live ? (
            <Badge tone="lime">
              <span aria-hidden="true" className="size-2 rounded-full bg-lime motion-safe:animate-glow-pulse" />
              Live now · demo bar
            </Badge>
          ) : (
            <Badge tone="neutral">Demo bar on a break</Badge>
          )}
          <Kicker>Live demo</Kicker>
          <Heading as="h1" size="display" id="demo-title" className="max-w-4xl">
            Play a live round. <span className="block text-gradient-brand">The TV runs the show.</span>
          </Heading>
          <p className="max-w-2xl text-lg leading-relaxed text-muted sm:text-xl">
            {live
              ? 'You’re playing live against our house bots. Pick a nickname on the phone and watch the bar TV react to every answer.'
              : 'Our demo bar is taking a quick break, so here’s what a round looks like. Check back in a few minutes to play live against our house bots.'}
          </p>
        </Container>

        <Container className="pb-16 sm:pb-24">
          {live && tvSrc && phoneSrc && ownPhoneUrl ? (
            <div className="grid items-start gap-10 lg:grid-cols-[minmax(0,1fr)_340px] lg:gap-12">
              <figure className="flex min-w-0 flex-col gap-6">
                <DemoTv src={tvSrc} title="Live PintRush TV display in the demo bar" className="w-full" />
                <figcaption className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                  <span className="flex items-center gap-3 text-sm text-muted">
                    <TvIcon className="size-5 text-cyan" />
                    <span>
                      <strong className="font-semibold text-fg">The bar TV.</strong> Read-only; it never shows an answer before the lock.
                    </span>
                  </span>
                  <a
                    href={tvSrc}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex min-h-12 items-center gap-2 self-start rounded-xl px-1 text-sm font-semibold text-cyan-soft underline-offset-4 hover:underline sm:self-auto"
                  >
                    Open the TV full screen
                    <ArrowRightIcon className="size-4" />
                    <span className="sr-only">(opens in a new tab)</span>
                  </a>
                </figcaption>
                <Card tone="default" padding="sm" className="flex items-center gap-5">
                  <QrCode value={ownPhoneUrl} label="QR code to join the PintRush demo bar on your own phone" className="size-28 shrink-0 rounded-lg" />
                  <div className="flex flex-col gap-1.5">
                    <p className="font-display font-semibold text-fg">Prefer your own phone?</p>
                    <p className="text-sm leading-relaxed text-muted">
                      Scan to join the same demo bar, or enter code <span className="font-display font-bold text-amber">{demo.joinCode}</span>. You’ll show up on the TV
                      above.
                    </p>
                  </div>
                </Card>
              </figure>

              <figure className="mx-auto flex w-full max-w-[340px] flex-col gap-4">
                <DemoPhone src={phoneSrc} title="PintRush phone: join the demo bar and play" />
                <figcaption className="flex items-start gap-3 text-sm text-muted">
                  <span aria-hidden="true" className="mt-1 size-2 shrink-0 rounded-full bg-violet" />
                  <span>
                    <strong className="font-semibold text-fg">Your phone.</strong> Pick any nickname and play. No app, no account.
                  </span>
                </figcaption>
              </figure>
            </div>
          ) : (
            <HeroStage className="mx-auto max-w-5xl" />
          )}
        </Container>
      </section>

      <Section spacing="lg" aria-labelledby="guide-title">
        <SectionHeader
          kicker="Reading the screen"
          title="What you’re looking at"
          lead="Everything on the TV is sized to read from across the bar. Here’s what each part means."
          id="guide-title"
        />
        <ul className="mt-12 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          {screenGuide.map(({ title, body, icon: Icon, tone }) => (
            <li key={title}>
              <Card className="flex h-full flex-col gap-4">
                <span className={`grid size-12 place-items-center rounded-2xl border ${tone}`}>
                  <Icon className="size-6" />
                </span>
                <Heading as="h3" size="md">
                  {title}
                </Heading>
                <p className="leading-relaxed text-muted">{body}</p>
              </Card>
            </li>
          ))}
        </ul>
      </Section>

      <Section spacing="md" aria-labelledby="demo-cta-title">
        <div className="relative isolate overflow-hidden rounded-[2rem] border border-violet/45 bg-[linear-gradient(135deg,rgb(106_75_245/0.4),rgb(13_20_51/0.96)_50%,rgb(14_116_144/0.35))] px-6 py-14 shadow-glow-violet sm:px-12 sm:py-16">
          <div aria-hidden="true" className="bg-streaks absolute inset-0 -z-10 opacity-80" />
          <div className="flex max-w-2xl flex-col gap-5">
            <Heading id="demo-cta-title" size="title">
              Want this on the TVs in your bar?
            </Heading>
            <p className="text-lg leading-relaxed text-muted">
              Any TV with a browser becomes the game show; guests play from their phones. We’re setting up a handful of pilot venues on Long Island.
            </p>
            <div className="mt-2 flex flex-col gap-3 sm:flex-row">
              <ButtonLink href="/pilot" size="lg">
                Join the pilot
                <ArrowRightIcon />
              </ButtonLink>
              <ButtonLink href="/how-it-works" size="lg" variant="secondary">
                How it works
              </ButtonLink>
            </div>
          </div>
        </div>
      </Section>
    </>
  );
}
