// book-full.jsx — Direction A, fully extended. WIRED TO BACKEND (critical features).
// Cover + 9 chapters + closing, presented as a vertical stack of book spreads.
//
// Wired via window.V2 (see v2-bridge.js):
//   • Login gate (LoginGateBook below)
//   • Chapter II "Days" → live count from CONFIG.anchorDate
//   • Chapter VII "The Bell" → real form + real recent rings log

const { useState: useStateFull, useEffect: useEffectFull, useRef: useRefFull } = React;

/* ════════════════════════════════════════════════════════════
   Floating controls (top-right): language toggle + push toggle
   ════════════════════════════════════════════════════════════ */

function FloatingControlsBook() {
  const [lang, setLang] = V2.useLang();
  const push = V2.usePushToggle();
  const { unlocked } = V2.useAuth();
  const onLogout = () => {
    if (confirm('Log out and re-enter the password?')) V2.logout();
  };
  return (
    <div style={{ position: 'fixed', top: 16, right: 16, zIndex: 200,
                  display: 'flex', gap: 8, alignItems: 'center' }}>
      {push.supported && (
        <button onClick={push.toggle} title={push.subscribed ? 'Notifications on' : 'Enable notifications'}
                style={pillBtnBook}>
          {push.subscribed ? '🔔' : '🔕'}
        </button>
      )}
      <button onClick={() => setLang(lang === 'en' ? 'ar' : 'en')} title="Switch language"
              style={pillBtnBook}>
        {lang === 'en' ? 'ع' : 'EN'}
      </button>
      {unlocked && (
        <button onClick={onLogout} title="Log out" style={pillBtnBook}>
          ⎋
        </button>
      )}
    </div>
  );
}
const pillBtnBook = {
  background: '#FDFAF3',
  border: '1px solid #8B6F47',
  color: '#6B4423',
  width: 40, height: 40, borderRadius: '50%',
  fontSize: 15, fontFamily: "'EB Garamond', serif",
  cursor: 'pointer', boxShadow: '0 4px 12px rgba(43,31,17,0.15)',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

/* ════════════════════════════════════════════════════════════
   Login gate (book-themed)
   ════════════════════════════════════════════════════════════ */

function LoginGateBook({ children }) {
  const { unlocked, login, pickIdentity, identity } = V2.useAuth();
  const [who, setWho] = useStateFull(identity || null);
  const [password, setPassword] = useStateFull('');
  const [error, setError] = useStateFull(null);
  const [busy, setBusy] = useStateFull(false);

  if (unlocked && who) return children;

  const onSubmit = async (e) => {
    e?.preventDefault?.();
    setBusy(true); setError(null);
    const ok = await login(password, who);
    setBusy(false);
    if (!ok) { setError("That's not the word."); setPassword(''); }
  };

  // Book-aesthetic login page — paper, gold rule, monogram.
  return (
    <div style={{
      minHeight: '100vh', background: '#F5F0E6', color: '#2B1F11',
      fontFamily: "'EB Garamond', serif",
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40
    }}>
      <div style={{
        background: '#FDFAF3', padding: '60px 50px', maxWidth: 460, width: '100%',
        border: '1px solid #C5A05E', borderRadius: 4,
        boxShadow: '0 24px 60px rgba(43,31,17,0.18)', textAlign: 'center'
      }}>
        <div style={{ fontSize: 56, color: '#6B4423', fontWeight: 400, letterSpacing: '0.04em', marginBottom: 4 }}>
          M <span style={{ fontStyle: 'italic', color: '#C5A05E' }}>&amp;</span> D
        </div>
        <div style={{ width: 60, height: 1, background: '#C5A05E', margin: '14px auto 24px' }} />
        <div style={{ fontStyle: 'italic', color: '#6B4423', opacity: 0.75, fontSize: 16, marginBottom: 24 }}>
          A Private Universe — Volume I
        </div>

        {!who ? (
          <>
            <div style={{ fontSize: 13, color: '#6B4423', letterSpacing: '0.3em', textTransform: 'uppercase', opacity: 0.65, marginBottom: 20 }}>
              who's reading?
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
              <button style={bookBtn} onClick={() => { setWho('mo'); pickIdentity('mo'); }}>I am Mo</button>
              <button style={bookBtn} onClick={() => { setWho('duha'); pickIdentity('duha'); }}>I am Duha</button>
            </div>
          </>
        ) : (
          <form onSubmit={onSubmit}>
            <div style={{ fontSize: 13, color: '#6B4423', letterSpacing: '0.3em', textTransform: 'uppercase', opacity: 0.65, marginBottom: 20 }}>
              {error || "what's our word?"}
            </div>
            <input type="password" autoFocus value={password} onChange={e => setPassword(e.target.value)}
                   placeholder="•••••"
                   style={{
                     width: '100%', padding: 14, border: '1px solid #8B6F47',
                     background: '#FFFCF5', color: '#2B1F11', fontSize: 16,
                     fontFamily: "'EB Garamond', serif", textAlign: 'center',
                     letterSpacing: '0.2em', borderRadius: 4, marginBottom: 16
                   }} />
            <button type="submit" disabled={busy || !password} style={{ ...bookBtn, width: '100%' }}>
              {busy ? 'opening…' : 'Open the book'}
            </button>
            <button type="button" onClick={() => setWho(null)}
                    style={{ background: 'none', border: 'none', color: '#8B6F47', fontSize: 12,
                             fontStyle: 'italic', cursor: 'pointer', marginTop: 12, fontFamily: "'EB Garamond', serif" }}>
              ← change reader
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

const bookBtn = {
  padding: '12px 28px', background: '#6B4423', color: '#FDFAF3',
  border: '1px solid #6B4423', borderRadius: 3, fontSize: 15,
  fontFamily: "'EB Garamond', serif", letterSpacing: '0.05em',
  cursor: 'pointer', fontStyle: 'italic'
};

/* ════════════════════════════════════════════════════════════
   Shared bits
   ════════════════════════════════════════════════════════════ */

function Flourish() {
  return (
    <div className="book-flourish">
      <div className="book-flourish__line" />
      <div className="book-flourish__diamond" />
      <div className="book-flourish__line" />
    </div>
  );
}

function ChapterHead({ num, title, titleEm, titleAr }) {
  return (
    <>
      <div className="book-chapter-num">Chapter {num}</div>
      <h2 className="book-chapter-title">{title}{titleEm && <> <em>{titleEm}</em></>}</h2>
      <div className="book-chapter-title-ar">{titleAr}</div>
      <div className="book-chapter-rule" />
    </>
  );
}

/* ════════════════════════════════════════════════════════════
   Spread 1 — Cover & Table of Chapters
   ════════════════════════════════════════════════════════════ */

function FullCover() {
  const toc = [
    { num: 'I',    en: 'How we met',                  ar: 'كيف التقينا',           folio: '09' },
    { num: 'II',   en: 'Days, counted',               ar: 'أيام، معدودة',           folio: '17' },
    { num: 'III',  en: 'Reasons',                     ar: 'أسباب',                 folio: '25' },
    { num: 'IV',   en: 'Letters to you',              ar: 'رسائل إليكِ',           folio: '33' },
    { num: 'V',    en: 'Voices, on the days',         ar: 'أصوات، في الأيام',      folio: '49' },
    { num: 'VI',   en: 'Plates: a year in frames',    ar: 'لوحات: سنة في صور',     folio: '61' },
    { num: 'VII',  en: 'The Bell',                    ar: 'الجرس',                 folio: '75' },
    { num: 'VIII', en: 'The house we are building',   ar: 'البيت الذي نبنيه',      folio: '83' },
    { num: 'IX',   en: 'Forever yours.',              ar: 'إلى الأبد لكِ.',        folio: '95' },
  ];
  return (
    <div className="book book--cover">
      <div className="book__spread">
        <div className="book__page">
          <div className="book-monogram">M <span className="amp">&amp;</span> D</div>
          <div className="book-cover-rule" />
          <div className="book-cover-title">
            A Private Universe<br/>
            <em style={{ opacity: 0.7, fontSize: '0.82em' }}>in two languages</em>
          </div>
          <div className="book-cover-meta">
            Volume I  ·  Privately Bound<br/>
            For her, by him.  ·  لها، منه.
          </div>
        </div>
        <div className="book__gutter" />
        <div className="book__page">
          <div className="book-tocheader">Table of Chapters</div>
          <div className="book-toc">
            {toc.map((c, i) => (
              <div key={i} className="book-toc__row">
                <span className="book-toc__num">{c.num}</span>
                <span className="book-toc__title">{c.en}</span>
                <span className="book-toc__title-ar">{c.ar}</span>
                <span className="book-toc__leader" />
                <span className="book-toc__folio">{c.folio}</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 36 }}><Flourish /></div>
          <div className="book-cover-meta" style={{ marginTop: 'auto' }}>
            Begun 5 October 2023  ·  Still being written
          </div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter I — How we met
   ════════════════════════════════════════════════════════════ */

function ChapterMeet() {
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="I" title="How we" titleEm="met." titleAr="كيف التقينا." />

          <div className="book-body">
            <p>
              It was a Thursday. Not a particularly remarkable one — that was the joke for
              months afterward, that the most important Thursday of either of our lives
              had been disguised as an ordinary errand. I was supposed to meet a friend.
              He was late. You were not.
            </p>
            <p>
              I had been holding a book I was not reading. You asked, with what I now
              know was your normal voice but at the time felt like a small private weather
              system, whether the chair next to me was taken. It was. I said no anyway.
              I have been saying no anyway ever since.
            </p>
            <p>
              We talked for forty minutes. We talked for two hours. I have, in the years
              since, given up trying to reconstruct the conversation; what I remember is
              the way you tilted your head when you were thinking, and the moment in the
              second hour where you started a sentence with <em>well, the thing is —</em>
              and the world quietly rearranged itself around me.
            </p>
          </div>

          <div className="book-margin" style={{ top: 200 }}>
            <small>The friend</small>
            <em>arrived an hour and twenty minutes late.</em> I have never thanked him properly.
            I should.
          </div>
          <div className="book-margin" style={{ top: 400 }}>
            <small>The book</small>
            <em>was Calvino,</em> <em>Invisible Cities</em>. I still have it. The receipt
            from that day is still in the back.
          </div>

          <div className="book-footnote">
            * In Arabic, the verb for <em>to meet</em> and <em>to gather</em> share a
            root. لقاء. I think about that often.
          </div>

          <div className="book__folio book__folio--left">— 9 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <div className="book-plate__inner" />
            <svg className="book-plate__diagram" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
              <g>
                {/* Engraved date with ornaments */}
                <text x="50" y="35" textAnchor="middle"
                      fontFamily="'EB Garamond', serif" fontStyle="italic"
                      fontSize="3.2" fill="rgba(232, 199, 123, 0.65)"
                      letterSpacing="0.3em">THE FIFTH OF OCTOBER</text>
                <line x1="20" y1="40" x2="80" y2="40" stroke="#C5A05E" strokeWidth="0.2" opacity="0.5" />
                <text x="50" y="58" textAnchor="middle"
                      fontFamily="'EB Garamond', serif"
                      fontSize="14" fill="#E8C77B"
                      fontWeight="500">2023</text>
                <line x1="20" y1="64" x2="80" y2="64" stroke="#C5A05E" strokeWidth="0.2" opacity="0.5" />
                <text x="50" y="74" textAnchor="middle"
                      fontFamily="'EB Garamond', serif" fontStyle="italic"
                      fontSize="2.6" fill="rgba(232, 199, 123, 0.6)"
                      letterSpacing="0.18em">a Thursday, just past nine.</text>
                {/* Ornaments */}
                <g fill="#C5A05E" opacity="0.55">
                  <circle cx="14" cy="50" r="0.6" />
                  <circle cx="18" cy="50" r="0.4" />
                  <circle cx="22" cy="50" r="0.6" />
                  <circle cx="78" cy="50" r="0.6" />
                  <circle cx="82" cy="50" r="0.4" />
                  <circle cx="86" cy="50" r="0.6" />
                </g>
              </g>
            </svg>
            <div className="book-plate__caption">
              <small>Plate I · Frontispiece</small>
              The day the list began
            </div>
          </div>
          <div className="book__folio book__folio--right">— 10 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter II — Days, counted
   ════════════════════════════════════════════════════════════ */

// Wired plate for Chapter II — live count from CONFIG.anchorDate.
// Stays in sync via V2.useDays (which recomputes every minute).
function DaysPlate() {
  const days = V2.useDays();
  const hours = Math.floor(days * 24);
  const minutes = Math.floor(days * 24 * 60);
  const years = (days / 365.25).toFixed(2);
  return (
    <div className="days-plate">
      <div className="days-plate__numeral">{days.toLocaleString()}</div>
      <div className="days-plate__label">days, and counting.</div>
      <div className="days-plate__rule" />
      <div className="days-plate__grid">
        <div className="days-plate__cell">
          <div className="days-plate__cell-val">{hours.toLocaleString()}</div>
          <div className="days-plate__cell-lbl">Hours</div>
        </div>
        <div className="days-plate__cell">
          <div className="days-plate__cell-val">{minutes.toLocaleString()}</div>
          <div className="days-plate__cell-lbl">Minutes</div>
        </div>
        <div className="days-plate__cell">
          <div className="days-plate__cell-val">{years}</div>
          <div className="days-plate__cell-lbl">Years</div>
        </div>
      </div>
    </div>
  );
}

function ChapterDays() {
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="II" title="Days," titleEm="counted." titleAr="أيام، معدودة." />

          <div className="book-body">
            <p>
              The first thing I did, on the morning after, was a small thing I would do
              again every morning for the rest of my life. I counted. Not deliberately.
              Time had simply rearranged itself around a new origin point, and I had been
              given, without asking, a new way to measure.
            </p>
            <p>
              There is something old-fashioned about counting days. Lovers used to do it
              on calendars, with a pen, before the calendars learned to do it themselves.
              I am not sure the counting is for anything other than itself. To say:
              <em> we have made it this far. </em>To say: <em>we have made it further than that.</em>
            </p>
            <p>
              What follows, opposite, is the count as of this writing. By the time you
              read it, the count will be wrong. That is the point.
            </p>
          </div>

          <div className="book-margin" style={{ top: 200 }}>
            <small>The smallest unit</small>
            <em>a second.</em> The largest, also a second — provided you are paying enough
            attention.
          </div>
          <div className="book-margin" style={{ top: 420 }}>
            <small>Arabic, again</small>
            <em>عدّ </em> means both <em>to count</em> and <em>to consider.</em>
          </div>

          <div className="book-footnote">
            * The count begins at midnight Damascus time on October 5, 2023. The choice of
            timezone was yours; I deferred.
          </div>

          <div className="book__folio book__folio--left">— 17 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <DaysPlate />
            <div className="days-plate__caption">
              <small>Plate II · The count</small>
              accurate to this very moment
            </div>
          </div>
          <div className="book__folio book__folio--right">— 18 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter III — Reasons
   ════════════════════════════════════════════════════════════ */

function ChapterReasons() {
  const reasons = [
    'The way your laugh fills a room before you do.',
    'How safe the world becomes when you are next to me.',
    'The fact that you remember every story I forget.',
    'The small kindness in how you ask if I have eaten.',
    'Your stubborn good faith in everyone you love.',
    'The seriousness with which you take small things.',
    'The way you say my name, twice, when you mean it.',
    'Your handwriting, which has not changed since we met.',
    'How you cry at songs in languages you do not speak.',
    'That you let me finish my sentence, every time.',
    'Your hand, in mine, in front of strangers.',
    'The Tuesday on your balcony, repeated, forever.',
  ];
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="III" title="Reasons," titleEm="numbered." titleAr="أسباب، مرقّمة." />

          <p className="book-subhead">
            An incomplete enumeration. I will keep adding to it on the inside back cover.
          </p>
          <div style={{ height: 22 }} />

          <div className="reasons-list">
            {reasons.map((r, i) => (
              <div key={i} className="reasons-list__item">
                <span className="reasons-list__num">№ {String(i + 1).padStart(2, '0')}.</span>
                <span className="reasons-list__text">{r}</span>
              </div>
            ))}
          </div>

          <div className="book-footnote" style={{ marginTop: 24 }}>
            * Reasons not yet in the list: ones I have not figured out how to say. They
            outnumber the ones I have.
          </div>

          <div className="book__folio book__folio--left">— 25 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <div className="reasons-featured">
              <div className="reasons-featured__num">№ 07  ·  one to keep</div>
              <div className="reasons-featured__quote">
                "The way you say my name, twice, when you mean it."
              </div>
              <div className="reasons-featured__quote-ar">
                «الطريقة التي تنادينني بها باسمي، مرّتين، حين تعنين ذلك.»
              </div>
              <div className="reasons-featured__sig">Featured plate · turn the page for more</div>
            </div>
          </div>
          <div className="book__folio book__folio--right">— 26 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter IV — Letters to you
   ════════════════════════════════════════════════════════════ */

function ChapterLetters() {
  const others = [
    { num: 'II',  title: 'A small thing, in writing.', date: 'March 2, 2024',
      preview: 'You laughed at my joke about the moon last Thursday. I have been thinking about it ever since…' },
    { num: 'III', title: 'On the future I want.',      date: 'August 27, 2024',
      preview: 'I do not want anything elaborate. A kitchen with morning light. The sound of you on the phone in the next room…' },
    { num: 'IV',  title: 'After the argument.',        date: 'October 11, 2024',
      preview: 'I am sorry. I was not listening; I was waiting to answer. There is a difference. I forget it sometimes…' },
    { num: 'V',   title: 'The garden, again.',         date: 'December 18, 2024',
      preview: 'You wore the green coat. The fountain was frozen at the edges. I almost said it, then. I should have said it then…' },
    { num: 'VI',  title: 'Three things, late.',        date: 'February 9, 2025',
      preview: 'It is nearly two in the morning. I cannot sleep. I want to tell you three things that I should have already told you…' },
    { num: 'VII', title: 'For when you read this last.', date: 'May 5, 2025',
      preview: 'I do not know which letter you will find last. So I am writing this one assuming it will be this one…' },
  ];

  return (
    <div className="book">
      <div className="book__spread">
        {/* Left page — a full letter (Letter I) */}
        <div className="book__page" style={{ position: 'relative' }}>
          <div className="book-chapter-num">Chapter IV  ·  Letter I of XII</div>
          <h2 className="book-chapter-title" style={{ fontSize: 38 }}>
            For when you <em>doubt this.</em>
          </h2>
          <div className="book-chapter-rule" />

          <div className="letter-page">
            <div className="letter-page__date">November 14, 2023</div>
            <div className="letter-page__salutation">My Duha,</div>
            <div className="letter-page__body">
              <p>
                It has been six weeks. Six. I keep wanting to write that down so that
                I will believe it. I keep failing to.
              </p>
              <p>
                I am writing this not because anything is wrong, but because everything,
                for once, is not. I have noticed, in myself, a quiet new instinct — a
                small turning, every time something happens, toward you. The instinct
                arrived without my asking. I think you put it there.
              </p>
              <p>
                On the days the world is too loud — and I know there will be days like
                that — remember this letter exists. Remember I picked you on the quietest
                morning, with no audience. I would pick you again.
              </p>
              <p>
                I will pick you, again.
              </p>
            </div>
            <div className="letter-page__sig">
              <div className="letter-page__sig-name">Mo</div>
              <div className="letter-page__sig-meta">— Mohammed, the one who waited</div>
            </div>
          </div>

          <div className="letter-seal">M</div>
          <div className="book__folio book__folio--left">— 33 —</div>
        </div>

        <div className="book__gutter" />

        {/* Right page — table of the other letters */}
        <div className="book__page" style={{ paddingTop: 60 }}>
          <div className="letter-toc-head">Other letters, in order.</div>
          <div className="letter-toc-sub">Eleven more · sealed and saved</div>

          <div className="letter-toc-list">
            {others.map((l, i) => (
              <div key={i} className="letter-toc-row">
                <div className="letter-toc-row__top">
                  <span className="letter-toc-row__num">{l.num}.</span>
                  <span className="letter-toc-row__title">{l.title}</span>
                  <span className="letter-toc-row__date">{l.date}</span>
                </div>
                <div className="letter-toc-row__preview">{l.preview}</div>
              </div>
            ))}
          </div>

          <div className="book-flourish" style={{ marginTop: 22 }}>
            <div className="book-flourish__line" />
            <div className="book-flourish__diamond" />
            <div className="book-flourish__line" />
          </div>
          <p style={{ fontFamily: "'EB Garamond', serif", fontStyle: 'italic', fontSize: 12, color: 'rgba(27, 42, 78, 0.55)', textAlign: 'center', marginTop: 6 }}>
            New letters added as they are written. Both of us may write them.
          </p>

          <div className="book__folio book__folio--right">— 34 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter V — Voices, on the days
   ════════════════════════════════════════════════════════════ */

function ChapterVoices() {
  const notes = [
    { t: 'For your hardest days.',     l: '2:18', d: 'March 14, 2024' },
    { t: "Today's note.",              l: '0:41', d: 'May 9, 2024' },
    { t: 'When you miss home.',        l: '3:02', d: 'January 22, 2024' },
    { t: 'The thing I forgot to say.', l: '1:07', d: 'April 3, 2024' },
    { t: 'On a Tuesday.',              l: '0:58', d: 'February 27, 2024' },
    { t: 'The man with the jasmine.',  l: '1:24', d: 'June 12, 2024' },
    { t: 'A small thing, in voice.',   l: '1:33', d: 'May 2, 2024' },
  ];
  const wave = (n) => Array.from({ length: 28 }, (_, i) => ((i * 31 + n * 17) % 18) + 4);

  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="V" title="Voices, on the" titleEm="days." titleAr="أصوات، في الأيام." />

          <p className="book-subhead">
            For when the words on the page are not enough. Press your thumb to the spine
            and listen.
          </p>
          <div style={{ height: 22 }} />

          <div className="voice-typeset">
            {notes.map((n, i) => (
              <div key={i} className="voice-typeset__row">
                <div className="voice-typeset__num">№ {String(i + 1).padStart(2, '0')}</div>
                <div>
                  <div className="voice-typeset__title">{n.t}</div>
                  <div className="voice-typeset__meta">
                    <span>{n.l}</span><span>·</span><span>{n.d}</span>
                  </div>
                  <div className="voice-typeset__wave">
                    {wave(i).map((h, j) => <span key={j} style={{ height: `${(h / 22) * 100}%` }} />)}
                  </div>
                </div>
              </div>
            ))}
          </div>

          <div className="book__folio book__folio--left">— 49 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <div className="voice-feature">
              <div className="voice-feature__disc">
                <div className="voice-feature__center">▶</div>
              </div>
              <div className="voice-feature__title">"On a Tuesday."</div>
              <div className="voice-feature__meta">№ 05  ·  0:58  ·  February 27, 2024</div>

              <div style={{ marginTop: 32, fontFamily: "'EB Garamond', serif", fontStyle: 'italic', fontSize: 13, color: 'rgba(232, 199, 123, 0.7)', maxWidth: 360, textAlign: 'center', lineHeight: 1.6 }}>
                "I am at the desk. The rain has not stopped. I just wanted to say your
                name out loud, in this room, before I forgot the sound of it."
              </div>
            </div>
          </div>
          <div className="book__folio book__folio--right">— 50 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter VI — Plates: a year in frames
   ════════════════════════════════════════════════════════════ */

function MiniPlate({ kind, num, caption }) {
  const palettes = {
    sunset:   { sky: '#f4c098', glow: '#e88c5b', land: '#3a1f2a' },
    city:     { sky: '#2a3554', glow: '#5a6b8c', land: '#0d1426' },
    garden:   { sky: '#3a5240', glow: '#5a7858', land: '#1a2818' },
    sea:      { sky: '#5a96b8', glow: '#7ab0c8', land: '#1a384a' },
    portrait: { sky: '#3a2a38', glow: '#5a3a4a', land: '#2a1a28' },
    night:    { sky: '#0d1240', glow: '#252c5c', land: '#020514' },
  };
  const p = palettes[kind] || palettes.sunset;
  return (
    <div className="plate">
      <svg className="plate__svg" viewBox="0 0 200 150" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id={`mp-${num}-${kind}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={p.sky} />
            <stop offset="55%" stopColor={p.glow} />
            <stop offset="100%" stopColor={p.land} />
          </linearGradient>
        </defs>
        <rect width="200" height="150" fill={`url(#mp-${num}-${kind})`} />
        {kind === 'sunset' && <circle cx="140" cy="75" r="22" fill={p.glow} opacity="0.85" />}
        {kind === 'city' && (
          <>
            <rect x="20" y="80" width="14" height="50" fill={p.land} />
            <rect x="40" y="60" width="12" height="70" fill={p.land} />
            <rect x="58" y="70" width="16" height="60" fill={p.land} />
            <rect x="80" y="50" width="14" height="80" fill={p.land} />
            <rect x="100" y="75" width="18" height="55" fill={p.land} />
            <rect x="125" y="65" width="14" height="65" fill={p.land} />
            <rect x="145" y="80" width="20" height="50" fill={p.land} />
            <rect x="170" y="70" width="14" height="60" fill={p.land} />
          </>
        )}
        {kind === 'sea' && <path d="M 0 95 Q 50 90 100 95 T 200 97 L 200 150 L 0 150 Z" fill={p.land} opacity="0.85" />}
        {kind === 'garden' && (
          <>
            <ellipse cx="40" cy="120" rx="30" ry="18" fill={p.land} opacity="0.7" />
            <ellipse cx="120" cy="125" rx="40" ry="20" fill={p.land} opacity="0.85" />
            <ellipse cx="175" cy="115" rx="25" ry="15" fill={p.land} opacity="0.7" />
          </>
        )}
        {kind === 'portrait' && (
          <>
            <circle cx="100" cy="60" r="22" fill="#c89898" opacity="0.7" />
            <ellipse cx="100" cy="135" rx="55" ry="35" fill="#c89898" opacity="0.4" />
          </>
        )}
        {kind === 'night' && (
          <>
            {Array.from({ length: 14 }).map((_, i) => (
              <circle key={i} cx={(i * 17 + 7) % 200} cy={(i * 11 + 5) % 70} r="0.8" fill="#d4b86a" opacity="0.7" />
            ))}
            <path d="M 0 110 Q 100 95 200 105 L 200 150 L 0 150 Z" fill={p.land} />
          </>
        )}
      </svg>
      <div className="plate__cap">
        <small>Plate VI · {num}</small>
        {caption}
      </div>
    </div>
  );
}

function ChapterPlates() {
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="VI" title="A year, in" titleEm="frames." titleAr="سنة، في صور." />

          <div className="book-body">
            <p>
              I have never been a good photographer. I take too many; I look at them too
              rarely. But this year is different. I have started to feel, around the
              edges of every ordinary day, the small private suspicion that — <em>this
              one, also, will be missed later.</em> So I photograph it.
            </p>
            <p>
              The plates that follow are not arranged chronologically. They are arranged
              by the order in which I miss them. The Corniche first; the kitchen at
              Eid second; the garden in December; the night the highway emptied. I will
              keep adding to this gallery for as long as we are accruing days.
            </p>
            <p>
              Each plate has a caption. Each caption has been written twice — once when
              the photograph was taken, and again now, when I have had longer to think
              about what it was.
            </p>
          </div>

          <div className="book-margin" style={{ top: 200 }}>
            <small>Plate VI · 02</small>
            <em>was taken from inside the car</em>, with the window down, while you were
            looking the other way.
          </div>
          <div className="book-margin" style={{ top: 420 }}>
            <small>The captions</small>
            <em>were Duha's.</em> The mistakes are mine.
          </div>

          <div className="book-footnote">
            * The image opposite is a contact sheet. Full plates begin on page 62.
          </div>

          <div className="book__folio book__folio--left">— 61 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <div className="plates-spread">
              <MiniPlate kind="sunset"   num="01" caption="Sunset at the Corniche." />
              <MiniPlate kind="city"     num="02" caption="Old city, the morning after." />
              <MiniPlate kind="sea"      num="03" caption="Sea, after the storm." />
              <MiniPlate kind="garden"   num="04" caption="The garden in December." />
            </div>
            <div className="book-plate__caption">
              <small>Plate VI · contact sheet</small>
              Four of the year's eighty-seven
            </div>
          </div>
          <div className="book__folio book__folio--right">— 62 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter VII — The Bell  (notifications)
   ════════════════════════════════════════════════════════════ */

function ChapterBell() {
  // WIRED to live notifications. Form sends a real push to the OTHER person.
  const notifs = V2.useNotifications();
  const pushState = V2.usePushToggle();
  const [title, setTitle] = useStateFull('');
  const [body, setBody] = useStateFull('');
  const [sending, setSending] = useStateFull(false);
  const [justSent, setJustSent] = useStateFull(false);

  const log = [...notifs]
    .sort((a, b) => (b.sentAt || b.addedAt || 0) - (a.sentAt || a.addedAt || 0))
    .slice(0, 7)
    .map(n => ({
      who: (n.sentBy || n.addedBy) === 'mo' ? 'Mo' : 'Duha',
      msgTitle: n.title || '(untitled)',
      msg: n.body || '',
      when: V2.timeAgo(n.sentAt || n.addedAt),
    }));

  const onRing = async () => {
    if (!title.trim() && !body.trim()) return;
    setSending(true);
    try {
      await V2.sendBell({ title, body });
      setTitle(''); setBody('');
      setJustSent(true);
      setTimeout(() => setJustSent(false), 2400);
    } catch (e) {
      alert('Could not send. Check your connection and try again.');
    }
    setSending(false);
  };
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="VII" title="The" titleEm="Bell." titleAr="الجرس." />

          <div className="book-body">
            <p>
              A bell, in this house, is not for emergencies. It is for the smaller, more
              important kind of signal. The <em>thinking of you</em> kind. The <em>the
              kettle is whistling</em> kind. The <em>look out the window, please</em> kind.
              There is no other bell like it; there could not be. It is private to us.
            </p>
            <p>
              On the page opposite, the device is sketched as it presently stands. It is
              extremely simple. A title. A message. A small bronze button. The bell
              rings on the other person's phone, regardless of where in the world that
              phone is. It rings softly. We can mute it; we never do.
            </p>
            <p>
              Below the device, a log of recent rings. Yours, mine. They are not very
              important, considered one at a time. Considered together, they are the
              sound of a house being lived in.
            </p>
          </div>

          <div className="book-margin" style={{ top: 220 }}>
            <small>On the sound</small>
            <em>it is the same note</em> as the chime over the door of the café where we
            first met. I did not tell you. I am telling you now.
          </div>

          <div className="book-footnote">
            * The bell does not ring between midnight and seven in the morning, by mutual
            agreement. Exceptions are permitted.
          </div>

          <div className="book__folio book__folio--left">— 75 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <div className="bell-device">
              <div className="bell-device__head">
                <div className="bell-device__head-title">Ring the bell.</div>
                <div className="bell-device__head-meta">Plate VII · the device</div>
              </div>

              <div className="bell-compose">
                <div className="bell-compose__row">
                  <div className="bell-compose__lbl">Title</div>
                  <input className="bell-compose__input"
                         value={title} onChange={e => setTitle(e.target.value)}
                         placeholder="Thinking of you ✦" maxLength={60} />
                </div>
                <div className="bell-compose__row">
                  <div className="bell-compose__lbl">Message</div>
                  <input className="bell-compose__input"
                         value={body} onChange={e => setBody(e.target.value)}
                         placeholder="A small thing, for the bell —" maxLength={200} />
                </div>
                <button className="bell-compose__send"
                        onClick={onRing}
                        disabled={sending || (!title.trim() && !body.trim())}>
                  {sending ? 'Ringing…' : justSent ? 'Rang ♥' : 'Ring  ✦'}
                </button>
                {pushState.supported && (
                  <button onClick={pushState.toggle}
                          style={{ marginTop: 12, background: 'none',
                                   border: '1px solid #8b6f47', color: '#6b4423',
                                   padding: '6px 14px', borderRadius: 999, fontSize: 11,
                                   letterSpacing: '0.05em', cursor: 'pointer',
                                   fontFamily: "'EB Garamond', serif" }}>
                    {pushState.subscribed
                      ? '🔔 Notifications: ON (tap to disable)'
                      : '🔕 Notifications: OFF (tap to enable)'}
                  </button>
                )}
              </div>

              <div className="bell-log">
                <div className="bell-log__title">Recent rings</div>
                {log.map((r, i) => (
                  <div key={i} className="bell-log__row">
                    <div className="bell-log__who">{r.who}</div>
                    <div className="bell-log__msg">
                      <span className="bell-log__msg-title">{r.msgTitle}</span>
                      {r.msg}
                    </div>
                    <div className="bell-log__when">{r.when}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="book__folio book__folio--right">— 76 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Chapter VIII — The house we are building
   ════════════════════════════════════════════════════════════ */

function HouseRoof({ kind }) {
  // Three roof silhouettes — gable, hip, dome — to feel architectural
  if (kind === 'gable') {
    return (
      <svg viewBox="0 0 80 50">
        <path d="M 8 50 L 40 6 L 72 50 Z" fill="none" stroke="#C5A05E" strokeWidth="1" />
        <line x1="20" y1="50" x2="60" y2="50" stroke="#C5A05E" strokeWidth="0.6" />
        <circle cx="40" cy="30" r="2" fill="none" stroke="#C5A05E" strokeWidth="0.6" />
      </svg>
    );
  }
  if (kind === 'hip') {
    return (
      <svg viewBox="0 0 80 50">
        <path d="M 14 50 L 28 12 L 52 12 L 66 50 Z" fill="none" stroke="#C5A05E" strokeWidth="1" />
        <line x1="28" y1="12" x2="52" y2="12" stroke="#C5A05E" strokeWidth="0.6" />
        <rect x="36" y="28" width="8" height="14" fill="none" stroke="#C5A05E" strokeWidth="0.5" />
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 80 50">
      <path d="M 14 50 Q 40 -4 66 50 Z" fill="none" stroke="#C5A05E" strokeWidth="1" />
      <circle cx="40" cy="50" r="1.5" fill="#C5A05E" />
      <line x1="40" y1="6" x2="40" y2="48" stroke="#C5A05E" strokeWidth="0.4" strokeDasharray="1 2" />
    </svg>
  );
}

function ChapterHouse() {
  const cols = [
    { num: 'I', title: 'This year', roof: 'gable', items: [
      { en: 'Spend a weekend in the old city.',       ar: 'نقضي عطلة في المدينة القديمة.' },
      { en: 'Start the Sunday breakfast ritual.',     ar: 'نبدأ تقليد فطور الأحد.' },
      { en: 'Read the same book at the same time.',   ar: 'نقرأ نفس الكتاب في نفس الوقت.' },
      { en: 'Frame the first photograph.',            ar: 'نُؤطّر أول صورة.' },
    ]},
    { num: 'II', title: 'Next five years', roof: 'hip', items: [
      { en: 'Two visas, one passport queue.',         ar: 'تأشيرتان، وطابور جوازات واحد.' },
      { en: 'A kitchen with morning light.',          ar: 'مطبخ بضوء الصباح.' },
      { en: 'Northern lights, on a bench, together.', ar: 'الشفق القطبي، على مقعد، معاً.' },
      { en: 'The garden, properly planted.',          ar: 'الحديقة، مزروعةً كما يجب.' },
    ]},
    { num: 'III', title: 'Our forever', roof: 'dome', items: [
      { en: 'A door that always opens onto you.',     ar: 'باب يُفتح دائماً عليكِ.' },
      { en: 'The same vows, at every age.',           ar: 'نفس الوعود، في كل عمر.' },
      { en: 'A long, ordinary life.',                 ar: 'حياة طويلة، عادية.' },
    ]},
  ];
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page" style={{ paddingRight: 150 }}>
          <ChapterHead num="VIII" title="The house we are" titleEm="building." titleAr="البيت الذي نبنيه." />

          <div className="book-body">
            <p>
              We have not bought a house. We have not signed anything; we have not
              picked a city. And yet, somewhere in the way we talk, we have started to
              build one. The conversation is, by now, well underway. The plans are in
              two languages and several handwritings. The materials are mostly small.
            </p>
            <p>
              On the page opposite, three elevations: <em>this year</em>, <em>the next
              five</em>, <em>our forever</em>. Each column is a wall of the same house.
              They are not separate buildings; they are different aspects of the same
              one. We add to them constantly. We finish, occasionally.
            </p>
            <p>
              Nothing on these walls is binding. Things move between columns. Things
              get crossed off, then added back. The point of the document is not the
              document; the point is that we keep writing it together.
            </p>
          </div>

          <div className="book-margin" style={{ top: 220 }}>
            <small>The house</small>
            <em>does not, in fact, exist.</em> It exists.
          </div>

          <div className="book-footnote">
            * The elevations were drawn by Duha. The roofline of "our forever" was a
            compromise.
          </div>

          <div className="book__folio book__folio--left">— 83 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page" style={{ padding: 36 }}>
          <div className="book-plate">
            <div className="house-elevations">
              {cols.map((c, i) => (
                <div key={i} className="house-col">
                  <div className="house-col__roof"><HouseRoof kind={c.roof} /></div>
                  <div className="house-col__num">{c.num}</div>
                  <div className="house-col__title">{c.title}</div>
                  <div className="house-col__list">
                    {c.items.map((it, j) => (
                      <div key={j} className="house-col__item">
                        <div className="house-col__bullet" />
                        <div>
                          <div>{it.en}</div>
                          <div className="house-col__item-ar">{it.ar}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
            <div className="book-plate__caption">
              <small>Plate VIII · three elevations</small>
              the house, in section
            </div>
          </div>
          <div className="book__folio book__folio--right">— 84 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Closing spread — Chapter IX, Forever yours
   ════════════════════════════════════════════════════════════ */

function ChapterClosing() {
  return (
    <div className="book">
      <div className="book__spread">
        <div className="book__page">
          <div className="closing-page">
            <div className="closing-page__mark">Chapter IX  ·  the last page (for now)</div>
            <Flourish />
            <div className="closing-page__line">
              Forever yours, Mo
            </div>
            <div className="closing-page__line" style={{ marginTop: 10, opacity: 0.8 }}>
              ✦ Always mine, Duha
            </div>
            <div className="closing-page__line-ar">
              إلى الأبد لكِ، محمد ✦ دائماً لي، ضحى
            </div>
            <div style={{ height: 28 }} />
            <div className="closing-page__seal">M&amp;D</div>
            <Flourish />
            <p className="closing-page__colophon">
              This volume continues — every letter, every photograph, every ring of the
              bell adds a page. The book is not finished. It will not be.
            </p>
          </div>
          <div className="book__folio book__folio--left">— 95 —</div>
        </div>

        <div className="book__gutter" />

        <div className="book__page">
          <div className="colophon">
            <div className="colophon__title">Colophon</div>
            <p className="colophon__body">
              Begun on the morning of <em>5 October 2023</em>, somewhere between a
              coffee shop and an apartment with a balcony.
              <br/><br/>
              Set in <em>EB Garamond</em>; ornaments in gilt;
              binding by hand. Both languages, by mutual agreement,
              of equal weight.
            </p>
            <div className="colophon__list">
              <div>Written, mostly, by Mo</div>
              <div>Edited, kindly, by Duha</div>
              <div>Bound, privately, for two</div>
            </div>
            <div style={{ marginTop: 36 }}><Flourish /></div>
            <div style={{ marginTop: 16, fontFamily: "'EB Garamond', serif", fontStyle: 'italic', fontSize: 11, letterSpacing: '0.32em', textTransform: 'uppercase', color: 'rgba(27, 42, 78, 0.5)' }}>
              Volume I  ·  2023 —
            </div>
          </div>
          <div className="book__folio book__folio--right">— 96 —</div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   Full book — stacked spreads
   ════════════════════════════════════════════════════════════ */

function FullBook() {
  const spreads = [
    { label: 'Front matter',         comp: <FullCover /> },
    { label: 'Chapter I',            comp: <ChapterMeet /> },
    { label: 'Chapter II',           comp: <ChapterDays /> },
    { label: 'Chapter III',          comp: <ChapterReasons /> },
    { label: 'Chapter IV',           comp: <ChapterLetters /> },
    { label: 'Chapter V',            comp: <ChapterVoices /> },
    { label: 'Chapter VI',           comp: <ChapterPlates /> },
    { label: 'Chapter VII',          comp: <ChapterBell /> },
    { label: 'Chapter VIII',         comp: <ChapterHouse /> },
    { label: 'Chapter IX · Closing', comp: <ChapterClosing /> },
  ];
  return (
    <div className="book-stack" data-screen-label="The Bound Book">
      <FloatingControlsBook />
      <div className="book-stack__intro">
        Direction A · The Bound Book — Volume I, in {spreads.length} spreads.
      </div>
      {spreads.map((s, i) => (
        <div key={i} className="book-stack__spread" data-screen-label={s.label}>
          <div className="book-stack__label">{s.label}</div>
          {s.comp}
        </div>
      ))}
    </div>
  );
}

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