// HyperBook — main app shell, mounts iOS frame + reading + contents

const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp, useRef: useRefApp } = React;

function HyperBookApp() {
  const [t, setTweak] = useTweaks(TWEAKS);

  const flat = useMemoApp(() => flattenChapters(window.BOOK), []);
  const [readingN, setReadingN] = useStateApp('01');
  const [drawerOpen, setDrawerOpen] = useStateApp(true);     // start open — show the magic
  const [expandedN, setExpandedN] = useStateApp('02');       // chapter 2 summary pre-unfolded

  const readingChapter = flat.find((c) => c.n === readingN) || flat[0];

  const scrollRef = useRefApp(null);

  const readChapter = (n) => {
    setReadingN(n);
    setDrawerOpen(false);
    setExpandedN(n);
    // scroll reading view to top
    requestAnimationFrame(() => {
      if (scrollRef.current) scrollRef.current.scrollTo({ top: 0, behavior: 'smooth' });
    });
  };

  // Reading progress for the top hairline
  const [progress, setProgress] = useStateApp(0);
  useEffectApp(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => {
      const max = el.scrollHeight - el.clientHeight;
      setProgress(max > 0 ? Math.min(1, el.scrollTop / max) : 0);
    };
    onScroll();
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, [readingN]);

  // Paper tone variant — applied via a wrapper inline-var
  const paperVar = {
    cream: { '--paper': '#F6F1E5', '--surface': '#FBF7EC' },
    bone:  { '--paper': '#EFE9DA', '--surface': '#F5F0E0' },
    warm:  { '--paper': '#E8DEC9', '--surface': '#EFE6D2' },
  }[t.paperTone] || {};

  const lamp = t.lampMode;
  const bodyBg = lamp ? '#15110F' : 'var(--paper)';

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      minHeight: '100vh', padding: '24px 0 80px',
      gap: 18,
    }}>
      {/* Designer notes header above frame */}
      <DesignNotes />

      <div style={{
        position: 'relative',
        ...paperVar,
      }}>
        <IOSDevice width={402} height={874} dark={lamp}>
          <div ref={scrollRef} style={{
            position: 'absolute', inset: 0,
            overflowY: 'auto', overflowX: 'hidden',
            background: bodyBg,
            paddingTop: 54,  // status bar clearance (status bar is absolute on top)
            paddingBottom: 0,
          }}>
            {/* top progress hairline — sits just below status bar */}
            <div style={{
              position: 'sticky', top: 0, zIndex: 32,
              height: 0,
            }}>
              <div style={{
                height: 2,
                width: `${Math.round(progress * 100)}%`,
                background: lamp ? '#E89260' : 'var(--flame)',
                transition: 'width 120ms linear',
              }} />
            </div>

            <PageHeader
              chapter={readingChapter}
              totalPages={window.BOOK.totalPages}
              onContents={() => setDrawerOpen(true)}
              lampMode={lamp}
            />

            <ReadingView
              chapter={readingChapter}
              all={flat}
              onNavigate={(n) => readChapter(n)}
              lampMode={lamp}
              typeSize={t.typeSize}
              showPullQuote={t.showPullQuote}
            />
          </div>

          {/* TOC drawer — overlaid above status bar area is OK because drawer is below status bar */}
          <div style={{ position: 'absolute', inset: '54px 0 0 0', zIndex: 36, pointerEvents: 'none' }}>
            <div style={{ position: 'relative', height: '100%', pointerEvents: 'auto' }}>
              <ContentsDrawer
                book={window.BOOK}
                isOpen={drawerOpen}
                onClose={() => setDrawerOpen(false)}
                expandedN={expandedN}
                setExpandedN={setExpandedN}
                currentN={readingN}
                transition={t.transition}
                lampMode={lamp}
                onReadChapter={readChapter}
              />
            </div>
          </div>
        </IOSDevice>
      </div>

      <FrameCaption transition={t.transition} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Magic" />
        <TweakSelect
          label="TOC → summary transition"
          value={t.transition}
          options={[
            { value: 'unfold',     label: 'Unfold · height grow' },
            { value: 'fold',       label: 'Fold · paper hinge' },
            { value: 'fade',       label: 'Fade · soft rise' },
            { value: 'marginalia', label: 'Marginalia · slide from gutter' },
            { value: 'bleed',      label: 'Bleed · ink wipe down' },
          ]}
          onChange={(v) => setTweak('transition', v)}
        />

        <TweakSection label="Paper" />
        <TweakRadio
          label="Tone"
          value={t.paperTone}
          options={[
            { value: 'cream', label: 'Cream' },
            { value: 'bone',  label: 'Bone' },
            { value: 'warm',  label: 'Warm' },
          ]}
          onChange={(v) => setTweak('paperTone', v)}
        />
        <TweakToggle
          label="Lamp mode (dark)"
          value={t.lampMode}
          onChange={(v) => setTweak('lampMode', v)}
        />

        <TweakSection label="Type" />
        <TweakSlider
          label="Body size"
          value={t.typeSize}
          min={14} max={22} step={1} unit="px"
          onChange={(v) => setTweak('typeSize', v)}
        />
        <TweakToggle
          label="Pull quotes in margin"
          value={t.showPullQuote}
          onChange={(v) => setTweak('showPullQuote', v)}
        />

        <TweakSection label="Demo" />
        <TweakButton label="Open contents drawer"  onClick={() => setDrawerOpen(true)} />
        <TweakButton label="Close drawer" secondary onClick={() => setDrawerOpen(false)} />
      </TweaksPanel>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Designer's notes — a small editorial preamble above the device frame
// ─────────────────────────────────────────────────────────────────────────

function DesignNotes() {
  return (
    <div style={{
      maxWidth: 540, padding: '0 24px',
      display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
        <Chrome style={{ color: 'var(--flame)', fontSize: 11 }}>
          Hyperbook · prototype 01 · may 2026
        </Chrome>
        <span style={{ flex: 1, height: 1, background: 'var(--ink)', opacity: 0.2 }} />
        <a href="/" style={{
          fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.22em',
          textTransform: 'uppercase', color: 'var(--ink)',
          textDecoration: 'underline', textDecorationColor: 'var(--flame)',
          textUnderlineOffset: 4, whiteSpace: 'nowrap', flexShrink: 0,
        }}>desktop version →</a>
      </div>
      <h1 style={{
        fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 600,
        fontSize: 32, lineHeight: 1.04, letterSpacing: '-0.015em',
        color: 'var(--ink)', margin: '2px 0 4px',
        textWrap: 'balance',
      }}>
        A book where the table of contents thinks out loud.
      </h1>
      <p style={{
        fontFamily: 'var(--font-serif)', fontWeight: 400,
        fontSize: 14, lineHeight: 1.5, color: 'var(--ink-soft)',
        margin: 0, maxWidth: 480, textWrap: 'pretty',
      }}>
        Tap a chapter in the contents drawer.  Instead of jumping straight to the page,
        the section unfolds an inline summary — chapter promise, short explanation,
        key takeaways — like a marginal note opening inside the book.  Tap{' '}
        <em>Read chapter</em> to continue into the full text.
      </p>
      <Chrome style={{ color: 'var(--ink-mute)', fontSize: 10, marginTop: 6 }}>
        try the tweaks panel · five unfold transitions · lamp mode · paper tones
      </Chrome>
    </div>
  );
}

function FrameCaption({ transition }) {
  const labels = {
    unfold: 'unfold · height grow + slight rise',
    fold: 'fold · paper hinge, rotateX',
    fade: 'fade · opacity + soft rise',
    marginalia: 'marginalia · slides from the gutter',
    bleed: 'bleed · ink wipe down with light blur',
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '0 24px', maxWidth: 540,
    }}>
      <Chrome style={{ color: 'var(--ink-mute)', fontSize: 10 }}>fig. 01 · iphone 15 pro</Chrome>
      <span style={{ flex: 1, height: 1, background: 'var(--ink)', opacity: 0.25 }} />
      <Chrome style={{ color: 'var(--flame)', fontSize: 10 }}>
        {`transition: ${labels[transition] || transition}`}
      </Chrome>
    </div>
  );
}

Object.assign(window, { HyperBookApp });
