// HyperBook — Desktop layout
// Persistent left sidebar TOC with inline summary unfold; wide reading column.

const { useState: useStateD, useEffect: useEffectD, useMemo: useMemoD, useRef: useRefD } = React;

const TWEAKS_D = /*EDITMODE-BEGIN*/{
  "transition": "unfold",
  "paperTone": "cream",
  "typeSize": 18,
  "lampMode": false,
  "showPullQuote": true,
  "sidebarWidth": 360
}/*EDITMODE-END*/;

// ─────────────────────────────────────────────────────────────────────────
// Desktop reading column — wider margins, larger type
// ─────────────────────────────────────────────────────────────────────────

function DesktopReadingColumn({ chapter, all, onNavigate, lampMode, typeSize, showPullQuote }) {
  const idx = all.findIndex((c) => c.n === chapter.n);
  const prev = idx > 0 ? all[idx - 1] : null;
  const next = idx < all.length - 1 ? all[idx + 1] : null;

  const fg = lampMode ? 'var(--paper)' : 'var(--ink)';
  const fg2 = lampMode ? 'rgba(246,241,229,0.82)' : 'var(--ink-soft)';
  const fg3 = lampMode ? 'rgba(246,241,229,0.5)' : 'var(--ink-mute)';
  const accent = lampMode ? '#E89260' : 'var(--flame)';
  const border = lampMode ? 'rgba(246,241,229,0.25)' : 'var(--ink)';

  return (
    <article style={{
      maxWidth: 640, margin: '0 auto',
      padding: '52px 24px 120px',
    }}>

      {/* eyebrow */}
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 28,
      }}>
        <Chrome style={{ color: accent, fontSize: 12 }}>
          {`Part ${chapter.partRoman} · ${chapter.partTitle}`}
        </Chrome>
        <span style={{ flex: 1, height: 1, background: border, opacity: 0.5, marginBottom: 4, minWidth: 8 }} />
        <Chrome style={{ color: fg3, fontSize: 11, flexShrink: 0 }}>
          {`${chapter.readMin} min read · p. ${chapter.page}`}
        </Chrome>
      </div>

      {/* chapter number */}
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 13, letterSpacing: '.32em',
        color: fg3, textTransform: 'uppercase', marginBottom: 12,
      }}>{`Chapter ${chapter.n}`}</div>

      {/* chapter title — bigger on desktop but still editorial */}
      <h1 style={{
        fontFamily: 'var(--font-serif)', fontWeight: 500, fontStyle: 'normal',
        fontSize: 44, lineHeight: 1.08, letterSpacing: '-0.015em',
        color: fg, margin: '0 0 44px',
        textWrap: 'balance',
      }}>{chapter.title}</h1>

      {/* body — markdown-rendered. */}
      {(() => {
        const md = Array.isArray(chapter.body) ? chapter.body.join('\n\n') : chapter.body;
        const theme = buildTheme({
          lampMode, typeSize, accent, fg, fg2, fg3, scale: 'desktop',
        });
        const pqEl = showPullQuote && chapter.pullQuote
          ? <DesktopPullQuote text={chapter.pullQuote} lampMode={lampMode} accent={accent} fg={fg} />
          : null;
        return (
          <Markdown
            text={md}
            theme={theme}
            dropCap={true}
            pullQuoteAfter={2}
            pullQuoteEl={pqEl}
          />
        );
      })()}

      {/* ornament */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        margin: '54px 0 36px', gap: 14,
      }}>
        <span style={{ width: 40, height: 1, background: border, opacity: 0.6 }} />
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 15, letterSpacing: '.3em',
          color: fg3,
        }}>§</span>
        <span style={{ width: 40, height: 1, background: border, opacity: 0.6 }} />
      </div>

      {/* prev / next */}
      <nav style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 28,
      }}>
        {prev ? <DesktopChapterLink dir="prev" chapter={prev} onClick={() => onNavigate(prev.n)} lampMode={lampMode} /> : <div />}
        {next ? <DesktopChapterLink dir="next" chapter={next} onClick={() => onNavigate(next.n)} lampMode={lampMode} /> : <div />}
      </nav>
    </article>
  );
}

function DesktopPullQuote({ text, lampMode, accent, fg }) {
  const border = lampMode ? 'rgba(246,241,229,0.4)' : 'var(--ink)';
  return (
    <aside style={{
      margin: '32px -40px 32px',
      padding: '24px 28px 24px 30px',
      borderTop: `1.5px solid ${border}`,
      borderBottom: `1.5px solid ${border}`,
      position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: -12, left: 24,
        background: lampMode ? '#15110F' : 'var(--paper)',
        padding: '0 10px',
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.24em',
        color: accent, textTransform: 'uppercase',
        whiteSpace: 'nowrap',
      }}>« pull quote</div>
      <p style={{
        fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 500,
        fontSize: 26, lineHeight: 1.26, color: fg,
        margin: 0, textWrap: 'balance',
      }}>{text}</p>
    </aside>
  );
}

function DesktopChapterLink({ dir, chapter, onClick, lampMode }) {
  const isPrev = dir === 'prev';
  const fg = lampMode ? 'var(--paper)' : 'var(--ink)';
  const fg3 = lampMode ? 'rgba(246,241,229,0.5)' : 'var(--ink-mute)';
  const border = lampMode ? 'rgba(246,241,229,0.35)' : 'var(--ink)';
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer',
      background: 'transparent',
      border: `1px solid ${border}`,
      padding: '16px 18px',
      textAlign: isPrev ? 'left' : 'right',
      display: 'flex', flexDirection: 'column', gap: 6,
      transition: 'transform 80ms linear, box-shadow 80ms linear',
    }}
    onMouseDown={(e) => e.currentTarget.style.transform = 'translate(1px,1px)'}
    onMouseUp={(e) => e.currentTarget.style.transform = ''}
    onMouseLeave={(e) => e.currentTarget.style.transform = ''}>
      <span style={{
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.24em',
        color: fg3, textTransform: 'uppercase', whiteSpace: 'nowrap',
      }}>{isPrev ? `← ch. ${chapter.n} · previous` : `next · ch. ${chapter.n} →`}</span>
      <span style={{
        fontFamily: 'var(--font-serif)', fontWeight: 500, fontStyle: 'italic',
        fontSize: 17, color: fg, lineHeight: 1.25, textWrap: 'balance',
      }}>{chapter.title}</span>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Desktop sidebar — persistent left rail with TOC + inline summary unfold
// ─────────────────────────────────────────────────────────────────────────

function DesktopSidebar({ book, expandedN, setExpandedN, currentN, transition, lampMode, onReadChapter, onHome, width }) {
  const fg = lampMode ? 'var(--paper)' : 'var(--ink)';
  const fg2 = lampMode ? 'rgba(246,241,229,0.82)' : 'var(--ink-soft)';
  const fg3 = lampMode ? 'rgba(246,241,229,0.5)' : 'var(--ink-mute)';
  const accent = lampMode ? '#E89260' : 'var(--flame)';
  const bg = lampMode ? '#1A1614' : 'var(--surface-2)';
  const border = lampMode ? 'rgba(246,241,229,0.18)' : 'var(--ink)';

  return (
    <aside style={{
      width, flexShrink: 0,
      background: bg,
      borderRight: `1.5px solid ${border}`,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      height: '100%',
    }}>
      {/* sidebar chrome top */}
      <div style={{
        padding: '14px 18px 12px',
        borderBottom: `1.5px solid ${border}`,
        background: lampMode ? '#15110F' : 'var(--paper)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
      }}>
          <Chrome style={{ color: fg, fontSize: 12 }}>Contents</Chrome>
        <Chrome style={{ color: fg3, fontSize: 11, flexShrink: 0 }}>{`${flattenChapters(book).length} lessons · ${book.parts.length} parts`}</Chrome>
      </div>

      {/* book masthead */}
      <div
        onClick={onHome}
        role={onHome ? 'button' : undefined}
        tabIndex={onHome ? 0 : undefined}
        onKeyDown={(e) => { if (onHome && (e.key === 'Enter' || e.key === ' ')) onHome(); }}
        style={{
          padding: '22px 20px 18px',
          borderBottom: `1px solid ${border}`,
          background: lampMode ? '#15110F' : 'var(--paper)',
          cursor: onHome ? 'pointer' : 'default',
        }}>
        <Chrome style={{ color: accent, fontSize: 10 }}>field guide · 2025 · first ed.</Chrome>
        <h2 style={{
          fontFamily: 'var(--font-serif)', fontWeight: 600, fontStyle: 'italic',
          fontSize: 32, lineHeight: 1.02, letterSpacing: '-0.015em',
          color: fg, margin: '6px 0 6px', textWrap: 'balance',
        }}>{book.title}</h2>
        <p style={{
          fontFamily: 'var(--font-serif)', fontWeight: 400, fontStyle: 'italic',
          fontSize: 13.5, lineHeight: 1.35, color: fg2,
          margin: '0 0 12px',
        }}>{book.subtitle}</p>
        <Chrome style={{ color: fg3, fontSize: 10 }}>
          {`${book.author}  ·  ${book.publisher}`}
        </Chrome>
      </div>

      {/* hint pill */}
      <div style={{
        padding: '12px 18px 6px',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <span style={{
          width: 6, height: 6, background: accent, borderRadius: '50%',
          flexShrink: 0,
        }} />
        <span style={{
          fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12.5,
          color: fg3, lineHeight: 1.35,
        }}>tap a chapter to unfold its summary.</span>
      </div>

      {/* TOC list */}
      <div style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        padding: '6px 0 40px',
      }}>
        {book.parts.map((part) => (
          <PartSection
            key={part.part}
            part={part}
            currentN={currentN}
            expandedN={expandedN}
            setExpandedN={setExpandedN}
            transition={transition}
            lampMode={lampMode}
            onReadChapter={onReadChapter}
          />
        ))}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '18px 18px 0',
        }}>
          <span style={{ flex: 1, height: 1, background: border, opacity: 0.55 }} />
          <Chrome style={{ color: fg3, fontSize: 10 }}>· end ·</Chrome>
          <span style={{ flex: 1, height: 1, background: border, opacity: 0.55 }} />
        </div>
      </div>

      {/* bottom edition strip */}
      <div style={{
        padding: '10px 18px',
        borderTop: `1px solid ${border}`,
        background: lampMode ? '#0F0C0B' : 'var(--paper)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <Chrome style={{ color: fg3, fontSize: 10 }}>hyperbook v0.1</Chrome>
        <Chrome style={{ color: fg3, fontSize: 10 }}>side b press</Chrome>
      </div>
    </aside>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Desktop reading-area header — running chapter chrome
// ─────────────────────────────────────────────────────────────────────────

function DesktopRunningHeader({ chapter, totalPages, lampMode, progress }) {
  const fg = lampMode ? 'var(--paper)' : 'var(--ink)';
  const fg3 = lampMode ? 'rgba(246,241,229,0.5)' : 'var(--ink-mute)';
  const accent = lampMode ? '#E89260' : 'var(--flame)';
  const bg = lampMode ? '#15110F' : 'var(--paper)';
  const border = lampMode ? 'rgba(246,241,229,0.2)' : 'var(--ink)';
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 5,
      background: bg, borderBottom: `1px solid ${border}`,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 18,
        padding: '12px 32px',
        maxWidth: 1100, margin: '0 auto',
      }}>
        <Chrome style={{ color: fg, fontSize: 12, flexShrink: 0 }}>
          {`LLMs for Creatives · ch. ${chapter.n}`}
        </Chrome>
        <span style={{
          fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 400,
          fontSize: 14, color: fg3, flex: 1, minWidth: 0,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>— {chapter.title}</span>
        <Chrome style={{ color: accent, fontSize: 12, flexShrink: 0 }}>
          {`p. ${chapter.page} / ${totalPages}`}
        </Chrome>
      </div>
      {/* hairline progress */}
      <div style={{
        height: 2, width: `${Math.round(progress * 100)}%`,
        background: accent, transition: 'width 120ms linear',
      }} />
    </header>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Desktop app
// ─────────────────────────────────────────────────────────────────────────

function HyperBookDesktop() {
  const [t, setTweak] = useTweaks(TWEAKS_D);

  const flat = useMemoD(() => flattenChapters(window.BOOK), []);
  const [readingN, setReadingN] = useStateD('02');
  const [expandedN, setExpandedN] = useStateD('10');     // ch 10 (SFT) shows markdown headings/lists in summary preview area

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

  const scrollRef = useRefD(null);
  const [progress, setProgress] = useStateD(0);

  useEffectD(() => {
    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]);

  const readChapter = (n) => {
    setReadingN(n);
    setExpandedN(n);
    requestAnimationFrame(() => {
      if (scrollRef.current) scrollRef.current.scrollTo({ top: 0, behavior: 'smooth' });
    });
  };

  const paperVar = {
    cream: { '--paper': '#F6F1E5', '--surface': '#FBF7EC', '--surface-2': '#F1EAD7' },
    bone:  { '--paper': '#EFE9DA', '--surface': '#F5F0E0', '--surface-2': '#E8E1CE' },
    warm:  { '--paper': '#E8DEC9', '--surface': '#EFE6D2', '--surface-2': '#DFD3BA' },
  }[t.paperTone] || {};

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

  // Frame inner size (browser content area)
  const FRAME_W = 1280, FRAME_H = 880;
  const innerH = FRAME_H - 44 /* chrome */ - 40 /* toolbar */;

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      minHeight: '100vh', padding: '24px 0 60px', gap: 16,
    }}>
      <DesktopDesignNotes />

      <div style={{ ...paperVar }}>
        <ChromeWindow
          width={FRAME_W} height={FRAME_H}
          tabs={[
            { title: 'hyperbook · llms for designers' },
            { title: 'side b press · about' },
          ]}
          activeIndex={0}
          url={`hyperbook.app/llms-for-designers/ch-${readingChapter.n}`}>

          <div style={{
            display: 'flex', height: innerH, background: bg,
          }}>
            {/* sidebar */}
            <DesktopSidebar
              book={window.BOOK}
              expandedN={expandedN}
              setExpandedN={setExpandedN}
              currentN={readingN}
              transition={t.transition}
              lampMode={lamp}
              onReadChapter={readChapter}
              width={t.sidebarWidth}
            />

            {/* main reading column */}
            <main ref={scrollRef} style={{
              flex: 1, overflowY: 'auto', overflowX: 'hidden',
              background: bg, position: 'relative',
            }}>
              <DesktopRunningHeader
                chapter={readingChapter}
                totalPages={window.BOOK.totalPages}
                lampMode={lamp}
                progress={progress}
              />
              <DesktopReadingColumn
                chapter={readingChapter}
                all={flat}
                onNavigate={readChapter}
                lampMode={lamp}
                typeSize={t.typeSize}
                showPullQuote={t.showPullQuote}
              />
            </main>
          </div>
        </ChromeWindow>
      </div>

      <DesktopCaption 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 & layout" />
        <TweakSlider
          label="Body size"
          value={t.typeSize}
          min={15} max={22} step={1} unit="px"
          onChange={(v) => setTweak('typeSize', v)}
        />
        <TweakSlider
          label="Sidebar width"
          value={t.sidebarWidth}
          min={300} max={440} step={10} unit="px"
          onChange={(v) => setTweak('sidebarWidth', v)}
        />
        <TweakToggle
          label="Pull quotes"
          value={t.showPullQuote}
          onChange={(v) => setTweak('showPullQuote', v)}
        />
      </TweaksPanel>
    </div>
  );
}

function DesktopDesignNotes() {
  return (
    <div style={{
      maxWidth: 1100, padding: '0 32px',
      display: 'flex', alignItems: 'baseline', gap: 24,
    }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <Chrome style={{ color: 'var(--flame)', fontSize: 11 }}>
          hyperbook · prototype 01 · desktop · may 2026
        </Chrome>
        <h1 style={{
          fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 600,
          fontSize: 28, lineHeight: 1.05, letterSpacing: '-0.015em',
          color: 'var(--ink)', margin: '2px 0 4px', textWrap: 'balance',
        }}>The contents thinks out loud — beside you, as you read.</h1>
        <p style={{
          fontFamily: 'var(--font-serif)', fontWeight: 400, fontSize: 13.5,
          lineHeight: 1.5, color: 'var(--ink-soft)', margin: 0, maxWidth: 720,
        }}>
          On desktop the table of contents lives permanently on the left.  Tap a
          chapter and its summary unfolds in place, beside whatever you're
          reading — no drawer to open, no page to lose.
        </p>
      </div>
      <a href="/mobile" 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,
      }}>← mobile version</a>
    </div>
  );
}

function DesktopCaption({ transition }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '0 32px', maxWidth: 1100, width: '100%', boxSizing: 'border-box',
    }}>
      <Chrome style={{ color: 'var(--ink-mute)', fontSize: 10 }}>fig. 02 · 1280 × 880 desktop</Chrome>
      <span style={{ flex: 1, height: 1, background: 'var(--ink)', opacity: 0.25 }} />
      <Chrome style={{ color: 'var(--flame)', fontSize: 10 }}>{`transition: ${transition}`}</Chrome>
    </div>
  );
}

Object.assign(window, {
  HyperBookDesktop,
  DesktopReadingColumn,
  DesktopSidebar,
  DesktopRunningHeader,
});
