const { useMemo: useMemoP, useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

function HyperBookProduct() {
  const [isMobile, setIsMobile] = useStateP(() => window.matchMedia('(max-width: 820px)').matches);

  useEffectP(() => {
    const mq = window.matchMedia('(max-width: 820px)');
    const onChange = () => setIsMobile(mq.matches);
    onChange();
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);

  return isMobile ? <ProductMobile /> : <ProductDesktop />;
}

function ProductDesktop() {
  const flat = useMemoP(() => flattenChapters(window.BOOK), []);
  const [readingN, setReadingN] = useStateP(null);
  const [expandedN, setExpandedN] = useStateP('01');
  const scrollRef = useRefP(null);

  const readingChapter = readingN ? flat.find((c) => c.n === readingN) : null;

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

  const showHome = () => {
    setReadingN(null);
    requestAnimationFrame(() => scrollRef.current?.scrollTo({ top: 0, behavior: 'smooth' }));
  };

  return (
    <div style={{
      height: '100vh', width: '100vw', overflow: 'hidden',
      display: 'flex', background: 'var(--paper)', color: 'var(--ink)',
    }}>
      {readingChapter && (
        <DesktopSidebar
          book={window.BOOK}
          expandedN={expandedN}
          setExpandedN={setExpandedN}
          currentN={readingN}
          transition="unfold"
          lampMode={false}
          onReadChapter={readChapter}
          onHome={showHome}
          width={360}
        />
      )}
      <main ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        background: 'var(--paper)', position: 'relative', minWidth: 0,
      }}>
        {readingChapter ? (
          <DesktopReadingColumn
            chapter={readingChapter}
            all={flat}
            onNavigate={readChapter}
            lampMode={false}
            typeSize={18}
            showPullQuote={true}
          />
        ) : (
          <TableOfContentsHome
            book={window.BOOK}
            flat={flat}
            expandedN={expandedN}
            setExpandedN={setExpandedN}
            onReadChapter={readChapter}
            isMobile={false}
          />
        )}
      </main>
    </div>
  );
}

function ProductMobile() {
  const flat = useMemoP(() => flattenChapters(window.BOOK), []);
  const [readingN, setReadingN] = useStateP(null);
  const [drawerOpen, setDrawerOpen] = useStateP(false);
  const [expandedN, setExpandedN] = useStateP('01');
  const scrollRef = useRefP(null);
  const readingChapter = readingN ? flat.find((c) => c.n === readingN) : null;

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

  const showHome = () => {
    setReadingN(null);
    setDrawerOpen(false);
    requestAnimationFrame(() => scrollRef.current?.scrollTo({ top: 0, behavior: 'smooth' }));
  };

  return (
    <div style={{
      position: 'relative', width: '100vw', height: '100vh', overflow: 'hidden',
      background: 'var(--paper)', color: 'var(--ink)',
    }}>
      <div ref={scrollRef} style={{
        position: 'absolute', inset: 0, overflowY: 'auto', overflowX: 'hidden',
        background: 'var(--paper)',
      }}>
        {readingChapter ? (
          <ReadingView
            chapter={readingChapter}
            all={flat}
            onNavigate={readChapter}
            lampMode={false}
            typeSize={17}
            showPullQuote={true}
          />
        ) : (
          <TableOfContentsHome
            book={window.BOOK}
            flat={flat}
            expandedN={expandedN}
            setExpandedN={setExpandedN}
            onReadChapter={readChapter}
            isMobile={true}
          />
        )}
      </div>
      <button onClick={() => readingChapter ? showHome() : setDrawerOpen(true)} aria-label="Open contents" style={{
        position: 'fixed', left: 16, bottom: 16, zIndex: 34,
        appearance: 'none', cursor: 'pointer',
        background: 'var(--flame)', color: 'var(--paper)',
        border: '1.5px solid var(--ink)',
        boxShadow: '3px 3px 0 var(--ink)',
        padding: '10px 13px 9px',
        fontFamily: 'var(--font-sans)', fontWeight: 700,
        fontSize: 12, letterSpacing: '.1em', textTransform: 'uppercase',
      }}>{readingChapter ? 'Contents' : 'Browse'}</button>
      <ContentsDrawer
        book={window.BOOK}
        isOpen={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        expandedN={expandedN}
        setExpandedN={setExpandedN}
        currentN={readingN}
        transition="unfold"
        lampMode={false}
        onReadChapter={readChapter}
      />
    </div>
  );
}

function TableOfContentsHome({ book, flat, expandedN, setExpandedN, onReadChapter, isMobile }) {
  const totalMinutes = flat.reduce((sum, ch) => sum + (ch.readMin || 0), 0);
  const maxWidth = isMobile ? '100%' : 980;

  return (
    <section style={{
      maxWidth,
      margin: '0 auto',
      padding: isMobile ? '30px 20px 112px' : '58px 42px 120px',
      boxSizing: 'border-box',
    }}>
      <header style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.1fr .9fr',
        gap: isMobile ? 22 : 44,
        alignItems: 'end',
        paddingBottom: isMobile ? 26 : 38,
        borderBottom: '1.5px solid var(--ink)',
      }}>
        <div>
          <Chrome style={{ color: 'var(--flame)', fontSize: 11 }}>hyperbook · table of contents</Chrome>
          <h1 style={{
            fontFamily: 'var(--font-serif)',
            fontStyle: 'italic',
            fontWeight: 600,
            fontSize: isMobile ? 48 : 76,
            lineHeight: .92,
            letterSpacing: '-0.035em',
            color: 'var(--ink)',
            margin: '12px 0 14px',
            textWrap: 'balance',
          }}>{book.title}</h1>
          <p style={{
            fontFamily: 'var(--font-serif)',
            fontSize: isMobile ? 17 : 21,
            lineHeight: 1.34,
            color: 'var(--ink-soft)',
            margin: 0,
            maxWidth: 660,
            textWrap: 'pretty',
          }}>{book.subtitle}</p>
        </div>

        <aside style={{
          background: 'var(--surface)',
          border: '1.5px solid var(--ink)',
          boxShadow: '5px 5px 0 var(--flame)',
          padding: isMobile ? '16px 16px 14px' : '18px 20px 16px',
        }}>
          <Chrome style={{ color: 'var(--ink-mute)', fontSize: 10 }}>reading map</Chrome>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 10,
            marginTop: 12,
          }}>
            <HomeStat value={flat.length} label="lessons" />
            <HomeStat value={book.parts.length} label="parts" />
            <HomeStat value={`${Math.round(totalMinutes / 60)}h`} label="read" />
          </div>
        </aside>
      </header>

      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr',
        gap: isMobile ? 26 : 34,
        alignItems: 'start',
        marginTop: isMobile ? 24 : 34,
      }}>
        <div>
          {book.parts.map((part) => (
            <HomePart
              key={part.part}
              part={part}
              expandedN={expandedN}
              setExpandedN={setExpandedN}
              onReadChapter={onReadChapter}
              isMobile={isMobile}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

function HomeStat({ value, label }) {
  return (
    <div style={{ borderTop: '1px solid var(--ink)', paddingTop: 8 }}>
      <div style={{
        fontFamily: 'var(--font-serif)',
        fontStyle: 'italic',
        fontWeight: 600,
        fontSize: 30,
        lineHeight: 1,
        color: 'var(--ink)',
      }}>{value}</div>
      <Chrome style={{ color: 'var(--ink-mute)', fontSize: 9 }}>{label}</Chrome>
    </div>
  );
}

function HomePart({ part, expandedN, setExpandedN, onReadChapter, isMobile }) {
  return (
    <section style={{ marginBottom: isMobile ? 26 : 34 }}>
      <div style={{
        display: 'flex',
        alignItems: 'baseline',
        gap: 12,
        marginBottom: 10,
      }}>
        <Chrome style={{ color: 'var(--flame)', fontSize: 11 }}>{`Part ${part.part}`}</Chrome>
        <h2 style={{
          fontFamily: 'var(--font-serif)',
          fontStyle: 'italic',
          fontWeight: 600,
          fontSize: isMobile ? 22 : 28,
          lineHeight: 1.05,
          color: 'var(--ink)',
          margin: 0,
        }}>{part.title}</h2>
        <span style={{ flex: 1, height: 1, background: 'var(--ink)', opacity: .32 }} />
      </div>

      <ol style={{ listStyle: 'none', margin: 0, padding: 0, borderTop: '1px solid var(--ink)' }}>
        {part.chapters.map((ch) => {
          const isExpanded = ch.n === expandedN;
          return (
            <li key={ch.n} style={{ borderBottom: '1px solid var(--ink)' }}>
              <button
                onClick={() => setExpandedN(isExpanded ? null : ch.n)}
                style={{
                  appearance: 'none',
                  width: '100%',
                  border: 'none',
                  background: isExpanded ? 'rgba(217,107,39,0.065)' : 'transparent',
                  cursor: 'pointer',
                  padding: isMobile ? '14px 0' : '16px 0',
                  display: 'grid',
                  gridTemplateColumns: isMobile ? '34px 1fr' : '42px 1fr 80px',
                  gap: 12,
                  alignItems: 'baseline',
                  textAlign: 'left',
                }}>
                <span style={{
                  fontFamily: 'var(--font-mono)',
                  fontSize: 14,
                  letterSpacing: '.08em',
                  color: isExpanded ? 'var(--flame)' : 'var(--ink-mute)',
                }}>{ch.n}</span>
                <span style={{
                  fontFamily: 'var(--font-serif)',
                  fontSize: isMobile ? 18 : 21,
                  fontStyle: isExpanded ? 'italic' : 'normal',
                  fontWeight: isExpanded ? 600 : 500,
                  lineHeight: 1.18,
                  color: 'var(--ink)',
                  textWrap: 'balance',
                }}>{ch.title}</span>
                {!isMobile && <Chrome style={{ color: 'var(--ink-mute)', fontSize: 10 }}>{`${ch.readMin}m · p.${ch.page}`}</Chrome>}
              </button>

              <MagicReveal chapterKey={isExpanded ? ch.n : `__empty_home_${ch.n}`} transition="unfold" lampMode={false}>
                {isExpanded ? <HomeInlineSummary chapter={ch} onRead={() => onReadChapter(ch.n)} isMobile={isMobile} /> : <div style={{ height: 0 }} />}
              </MagicReveal>
            </li>
          );
        })}
      </ol>
    </section>
  );
}

function HomeInlineSummary({ chapter, onRead, isMobile }) {
  return (
    <div style={{
      padding: isMobile ? '0 0 18px 46px' : '0 0 20px 54px',
      maxWidth: isMobile ? '100%' : 760,
    }}>
      <p style={{
        fontFamily: 'var(--font-serif)',
        fontSize: isMobile ? 16 : 17,
        lineHeight: 1.48,
        color: 'var(--ink-soft)',
        margin: '0 0 12px',
        textWrap: 'pretty',
      }}>{chapter.summary}</p>
      <button onClick={onRead} style={{
        appearance: 'none',
        cursor: 'pointer',
        background: 'var(--flame)',
        color: 'var(--paper)',
        border: '1.5px solid var(--ink)',
        boxShadow: '2px 2px 0 var(--ink)',
        padding: '7px 11px 6px',
        fontFamily: 'var(--font-sans)',
        fontWeight: 700,
        fontSize: 11,
        letterSpacing: '.08em',
        textTransform: 'uppercase',
      }}>Read lesson</button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HyperBookProduct />);
