/* Direction B — "Quiet Scrapbook"
   Now chapter-based: composed editorial scrolling through 8 chapters.
   Polaroids align to a soft grid. Handwritten notes are accents only. */

const { useRef: useRefB, useEffect: useEffectB } = React;

function DirB_Opening({ registerSection }) {
  const m = window.MEMORIES;
  const ref = useRefB(null);
  useEffectB(() => {
    if (ref.current && registerSection) registerSection('__opening', ref.current);
  }, []);
  return (
    <section ref={ref} data-chapter-id="__opening" style={{ position: 'relative', minHeight: 780, padding: '120px 110px 100px', display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 80, alignItems: 'center' }}>
      <div>
        <Eyebrow style={{ marginBottom: 30 }}>{m.opening.eyebrow}</Eyebrow>
        <h1 style={{ fontFamily: 'var(--display)', fontSize: 88, lineHeight: 0.98, margin: '0 0 50px', letterSpacing: '-0.018em', fontWeight: 400, fontStyle: 'italic' }}>
          a year,<br/>in pieces.
        </h1>
        <div className="read-col" style={{ fontSize: 17 }}>
          {m.opening.body.map((p, i) => <p key={i} style={{ margin: '0 0 12px' }}>{p}</p>)}
        </div>
        <div style={{ marginTop: 36, display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 40, height: 1, background: 'var(--ink-faded)' }} />
          <div style={{ fontFamily: 'var(--hand)', fontSize: 30, color: 'var(--ink-soft)' }}>{m.opening.signoff}</div>
        </div>
      </div>
      <div style={{ position: 'relative', justifySelf: 'center' }}>
        <Polaroid rotate={2} tape tapeAt="tc" size="large">
          <PhotoPlaceholder label="us, last december" w={300} h={380} />
          <div className="caption" style={{ fontSize: 18 }}>chapter one.</div>
        </Polaroid>
      </div>
      <div style={{ position: 'absolute', bottom: 36, left: 110, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.3em', color: 'var(--ink-faded)' }}>
        OPENING
      </div>
      <div style={{ position: 'absolute', bottom: 36, right: 110, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.3em', color: 'var(--ink-faded)' }}>
        SCROLL ↓
      </div>
    </section>
  );
}

// ── Chapter ───────────────────────────────────────────────
function DirB_Chapter({ chapter, registerSection }) {
  const ref = useRefB(null);
  useEffectB(() => {
    if (ref.current && registerSection) registerSection(chapter.id, ref.current);
  }, [chapter.id]);

  if (chapter.isFinal) return <DirB_Final chapter={chapter} sectionRef={ref} />;

  return (
    <section ref={ref} data-chapter-id={chapter.id} style={{ position: 'relative', padding: '20px 0 80px' }}>
      <div className="chapter-marker">
        <span>{chapter.eyebrow}</span>
        <span className="roman">— {chapter.roman} —</span>
        <span>♪ {chapter.track.title} · {chapter.track.artist}</span>
      </div>

      {/* chapter title spread */}
      <Reveal>
        <div style={{ padding: '80px 110px 30px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center', minHeight: 360 }}>
          <div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.3em', color: 'var(--ink-faded)', marginBottom: 16 }}>
              {chapter.place}
            </div>
            <h2 style={{ fontFamily: 'var(--display)', fontSize: 64, lineHeight: 1.02, margin: '0 0 24px', fontWeight: 400, fontStyle: 'italic', letterSpacing: '-0.01em' }}>
              {chapter.title}
            </h2>
            <div style={{ width: 36, height: 1, background: 'var(--ink-faded)', margin: '0 0 22px' }} />
            {chapter.notes && chapter.notes[0] && (
              <div style={{ fontFamily: 'var(--serif)', fontSize: 18, lineHeight: 1.6, color: 'var(--ink)', maxWidth: 380 }}>
                {chapter.notes[0]}
              </div>
            )}
            {chapter.ticket && <Ticket rotate={-1.5} style={{ marginTop: 22 }}>{chapter.ticket}</Ticket>}
          </div>
          <div style={{ justifySelf: 'center' }}>
            {chapter.photos[0] && (
              <Polaroid rotate={chapter.photos[0].rotate * 0.4} tape tapeAt="tc" size="large">
                <PhotoPlaceholder label={chapter.photos[0].label} w={chapter.photos[0].w} h={chapter.photos[0].h} src={chapter.photos[0].src} />
              </Polaroid>
            )}
          </div>
        </div>
      </Reveal>

      {/* photo grid (remaining photos) */}
      <DirB_PhotoGrid photos={chapter.photos.slice(1)} />

      {/* second note */}
      {chapter.notes && chapter.notes[1] && (
        <Reveal>
          <div style={{ padding: '20px 110px 40px', textAlign: 'center' }}>
            <Note size={32} rotate={-1} style={{ maxWidth: 600, margin: '0 auto', lineHeight: 1.2 }}>
              {chapter.notes[1]}
            </Note>
          </div>
        </Reveal>
      )}

      <Stitch style={{ margin: '20px 110px 0' }} />
    </section>
  );
}

function DirB_PhotoGrid({ photos }) {
  if (!photos || !photos.length) return null;

  // Group consecutive photos sharing a `group` id; emit special units for `pairWith` and comments.
  const units = [];
  const seen = new Set();
  photos.forEach((p, i) => {
    if (seen.has(i)) return;
    if (p.group) {
      const gp = photos.filter((q, j) => q.group === p.group && (seen.add(j), true));
      units.push({ kind: 'group', photos: gp });
    } else {
      seen.add(i);
      units.push({ kind: 'solo', photo: p });
    }
  });

  return (
    <Reveal>
      <div style={{ padding: '40px 110px 30px', display: 'flex', flexDirection: 'column', gap: 60 }}>
        {units.map((u, ui) => {
          if (u.kind === 'group') {
            return (
              <div key={ui} style={{ display: 'flex', flexWrap: 'wrap', gap: '32px 40px', justifyContent: 'center', alignItems: 'flex-end' }}>
                {u.photos.map((p, i) => (
                  <div key={i} style={{ position: 'relative', marginTop: i % 2 === 1 ? 20 : 0 }}>
                    <Polaroid rotate={p.rotate * 0.4} size="small" tape={i === 0} tapeAt="tc">
                      <PhotoPlaceholder label={p.label} w={p.w} h={p.h} src={p.src} />
                    </Polaroid>
                    {p.comment && <DirB_Comment text={p.comment} side={i % 2 === 0 ? 'right' : 'left'} />}
                  </div>
                ))}
              </div>
            );
          }
          const p = u.photo;
          if (p.pairWith) {
            return (
              <div key={ui} style={{ display: 'flex', flexWrap: 'wrap', gap: '40px 60px', justifyContent: 'center', alignItems: 'center' }}>
                <Polaroid rotate={p.pairWith.rotate * 0.4} size="small" tape tapeAt="tl">
                  <PhotoPlaceholder label={p.pairWith.label} w={p.pairWith.w} h={p.pairWith.h} src={p.pairWith.src} />
                  <div className="caption" style={{ fontSize: 14 }}>{p.pairWith.sub}</div>
                </Polaroid>
                <Note size={22} rotate={-3} style={{ color: 'var(--ink-soft)', maxWidth: 140 }}>then · now</Note>
                <div style={{ position: 'relative' }}>
                  <Polaroid rotate={p.rotate * 0.4} size="small" tape tapeAt="tr">
                    <PhotoPlaceholder label={p.label} w={p.w} h={p.h} src={p.src} />
                  </Polaroid>
                  {p.comment && <DirB_Comment text={p.comment} side="right" />}
                </div>
              </div>
            );
          }
          return (
            <div key={ui} style={{ display: 'flex', justifyContent: 'center' }}>
              <div style={{ position: 'relative' }}>
                <Polaroid rotate={p.rotate * 0.35} size="small" tape={ui % 3 === 0} tapeAt="tc">
                  <PhotoPlaceholder label={p.label} w={p.w} h={p.h} src={p.src} />
                </Polaroid>
                {p.comment && <DirB_Comment text={p.comment} side="right" />}
              </div>
            </div>
          );
        })}
      </div>
    </Reveal>
  );
}

function DirB_Comment({ text, side = 'right' }) {
  const isRight = side === 'right';
  return (
    <div style={{
      position: 'absolute',
      [isRight ? 'left' : 'right']: '100%',
      [isRight ? 'marginLeft' : 'marginRight']: 14,
      top: 22,
      width: 170,
      transform: `rotate(${isRight ? -2 : 2}deg)`,
      fontFamily: 'var(--hand)',
      fontSize: 20,
      color: 'var(--ink-soft)',
      lineHeight: 1.15,
      pointerEvents: 'none',
    }}>
      <span style={{ color: 'var(--rose)', marginRight: 4 }}>{isRight ? '←' : '→'}</span>
      {text}
    </div>
  );
}

function DirB_Final({ chapter, sectionRef }) {
  return (
    <section ref={sectionRef} data-chapter-id={chapter.id} style={{ position: 'relative', padding: '20px 0 130px' }}>
      <div className="chapter-marker">
        <span>{chapter.eyebrow}</span>
        <span className="roman">— {chapter.roman} —</span>
        <span>♪ {chapter.track.title} · {chapter.track.artist}</span>
      </div>
      <Reveal>
        <div style={{ padding: '110px 110px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center' }}>
          <div>
            <Eyebrow style={{ marginBottom: 22 }}>{chapter.place}</Eyebrow>
            <h2 style={{ fontFamily: 'var(--display)', fontSize: 68, lineHeight: 1.02, margin: '0 0 30px', fontWeight: 400, fontStyle: 'italic' }}>
              {chapter.title}
            </h2>
            <div style={{ width: 36, height: 1, background: 'var(--ink-faded)', margin: '0 0 28px' }} />
            <div className="read-col" style={{ fontSize: 18 }}>
              {chapter.body.map((p, i) => <p key={i} style={{ margin: '0 0 14px' }}>{p}</p>)}
            </div>
            <div style={{ marginTop: 32, fontFamily: 'var(--hand)', fontSize: 28, color: 'var(--ink-soft)' }}>{chapter.signoff}</div>
            <div style={{ fontFamily: 'var(--hand)', fontSize: 28, color: 'var(--ink-soft)' }}>{chapter.signoff2}</div>
          </div>
          <div style={{ justifySelf: 'center' }}>
            <Polaroid rotate={-1} size="large">
              <PhotoPlaceholder label={chapter.photos[0].label} w={chapter.photos[0].w} h={chapter.photos[0].h} src={chapter.photos[0].src} />
              <div className="caption" style={{ fontSize: 18 }}>still you.</div>
            </Polaroid>
          </div>
        </div>
      </Reveal>
    </section>
  );
}

function DirectionB({ tweaks, registerSection, fullViewport }) {
  const m = window.MEMORIES;
  if (fullViewport) {
    return (
      <div className={`memory-doc paper-bg memory-doc-full ${tweaks.grain ? 'grain-overlay' : ''}`}>
        <DirB_Opening registerSection={registerSection} />
        <Stitch style={{ margin: '0 110px' }} />
        {m.chapters.map((c) => (
          <DirB_Chapter key={c.id} chapter={c} registerSection={registerSection} />
        ))}
      </div>
    );
  }
  return (
    <div className={`memory-doc paper-bg ${tweaks.grain ? 'grain-overlay' : ''}`}>
      <div className="scroll-frame" data-scroll-frame="b">
        <DirB_Opening registerSection={registerSection} />
        <Stitch style={{ margin: '0 110px' }} />
        {m.chapters.map((c) => (
          <DirB_Chapter key={c.id} chapter={c} registerSection={registerSection} />
        ))}
      </div>
    </div>
  );
}

window.DirectionB = DirectionB;
