/* eslint-disable @next/next/no-img-element */
'use client';

import {
  type MouseEvent,
  type ReactNode,
  createContext,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react';

import { motion } from 'framer-motion';
import { ChevronUp, Info } from 'lucide-react';

import Section, { type SectionSurface, useSectionTone } from '@/components/common/Section';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Heading, Text } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import { buildMediaUrl } from '@/utils/images';

import { Link } from '@/i18n/navigation';

import MosaicPicture from './MosaicPicture';
import { formatNumber } from './charts';

/*
 * The building blocks of the story page. Every block type has one job, and the page alternates
 * them, so two neighbouring blocks never look the same:
 *   BigNumber    – one number over a mosaic of pictures, between parts
 *   GuessReveal  – the reader guesses first, then the answer and its view appear
 *   Scrolly      – the view stands still, the text moves past it step by step
 *   StoryBlock   – a title, a lead and a view, side by side or stacked
 *   Pictures     – creations as the view itself
 */

export type Picture = {
  id: string;
  title: string;
  year: number | null;
  image: number;
  creator?: string | null;
};

/** True once the element has come into view (or near it, with a margin). */
export function useInView<T extends Element>(rootMargin = '0px') {
  const ref = useRef<T>(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (!entry.isIntersecting) return;
        setInView(true);
        observer.disconnect();
      },
      { rootMargin }
    );
    observer.observe(element);
    return () => observer.disconnect();
  }, [rootMargin]);
  return [ref, inView] as const;
}

const COUNT_MS = 1400;

/**
 * A number that counts up when it comes into view. The server renders the final value; the count
 * only replays for numbers still below the screen, and never with reduced motion.
 * `onLoad` is for the first screen: the count starts from 0 on the server too (no flash of the
 * final value), runs as soon as the page is ready, after `delay` ms. `duration`: how long it
 * counts, in ms.
 */
export function CountUp({
  value,
  onLoad = false,
  delay = 0,
  duration = COUNT_MS,
  className,
}: {
  value: number;
  onLoad?: boolean;
  delay?: number;
  duration?: number;
  className?: string;
}) {
  const ref = useRef<HTMLSpanElement>(null);
  const [shown, setShown] = useState(onLoad ? 0 : value);
  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setShown(value);
      return;
    }
    let frame = 0;
    let timer = 0;
    const run = () => {
      const start = performance.now();
      const tick = (now: number) => {
        const progress = Math.min(1, (now - start) / duration);
        setShown(Math.round(value * (1 - (1 - progress) ** 3)));
        if (progress < 1) frame = requestAnimationFrame(tick);
      };
      frame = requestAnimationFrame(tick);
    };
    if (onLoad) {
      timer = window.setTimeout(run, delay);
      return () => {
        window.clearTimeout(timer);
        cancelAnimationFrame(frame);
      };
    }
    if (element.getBoundingClientRect().top < window.innerHeight) return;
    setShown(0);
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (!entry.isIntersecting) return;
        observer.disconnect();
        run();
      },
      { threshold: 0.6 }
    );
    observer.observe(element);
    return () => {
      observer.disconnect();
      cancelAnimationFrame(frame);
    };
  }, [value, onLoad, delay, duration]);
  // The final value is reserved (invisible) under the count, so the layout never jumps, and it
  // is what screen readers hear.
  return (
    <span ref={ref} className={cn('inline-grid tabular-nums', className)}>
      <span className="sr-only">{formatNumber(value)}</span>
      <span aria-hidden className="invisible col-start-1 row-start-1">
        {formatNumber(value)}
      </span>
      <span aria-hidden className="col-start-1 row-start-1">
        {formatNumber(shown)}
      </span>
    </span>
  );
}

/** Fades and lifts its content in once, when it scrolls into view. */
export function Reveal({
  children,
  className,
  delay = 0,
}: {
  children: ReactNode;
  className?: string;
  delay?: number;
}) {
  return (
    <motion.div
      className={className}
      initial={{ opacity: 0, y: 24 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: '-80px' }}
      transition={{ duration: 0.6, delay, ease: 'easeOut' }}
    >
      {children}
    </motion.div>
  );
}

/** Text tones that follow the surface: ink on light parts, white on dark ones. */
function useTones() {
  const dark = useSectionTone() === 'dark';
  return {
    dark,
    muted: dark ? ('inverseMuted' as const) : ('muted' as const),
    soft: dark ? ('inverseMuted' as const) : ('soft' as const),
  };
}

/** The number of creators in the database, for the note on the data under every part title. */
const CreatorTotal = createContext<number | null>(null);

export function CreatorTotalProvider({
  value,
  children,
}: {
  value: number | null;
  children: ReactNode;
}) {
  return <CreatorTotal value={value}>{children}</CreatorTotal>;
}

/**
 * One part of the story on its own surface. The parts' titles feed the progress button,
 * so each part carries its title on the element.
 */
export function StoryPart({
  id,
  number,
  total,
  title,
  lead,
  surface = 'paper',
  children,
}: {
  id: string;
  number: number;
  total: number;
  title: string;
  lead?: ReactNode;
  surface?: SectionSurface;
  children: ReactNode;
}) {
  return (
    <Section
      id={id}
      surface={surface}
      spacing="roomy"
      gap="loose"
      className="scroll-mt-[var(--header-h)]"
    >
      <PartHeader number={number} total={total} title={title} lead={lead} />
      {children}
    </Section>
  );
}

function PartHeader({
  number,
  total,
  title,
  lead,
}: {
  number: number;
  total: number;
  title: string;
  lead?: ReactNode;
}) {
  const { dark, muted, soft } = useTones();
  const creators = useContext(CreatorTotal);
  return (
    <Reveal className="max-w-3xl">
      <Text variant="eyebrow" tone={soft}>
        {String(number).padStart(2, '0')} / {String(total).padStart(2, '0')}
      </Text>
      <div className="mt-3 flex items-start gap-1">
        <Heading as="h2" variant="sectionTitle" className="min-w-0">
          {title}
        </Heading>
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              inverted={dark}
              className="size-8 shrink-0"
              aria-label="Tudnivaló az adatokról"
            >
              <Info aria-hidden />
            </Button>
          </PopoverTrigger>
          <PopoverContent aria-label="Tudnivaló az adatokról">
            <Text variant="bodySm">
              Az <span className="whitespace-nowrap">A–Z OPUS</span> adatbázis kizárólag a benne
              foglalt {creators ? `${formatNumber(creators)} ` : ''}kortárs művész adataira
              támaszkodik. A közölt adatok, elemzések erre figyelemmel értelmezhetők.
            </Text>
          </PopoverContent>
        </Popover>
      </div>
      {lead ? (
        <Text variant="lead" tone={muted} className="mt-5">
          {lead}
        </Text>
      ) : null}
    </Reveal>
  );
}

export type StoryChapter = {
  title: string;
  /** `game`: the part has one of the games (Mikor készült?, Hol készült?), marked in the contents. */
  parts: { id: string; number: number; title: string; game?: boolean }[];
};

/**
 * The table of contents of the opening, on its dark surface: the chapters and their parts. The
 * chapters have no block of their own on the page, so a chapter's link leads to its first part.
 */
export function StoryContents({
  chapters,
  className,
}: {
  chapters: StoryChapter[];
  className?: string;
}) {
  return (
    <nav aria-label="Tartalomjegyzék" className={className}>
      <ol className="space-y-5 border-l-2 border-[#dfcf6f] pl-5">
        {chapters.map((chapter, index) => (
          <li key={chapter.title}>
            <a
              href={`#${chapter.parts[0].id}`}
              className="font-slab text-lg font-bold leading-snug hover:underline"
            >
              {index + 1}. {chapter.title}
            </a>
            <ol className="mt-2 space-y-1">
              {chapter.parts.map((part) => (
                <li key={part.id}>
                  <a
                    href={`#${part.id}`}
                    className="flex gap-2 text-sm text-white/80 hover:text-white hover:underline"
                  >
                    <span className="tabular-nums text-white/60">
                      {String(part.number).padStart(2, '0')}
                    </span>
                    <span>
                      {part.title}
                      {part.game ? (
                        <span className="ml-1.5 inline-flex items-center gap-1 whitespace-nowrap font-bold text-[#dfcf6f]">
                          (játék)
                        </span>
                      ) : null}
                    </span>
                  </a>
                </li>
              ))}
            </ol>
          </li>
        ))}
      </ol>
    </nav>
  );
}

const CONTINUE_LINKS = [
  { href: '/alkotasok', label: 'Alkotások' },
  { href: '/alkotok', label: 'Alkotók' },
  { href: '/videok', label: 'Videók' },
  { href: '/programok', label: 'Programnaptár' },
] as const;

/** The end of the story: where the reader can go on in the database. */
export function ContinueStrip() {
  return (
    <Section surface="paper" spacing="compact">
      <div className="flex flex-col items-center gap-5 text-center">
        <p className="font-slab text-xl font-bold leading-snug text-[#151720] sm:text-2xl">
          A felfedezés még nem ért véget, itt folytathatja:
        </p>
        <ul className="flex flex-wrap justify-center gap-3">
          {CONTINUE_LINKS.map((item) => (
            <li key={item.href}>
              <Button asChild variant="outline">
                <Link href={item.href}>{item.label}</Link>
              </Button>
            </li>
          ))}
        </ul>
      </div>
    </Section>
  );
}

/** The sentence that leads from one part to the next. */
export function Bridge({ children }: { children: ReactNode }) {
  return (
    <Section surface="white" spacing="default">
      <Reveal>
        <p className="mx-auto max-w-3xl text-center font-slab text-2xl font-bold leading-snug text-[#151720] sm:text-4xl">
          {children}
        </p>
      </Reveal>
    </Section>
  );
}

/**
 * One big number across the screen. Over the mosaic of pictures, which fades in (dark), or on its
 * own, on the light page.
 */
export function BigNumber({
  value,
  label,
  mosaic = false,
  children,
}: {
  value: number;
  label: string;
  mosaic?: boolean;
  children?: ReactNode;
}) {
  const [ref, inView] = useInView<HTMLDivElement>('200px');

  if (!mosaic) {
    return (
      <Section surface="paper" spacing="roomy">
        <div className="relative py-10 text-center lg:py-20">
          <div className="font-slab text-6xl font-bold leading-none sm:text-8xl lg:text-[9rem]">
            <CountUp value={value} />
          </div>
          <Text variant="eyebrow" tone="muted" className="mt-5">
            {label}
          </Text>
          {children ? (
            <Text variant="lead" tone="muted" className="mx-auto mt-6 max-w-2xl">
              {children}
            </Text>
          ) : null}
        </div>
      </Section>
    );
  }

  return (
    <Section
      surface="ink"
      spacing="roomy"
      clip
      backdrop={
        <div ref={ref} aria-hidden className="absolute inset-0">
          {inView ? (
            <motion.div
              className="absolute inset-0"
              initial={{ opacity: 0 }}
              animate={{ opacity: 0.35 }}
              transition={{ duration: 0.8 }}
            >
              <MosaicPicture className="grayscale" />
            </motion.div>
          ) : null}
          <div className="absolute inset-0 bg-gradient-to-b from-[#151720]/40 via-[#151720]/75 to-[#151720]" />
        </div>
      }
    >
      <div className="relative py-10 text-center lg:py-20">
        <div className="font-slab text-6xl font-bold leading-none sm:text-8xl lg:text-[9rem]">
          <CountUp value={value} />
        </div>
        <Text variant="eyebrow" tone="accent" className="mt-5">
          {label}
        </Text>
        {children ? (
          <Text variant="lead" tone="inverseMuted" className="mx-auto mt-6 max-w-2xl">
            {children}
          </Text>
        ) : null}
      </div>
    </Section>
  );
}

/**
 * A titled view. "split": text beside the view (flip puts the text on the right);
 * "stack": text above, the view across the full width.
 */
export function StoryBlock({
  title,
  lead,
  look,
  layout = 'split',
  flip = false,
  framed,
  children,
}: {
  title: ReactNode;
  lead?: ReactNode;
  /** What to look for in the view; marked in yellow, read before the view. */
  look?: ReactNode;
  layout?: 'split' | 'stack';
  flip?: boolean;
  /** A white frame around the view; the default on dark parts, where the charts need it. */
  framed?: boolean;
  children: ReactNode;
}) {
  const { dark, muted } = useTones();
  const frame = framed ?? dark;
  return (
    <article
      className={cn(
        'grid gap-8',
        layout === 'split' && 'lg:grid-cols-12 lg:items-center lg:gap-14'
      )}
    >
      <Reveal
        className={cn(
          layout === 'split' ? 'lg:col-span-5' : 'max-w-3xl',
          layout === 'split' && flip && 'lg:order-2'
        )}
      >
        <h3 className="font-slab text-2xl font-bold leading-tight sm:text-3xl lg:text-4xl">
          {title}
        </h3>
        {lead ? (
          <Text tone={muted} className="mt-4">
            {lead}
          </Text>
        ) : null}
        {look ? (
          <Text
            variant="bodySm"
            className={cn(
              'mt-5 border-l-4 border-[#dfcf6f] pl-3 font-semibold',
              dark && 'text-white'
            )}
          >
            {look}
          </Text>
        ) : null}
      </Reveal>
      <Reveal
        delay={0.1}
        className={cn(
          'min-w-0',
          layout === 'split' && 'lg:col-span-7',
          frame && 'bg-white p-4 text-[#151720] sm:p-6'
        )}
      >
        {children}
      </Reveal>
    </article>
  );
}

type RangeGuess = {
  kind: 'range';
  min: number;
  max: number;
  step?: number;
  initial: number;
  unit: string;
};
type ChoiceGuess = {
  kind: 'choice';
  options: string[];
};

/**
 * The reader guesses first (a slider or a few options), then the verdict and the view appear.
 * "Tipp nélkül" opens the answer straight away.
 */
export function GuessReveal({
  question,
  guess,
  verdict,
  children,
}: {
  question: string;
  guess: RangeGuess | ChoiceGuess;
  /** The answer's headline, for the guess (null when the reader skipped guessing). */
  verdict: (value: number | string | null) => ReactNode;
  children: ReactNode;
}) {
  const [value, setValue] = useState<number>(guess.kind === 'range' ? guess.initial : 0);
  const [answer, setAnswer] = useState<{ value: number | string | null } | null>(null);
  return (
    <div className="grid gap-8">
      <Reveal className="mx-auto w-full max-w-3xl border-2 border-[#151720] bg-white p-6 sm:p-10">
        <Text variant="eyebrow" tone="soft">
          Tippeljen!
        </Text>
        <p className="mt-3 font-slab text-2xl font-bold leading-tight text-[#151720] sm:text-3xl">
          {question}
        </p>
        {answer ? (
          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            className="mt-6 text-lg text-[#151720]"
          >
            {verdict(answer.value)}
          </motion.div>
        ) : guess.kind === 'range' ? (
          <div className="mt-8">
            <div className="font-slab text-5xl font-bold tabular-nums text-[#151720]">
              {value}
              <span className="ml-1 text-2xl">{guess.unit}</span>
            </div>
            {/* The project has no slider component; the native range input carries the keyboard support. */}
            <input
              type="range"
              min={guess.min}
              max={guess.max}
              step={guess.step ?? 1}
              value={value}
              onChange={(event) => setValue(Number(event.target.value))}
              aria-label={question}
              className="mt-4 w-full accent-[#151720]"
            />
            <div className="flex justify-between text-xs tabular-nums text-[#151720]/55">
              <span>
                {guess.min}
                {guess.unit}
              </span>
              <span>
                {guess.max}
                {guess.unit}
              </span>
            </div>
          </div>
        ) : (
          <div className="mt-8 grid grid-cols-2 gap-2 sm:grid-cols-4">
            {guess.options.map((option) => (
              <Button
                key={option}
                variant="outline"
                size="control"
                onClick={() => setAnswer({ value: option })}
              >
                {option}
              </Button>
            ))}
          </div>
        )}
        {answer ? null : (
          <div className="mt-8 flex flex-wrap items-center gap-4">
            {guess.kind === 'range' ? (
              <Button onClick={() => setAnswer({ value })}>Megnézem a választ</Button>
            ) : null}
            <Button variant="link" onClick={() => setAnswer({ value: null })}>
              Tipp nélkül mutassa
            </Button>
          </div>
        )}
      </Reveal>
      {answer ? (
        <motion.div initial={{ opacity: 0, y: 24 }} animate={{ opacity: 1, y: 0 }}>
          {children}
        </motion.div>
      ) : null}
    </div>
  );
}

/**
 * Scrollytelling: the view stays in place while the steps scroll past; the step in the middle
 * of the screen decides what the view shows. On phones the view sticks to the top.
 */
export function Scrolly({
  steps,
  children,
}: {
  steps: ReactNode[];
  children: (active: number) => ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(0);
  useEffect(() => {
    const elements = [...(box.current?.querySelectorAll<HTMLElement>('[data-step]') ?? [])];
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) setActive(Number((entry.target as HTMLElement).dataset.step));
        }
      },
      { rootMargin: '-55% 0px -45% 0px' }
    );
    elements.forEach((element) => observer.observe(element));
    return () => observer.disconnect();
  }, []);
  return (
    <div ref={box} className="grid lg:grid-cols-12 lg:gap-14">
      <div className="sticky top-[var(--header-h)] z-10 self-start bg-surface-paper py-3 lg:order-2 lg:col-span-7 lg:flex lg:h-[calc(100vh-var(--header-h))] lg:items-center lg:bg-transparent lg:py-0">
        <div className="w-full">{children(active)}</div>
      </div>
      <div className="lg:col-span-5">
        {steps.map((step, index) => (
          <div
            key={index}
            data-step={index}
            className="flex min-h-[70vh] items-center first:pt-[10vh] last:min-h-[90vh]"
          >
            <div
              className={cn(
                'border-l-4 bg-white p-5 text-[#151720] shadow-sm transition-all duration-500 sm:p-6',
                index === active ? 'border-[#dfcf6f] opacity-100' : 'border-transparent opacity-40'
              )}
            >
              {step}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/** Creations as linked pictures, with the title and the creator under each one. */
export function Pictures({
  items,
  className,
  size = 'w256',
}: {
  items: Picture[];
  className?: string;
  size?: 'w256' | 'w640';
}) {
  const { muted } = useTones();
  return (
    <ul className={cn('grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6', className)}>
      {items.map((item) => (
        <li key={item.id} className="min-w-0">
          <Link
            href={{ pathname: '/alkotas/[id]', params: { id: item.id } }}
            className="group block"
          >
            <span className="block overflow-hidden">
              <img
                src={buildMediaUrl(item.image, size)}
                alt=""
                loading="lazy"
                className="aspect-[4/5] w-full object-cover transition-transform duration-500 group-hover:scale-105"
              />
            </span>
            <Text variant="bodySm" className="mt-2 truncate font-semibold group-hover:underline">
              {item.title}
            </Text>
            <Text variant="caption" tone={muted} className="truncate">
              {[item.creator, item.year].filter(Boolean).join(', ')}
            </Text>
          </Link>
        </li>
      ))}
    </ul>
  );
}

// A creation's or a creator's own page, in either language.
const DETAIL_PATH = /^\/(?:en\/)?(?:alkotas|alkoto|creation|creator)\//;

/**
 * For the page's root, in the capture phase: links to a creation or a creator open in a new tab,
 * so the reader keeps their place in the story. It covers the shared cards and the games' layers
 * too (React events pass through portals), and the browser opens the tab itself: Next's link
 * leaves a click with a target to the browser.
 */
export function openDetailsInNewTab(event: MouseEvent<HTMLElement>) {
  const link = (event.target as Element).closest?.('a[href]');
  if (
    link instanceof HTMLAnchorElement &&
    link.origin === window.location.origin &&
    DETAIL_PATH.test(link.pathname)
  )
    link.target = '_blank';
}

/**
 * The note on the data, kept on screen at the bottom: the numbers show what the database holds
 * so far, not whole oeuvres. It appears once the opening's own note (`after`, an element id) has
 * scrolled away. Sticky at the end of the page: at the bottom of the screen while reading, and at
 * rest above the site footer at the end. A yellow fill shows reading progress. Phones get
 * a compact summary that opens the full explanation, keeping the reading area clear.
 */
export function DataNote({
  after,
  children,
  short,
}: {
  after: string;
  /** The full note, from the small breakpoint up. */
  children: ReactNode;
  /** A shorter note for phones. */
  short: ReactNode;
}) {
  const progress = useRef<HTMLDivElement>(null);
  const [past, setPast] = useState(false);
  // Straight on the element, once a frame at most: no render on every scroll step.
  useEffect(() => {
    const footer = document.querySelector('footer');
    let frame = 0;
    const update = () => {
      frame = 0;
      const end =
        (footer
          ? footer.getBoundingClientRect().top + window.scrollY
          : document.body.scrollHeight) - window.innerHeight;
      const share = end > 0 ? Math.min(1, Math.max(0, window.scrollY / end)) : 0;
      if (progress.current) progress.current.style.width = `${share * 100}%`;
    };
    const schedule = () => {
      if (!frame) frame = requestAnimationFrame(update);
    };
    update();
    window.addEventListener('scroll', schedule, { passive: true });
    window.addEventListener('resize', schedule);
    return () => {
      cancelAnimationFrame(frame);
      window.removeEventListener('scroll', schedule);
      window.removeEventListener('resize', schedule);
    };
  }, []);
  useEffect(() => {
    const opening = document.getElementById(after);
    if (!opening) return;
    const observer = new IntersectionObserver(([entry]) =>
      setPast(!entry.isIntersecting && entry.boundingClientRect.top < 0)
    );
    observer.observe(opening);
    return () => observer.disconnect();
  }, [after]);
  const shown = past;
  return (
    <div
      aria-hidden={!shown}
      inert={!shown}
      className={cn(
        // Reserve space for the back-to-top button from the small breakpoint up.
        'sticky bottom-0 z-40 border-t border-[#151720]/15 bg-surface-paper pl-4 pr-4 pt-1 text-[#151720] transition-transform duration-300 sm:py-3 sm:pl-6 sm:pr-20',
        shown ? 'translate-y-0' : 'translate-y-full'
      )}
    >
      <div
        ref={progress}
        aria-hidden
        className="absolute inset-y-0 left-0 border-r border-[#151720]/15 bg-[#dfcf6f]"
        style={{ width: 0 }}
      />
      <div className="relative sm:hidden">
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="ghost"
              className="h-11 w-full justify-start gap-2 whitespace-normal p-0 text-left text-xs leading-4 hover:bg-transparent"
              aria-label="Fontos tudnivaló az adatokról, részletek megnyitása"
            >
              <Info className="size-4 shrink-0 text-red-800" aria-hidden />
              <span className="flex-1">
                <strong className="text-red-800">Figyelem! </strong>
                {short}
              </span>
              <ChevronUp className="size-3.5 shrink-0 text-[#151720]/60" aria-hidden />
            </Button>
          </PopoverTrigger>
          <PopoverContent
            side="top"
            align="start"
            sideOffset={12}
            aria-label="Az adatok értelmezése"
          >
            <Text variant="label" className="text-red-800">
              Fontos az adatok értelmezéséhez
            </Text>
            <Text variant="bodySm" className="mt-2">
              {children}
            </Text>
          </PopoverContent>
        </Popover>
      </div>
      <div className="relative hidden items-center justify-center gap-3 sm:flex">
        <span className="inline-flex shrink-0 items-center gap-1.5 text-sm font-bold text-red-800">
          <Info className="size-4" aria-hidden /> Figyelem!
        </span>
        <Text variant="bodySm" tone="inherit" className="leading-snug">
          {children}
        </Text>
      </div>
    </div>
  );
}

/**
 * An interactive block of the last part, as one framed unit: the question, its control and the
 * answer on the left, the view that belongs to them on the right (under them on phones). With
 * `stack`, the view is under them on every screen, across the whole panel.
 */
export function PlayPanel({
  title,
  lead,
  controls,
  view,
  layout = 'split',
}: {
  title: ReactNode;
  lead?: ReactNode;
  controls: ReactNode;
  view: ReactNode;
  layout?: 'split' | 'stack';
}) {
  const split = layout === 'split';
  return (
    <Reveal>
      <article className="border border-[#151720]/10 bg-surface-paper p-5 sm:p-8 lg:p-10">
        <div className={cn('grid gap-8', split && 'lg:grid-cols-12 lg:gap-12')}>
          <div className={cn('min-w-0', split ? 'lg:col-span-5' : 'max-w-3xl')}>
            <h3 className="font-slab text-2xl font-bold leading-tight sm:text-3xl lg:text-4xl">
              {title}
            </h3>
            {lead ? (
              <Text tone="muted" className="mt-4">
                {lead}
              </Text>
            ) : null}
            <div className="mt-6">{controls}</div>
          </div>
          <div className={cn('min-w-0', split && 'lg:col-span-7')}>{view}</div>
        </div>
      </article>
    </Reveal>
  );
}
