import type { ComponentType, ReactNode } from 'react';
import { CtaBand } from '@/components/marketing/CtaBand';
import { PhoneFrame, TvFrame } from '@/components/marketing/mocks/Devices';
import { PhoneAnswerScreen, PhoneJoinScreen, PhonePowerUpScreen } from '@/components/marketing/mocks/PhoneScreens';
import { TvAttractScreen, TvRevealScreen } from '@/components/marketing/mocks/TvScreens';
import { PageHero } from '@/components/marketing/PageHero';
import { RushBoard } from '@/components/marketing/RushBoard';
import { Badge } from '@/components/ui/Badge';
import { ButtonLink } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Heading, SectionHeader } from '@/components/ui/Heading';
import { ArrowRightIcon, CheckIcon, ClockIcon, DoubleDownIcon, PlayIcon, SecondChanceIcon, SwapIcon } from '@/components/ui/icons';
import type { IconProps } from '@/components/ui/icons';
import { Section } from '@/components/ui/Section';
import { pageMetadata } from '@/lib/site';

export const metadata = pageMetadata({
  title: 'How it works',
  description:
    'Always-on rounds or a hosted Championship. Learn The Rush: scoring, speed bonus, 3×3 boards, lines, the wildcard, tie-breaks and power-ups that are earned, never sold.',
  path: '/how-it-works',
});

const sectionLinks = [
  { href: '#modes', label: 'Modes' },
  { href: '#rules', label: 'The Rush' },
  { href: '#scoring', label: 'Scoring' },
  { href: '#power-ups', label: 'Power-ups' },
  { href: '#championship', label: 'Championship' },
  { href: '#screens', label: 'Screens' },
];

const modeRows: { label: string; alwaysOn: ReactNode; championship: ReactNode }[] = [
  { label: 'Length', alwaysOn: '3–5 minute rounds, continuous', championship: '45–60 minute scheduled show' },
  { label: 'Host required', alwaysOn: 'No', championship: 'Yes' },
  { label: 'Leaderboard', alwaysOn: 'Nightly', championship: 'Event (separate)' },
  { label: 'Rounds', alwaysOn: 'The Rush, back to back with a 60-second break', championship: 'The Rush, Music Mayhem, Table Wars, Power Round, Final Rush' },
  { label: 'Joining', alwaysOn: 'Any time; late arrivals play from question 3 or the next round', championship: 'Lobby opens before showtime for nicknames and teams' },
  { label: 'Scores', alwaysOn: 'Fresh leaderboard every night', championship: 'Everyone starts at zero' },
];

const scoring: { event: string; points: string; limit: string; tone?: string }[] = [
  { event: 'Correct answer — standard', points: '100', limit: 'Per question' },
  { event: 'Correct answer — difficult', points: '150', limit: 'Per question' },
  { event: 'Speed bonus', points: '0–50', limit: 'Per correct answer', tone: 'text-cyan' },
  { event: 'Line (row, column or diagonal)', points: '250', limit: 'Once per line, 8 possible', tone: 'text-amber' },
  { event: 'Full board', points: '500', limit: 'Once per round', tone: 'text-lime' },
  { event: 'Table challenge win', points: '200', limit: 'Per challenge, normalized for teams' },
  { event: 'Incorrect or no answer', points: '0', limit: '—' },
];

const powerUps: { name: string; icon: ComponentType<IconProps>; when: string; effect: string; note: string; chip: string }[] = [
  {
    name: 'Double Down',
    icon: DoubleDownIcon,
    when: 'Before a question opens',
    effect: 'Bet 100 points on the next question. Get it right for +200 extra; miss it and lose 100.',
    note: 'You need at least 100 points to place the bet.',
    chip: 'bg-amber text-on-bright shadow-glow-amber',
  },
  {
    name: 'Second Chance',
    icon: SecondChanceIcon,
    when: 'While a multiple-choice question is open, before you answer',
    effect: 'One wrong option disappears from your screen, leaving better odds.',
    note: 'Works on multiple-choice questions with three or more options.',
    chip: 'bg-cyan text-on-bright shadow-glow-cyan',
  },
  {
    name: 'Category Swap',
    icon: SwapIcon,
    when: 'Between questions',
    effect: 'Swap the positions of two unlit tiles on your own board to set up a line.',
    note: 'Your nine categories stay the same, so the game stays fair.',
    chip: 'bg-lime text-on-bright shadow-glow-lime',
  },
];

const runOfShow: { time: string; title: string; body: string; badge?: string }[] = [
  { time: '0–5 min', title: 'Doors open', body: 'Guests join, pick nicknames and form teams while the countdown runs.' },
  { time: '5–15 min', title: 'The Rush', body: 'The signature game: standard questions, boards and lines.' },
  {
    time: '15–25 min',
    title: 'Music Mayhem',
    body: 'Song and artist questions — original or properly licensed only, never reproduced lyrics.',
  },
  { time: '25–35 min', title: 'Table Wars', body: 'Tables battle question by question. Team scores are averaged, so table size doesn’t decide it.' },
  { time: '35–45 min', title: 'Power Round', body: 'Boards return and power-ups take the spotlight.', badge: 'Power-ups' },
  {
    time: '45–50 min',
    title: 'Final Rush',
    body: 'The top five play five final questions for the crown. Everyone else predicts the winner in a just-for-fun side game.',
    badge: 'Finale',
  },
];

const roundFlow = [
  { title: 'Intro', body: 'Everyone gets a board with all nine categories.' },
  { title: '9 category questions', body: 'One per category, 15 seconds each (20 for harder ones).' },
  { title: 'Q10 · Wildcard', body: 'Get it right and light any tile you choose.' },
  { title: 'Results', body: 'Lines, full boards and the leaderboard on the TV.' },
];

export default function HowItWorksPage() {
  return (
    <>
      <PageHero
        kicker="How it works"
        title={
          <>
            Two ways to play. <span className="text-gradient-brand">One signature game.</span>
          </>
        }
        lead="PintRush runs on your TVs and your guests’ phones. Here’s everything about the modes, The Rush, scoring and power-ups — in plain words."
      >
        <ButtonLink href="/demo" size="lg">
          <PlayIcon /> Try the live demo
        </ButtonLink>
        <ButtonLink href="/pilot" size="lg" variant="secondary">
          Join the pilot
        </ButtonLink>
      </PageHero>

      <nav aria-label="On this page" className="glass sticky top-16 z-30 border-b border-line/60 lg:top-[4.5rem]">
        <ul className="container-page flex gap-1 overflow-x-auto py-2 [scrollbar-width:none]">
          {sectionLinks.map((link) => (
            <li key={link.href} className="shrink-0">
              <a
                href={link.href}
                className="inline-flex min-h-11 items-center rounded-lg px-3.5 text-sm font-semibold text-muted transition-colors hover:bg-white/[0.05] hover:text-fg"
              >
                {link.label}
              </a>
            </li>
          ))}
        </ul>
      </nav>

      {/* ───────────── Modes ───────────── */}
      <Section id="modes" spacing="lg" aria-labelledby="modes-title" className="scroll-mt-32">
        <SectionHeader
          kicker="Modes"
          title="Always-on vs Championship"
          lead="Run games quietly in the background every night, schedule a big hosted show, or both. A Championship pauses Always-on while it runs."
          id="modes-title"
        />
        <div className="mt-10 overflow-hidden rounded-card border border-line bg-surface/70">
          <table className="w-full border-collapse text-left text-sm sm:text-base">
            <caption className="sr-only">Always-on and Championship modes compared</caption>
            <thead>
              <tr className="border-b border-line">
                <th scope="col" className="w-[24%] px-3 py-4 sm:px-5 text-sm font-semibold text-subtle">
                  <span className="sr-only">Feature</span>
                </th>
                <th scope="col" className="px-3 py-4 sm:px-5">
                  <span className="flex flex-wrap items-center gap-2 font-display text-base font-bold sm:text-lg">
                    Always-on <Badge tone="cyan">No host</Badge>
                  </span>
                </th>
                <th scope="col" className="px-3 py-4 sm:px-5">
                  <span className="flex flex-wrap items-center gap-2 font-display text-base font-bold sm:text-lg">
                    Championship <Badge tone="amber">Hosted</Badge>
                  </span>
                </th>
              </tr>
            </thead>
            <tbody>
              {modeRows.map((row) => (
                <tr key={row.label} className="border-b border-line/60 last:border-0">
                  <th scope="row" className="px-3 py-4 sm:px-5 align-top text-sm font-semibold text-muted">
                    {row.label}
                  </th>
                  <td className="px-3 py-4 sm:px-5 align-top text-fg">{row.alwaysOn}</td>
                  <td className="px-3 py-4 sm:px-5 align-top text-fg">{row.championship}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Section>

      {/* ───────────── The Rush ───────────── */}
      <Section id="rules" tone="band" spacing="lg" aria-labelledby="rules-title" className="scroll-mt-32">
        <div className="grid gap-14 lg:grid-cols-[1.15fr_1fr] lg:items-center lg:gap-20">
          <div className="flex flex-col gap-8">
            <SectionHeader
              kicker="The Rush"
              kickerTone="violet"
              title="Light tiles. Complete lines. Fill the board."
              lead="Each round is ten questions on a 3×3 board. Nine questions match your nine category tiles; the tenth is a wildcard."
              id="rules-title"
            />
            <ul className="flex flex-col gap-4">
              {[
                'Your board holds all nine categories, once each.',
                'Answer a question correctly and that category’s tile lights up.',
                'Eight lines to chase: three rows, three columns and two diagonals — 250 points each.',
                'Q10 is the Wildcard: get it right and light any unlit tile you choose. Nine correct answers out of ten is a full board.',
                'Fair by design: every board in a round is a rotation or mirror image of the same layout, so nobody is dealt an easier board.',
              ].map((item) => (
                <li key={item} className="flex gap-3 leading-relaxed text-fg">
                  <CheckIcon className="mt-1 size-5 shrink-0 text-violet-soft" />
                  {item}
                </li>
              ))}
            </ul>
          </div>
          <RushBoard className="mx-auto w-full max-w-sm" />
        </div>
        <ol className="mt-16 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {roundFlow.map((step, index) => (
            <li key={step.title}>
              <Card className="flex h-full flex-col gap-2" padding="md">
                <span className="num font-display text-sm font-bold text-cyan">Step {index + 1}</span>
                <h3 className="font-display text-lg font-bold">{step.title}</h3>
                <p className="text-sm leading-relaxed text-muted">{step.body}</p>
              </Card>
            </li>
          ))}
        </ol>
      </Section>

      {/* ───────────── Scoring ───────────── */}
      <Section id="scoring" spacing="lg" aria-labelledby="scoring-title" className="scroll-mt-32">
        <SectionHeader kicker="Scoring" title="Every point, explained" id="scoring-title" />
        <div className="mt-10 grid gap-8 lg:grid-cols-[1.4fr_1fr]">
          <div className="overflow-hidden rounded-card border border-line bg-surface/70">
            <table className="w-full border-collapse text-left text-sm sm:text-base">
              <caption className="sr-only">Points awarded in The Rush</caption>
              <thead>
                <tr className="border-b border-line text-xs tracking-[0.14em] text-subtle uppercase">
                  <th scope="col" className="px-3 py-4 sm:px-5 font-semibold">
                    Event
                  </th>
                  <th scope="col" className="px-3 py-4 sm:px-5 text-right font-semibold">
                    Points
                  </th>
                  <th scope="col" className="px-3 py-4 sm:px-5 font-semibold">
                    Limit
                  </th>
                </tr>
              </thead>
              <tbody>
                {scoring.map((row) => (
                  <tr key={row.event} className="border-b border-line/60 last:border-0">
                    <th scope="row" className="px-3 py-4 sm:px-5 font-medium text-fg">
                      {row.event}
                    </th>
                    <td className={`num px-3 py-4 sm:px-5 text-right font-display text-lg font-bold ${row.tone ?? 'text-fg'}`}>{row.points}</td>
                    <td className="px-3 py-4 sm:px-5 text-sm text-muted">{row.limit}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="flex flex-col gap-5">
            <Card tone="raised" className="flex flex-col gap-3">
              <span className="flex items-center gap-2 font-display font-bold text-cyan">
                <ClockIcon className="size-5" /> The speed bonus, in plain words
              </span>
              <p className="leading-relaxed text-muted">
                Answer correctly within the first <strong className="text-fg">¾ of a second</strong> and you get the full 50. After that, the bonus
                shrinks steadily and reaches zero as the clock runs out.
              </p>
              <p className="leading-relaxed text-muted">
                Example: a correct answer halfway through a 15-second question earns about <strong className="text-fg">26 bonus points</strong>.
              </p>
              <p className="leading-relaxed text-muted">
                Time is measured by our server when your answer arrives — never by your phone — so everyone plays against the same clock.
              </p>
            </Card>
            <Card className="flex flex-col gap-3">
              <h3 className="font-display font-bold">Tie-breaks (shown on the TV)</h3>
              <ol className="flex flex-col gap-2 text-muted">
                {['More total points', 'More correct answers', 'Less total time on correct answers', 'Earlier final correct answer'].map((item, index) => (
                  <li key={item} className="flex items-center gap-3">
                    <span className="num grid size-7 shrink-0 place-items-center rounded-lg bg-raised font-display text-sm font-bold text-fg">
                      {index + 1}
                    </span>
                    {item}
                  </li>
                ))}
              </ol>
            </Card>
          </div>
        </div>
        <Card className="mt-8 grid gap-6 md:grid-cols-2" padding="lg">
          <div className="flex flex-col gap-2">
            <h3 className="font-display text-lg font-bold">Teams</h3>
            <p className="leading-relaxed text-muted">
              A team’s score is the average of its members who answered at least once, so a big table has no built-in edge. Solo players and
              teams of one rank on a separate Solo board, unless the host merges everyone.
            </p>
          </div>
          <div className="flex flex-col gap-2">
            <h3 className="font-display text-lg font-bold">Table Wars</h3>
            <p className="leading-relaxed text-muted">
              Every question is a challenge: the table with the highest share of correct answers wins (ties go to the faster table), and each
              member who played gets +200.
            </p>
          </div>
        </Card>
      </Section>

      {/* ───────────── Power-ups ───────────── */}
      <Section id="power-ups" tone="band" spacing="lg" aria-labelledby="powerups-title" className="scroll-mt-32">
        <SectionHeader
          kicker="Power-ups"
          kickerTone="amber"
          title="Earned by completing a line. Never sold."
          lead="Every completed line earns a token. Spend it on any power-up you haven’t used yet in this event — a Championship, or one Always-on night. That’s one use of each, three at most."
          id="powerups-title"
        />
        <ul className="mt-12 grid gap-5 lg:grid-cols-3">
          {powerUps.map(({ name, icon: Icon, when, effect, note, chip }) => (
            <li key={name}>
              <Card tone="raised" padding="lg" className="flex h-full flex-col gap-5">
                <div className="flex items-center gap-4">
                  <span className={`grid size-14 place-items-center rounded-2xl ${chip}`}>
                    <Icon className="size-7" />
                  </span>
                  <Heading as="h3" size="lg">
                    {name}
                  </Heading>
                </div>
                <dl className="flex flex-col gap-4">
                  <div className="flex flex-col gap-1">
                    <dt className="text-xs font-bold tracking-[0.16em] text-subtle uppercase">When</dt>
                    <dd className="text-fg">{when}</dd>
                  </div>
                  <div className="flex flex-col gap-1">
                    <dt className="text-xs font-bold tracking-[0.16em] text-subtle uppercase">Effect</dt>
                    <dd className="text-fg">{effect}</dd>
                  </div>
                </dl>
                <p className="mt-auto border-t border-line/70 pt-4 text-sm text-muted">{note}</p>
              </Card>
            </li>
          ))}
        </ul>
      </Section>

      {/* ───────────── Championship ───────────── */}
      <Section id="championship" spacing="lg" aria-labelledby="championship-title" className="scroll-mt-32">
        <div className="grid gap-12 lg:grid-cols-[1fr_1.3fr] lg:gap-20">
          <div className="flex flex-col gap-6 lg:sticky lg:top-40 lg:self-start">
            <SectionHeader
              kicker="Championship"
              title="A 50-minute show, minute by minute"
              lead="The default run of show for a hosted Championship. Scores start at zero for everyone; Always-on progress gives no head start."
              id="championship-title"
            />
            <ButtonLink href="/for-venues" variant="secondary" className="self-start">
              Hosting a Championship <ArrowRightIcon />
            </ButtonLink>
          </div>
          <ol className="relative flex flex-col gap-4 before:absolute before:top-4 before:bottom-4 before:left-[1.1rem] before:w-px before:bg-[linear-gradient(180deg,var(--color-cyan),var(--color-violet),var(--color-amber))] sm:before:left-[1.35rem]">
            {runOfShow.map((segment) => (
              <li key={segment.title} className="relative flex gap-5 pl-0">
                <span
                  aria-hidden="true"
                  className="relative z-10 mt-5 grid size-9 shrink-0 place-items-center rounded-full border-2 border-violet bg-night sm:size-11"
                >
                  <span className="size-2.5 rounded-full bg-violet-soft" />
                </span>
                <Card className="flex flex-1 flex-col gap-2" padding="md">
                  <div className="flex flex-wrap items-center gap-3">
                    <span className="num font-display text-sm font-bold text-cyan">{segment.time}</span>
                    {segment.badge && <Badge tone="amber">{segment.badge}</Badge>}
                  </div>
                  <h3 className="font-display text-xl font-bold">{segment.title}</h3>
                  <p className="leading-relaxed text-muted">{segment.body}</p>
                </Card>
              </li>
            ))}
          </ol>
        </div>
      </Section>

      {/* ───────────── Screens ───────────── */}
      <Section id="screens" tone="band" spacing="lg" aria-labelledby="screens-title" className="scroll-mt-32">
        <SectionHeader
          kicker="Screens"
          title="What everyone sees"
          lead="The TV is built to be read from across the room. The phone is built for one thumb."
          id="screens-title"
        />
        <h3 className="mt-14 mb-6 font-display text-xl font-bold">On the TV</h3>
        <div className="grid gap-10 lg:grid-cols-2">
          <figure className="flex flex-col gap-4">
            <TvFrame>
              <div aria-hidden="true">
                <TvAttractScreen />
              </div>
            </TvFrame>
            <figcaption className="text-sm text-muted">
              <strong className="text-fg">Between rounds:</strong> a big QR code, the next-round timer, tonight’s top 10 and the next Championship.
            </figcaption>
          </figure>
          <figure className="flex flex-col gap-4">
            <TvFrame>
              <div aria-hidden="true">
                <TvRevealScreen />
              </div>
            </TvFrame>
            <figcaption className="text-sm text-muted">
              <strong className="text-fg">The reveal:</strong> answers are locked before anything is shown, then the room sees the split and the
              fastest correct answers.
            </figcaption>
          </figure>
        </div>
        <h3 className="mt-16 mb-6 font-display text-xl font-bold">On every phone</h3>
        <div className="grid gap-10 sm:grid-cols-3">
          {[
            { screen: <PhoneJoinScreen />, title: 'Join', body: 'Scan, choose a nickname, optionally pick a team.' },
            { screen: <PhoneAnswerScreen />, title: 'Play', body: 'Board up top, big answer buttons in the thumb zone.' },
            { screen: <PhonePowerUpScreen />, title: 'Power up', body: 'Lines earn tokens. Each power-up once per event.' },
          ].map((item) => (
            <figure key={item.title} className="flex flex-col items-center gap-4">
              <PhoneFrame className="w-full max-w-[16rem]">
                <div aria-hidden="true">{item.screen}</div>
              </PhoneFrame>
              <figcaption className="text-center text-sm text-muted">
                <strong className="text-fg">{item.title}:</strong> {item.body}
              </figcaption>
            </figure>
          ))}
        </div>
      </Section>

      <CtaBand title="See it on a real TV." lead="Open the live demo on a big screen, scan the QR with your phone and play a round against our bots." />
    </>
  );
}
