/* Direction A — \"Paper & Tape\"
   Now chapter-based: each chapter is a long scrolling section with a soundtrack.
   Layout is dense, layered, hand-tactile. */

const { useRef: useRefA, useEffect: useEffectA } = React;

function DirA_Opening({ registerSection }) {
  const m = window.MEMORIES;
  const ref = useRefA(null);
  useEffectA(() => {
    if (ref.current && registerSection) registerSection('__opening', ref.current);
  }, []);
  return (
    <section ref={ref} data-chapter-id="__opening" style={{ position: 'relative', minHeight: 760, padding: '90px 80px 110px', overflow: 'hidden' }}>
      <Eyebrow style={{ marginBottom: 22 }}>{m.opening.eyebrow}</Eyebrow>
      <h1 style={{ fontFamily: 'var(--display)', fontSize: 96, lineHeight: 0.98, margin: '0 0 38px', letterSpacing: '-0.015em', fontWeight: 400, maxWidth: 720 }}>
        a year, <span className="swash">in pieces</span>
      </h1>

      <div style={{ position: 'absolute', top: 110, right: 70, width: 360, height: 460 }}>
        <Polaroid rotate={6} tape tapeAt="tc" style={{ position: 'absolute', top: 0, right: 30 }}>
          <PhotoPlaceholder label="us, last december" w={220} h={260} />
        </Polaroid>
        <Polaroid rotate={-9} tape tapeAt="tl" style={{ position: 'absolute', top: 180, right: 130 }}>
          <PhotoPlaceholder label="that polaroid" w={180} h={210} />
        </Polaroid>
        <Sticker rotate={-12} style={{ top: 410, right: 60, fontSize: 28, color: 'var(--rose)' }}>♡</Sticker>
      </div>

      <div className="read-col" style={{ position: 'relative', zIndex: 2 }}>
        {m.opening.body.map((p, i) => <p key={i} style={{ margin: '0 0 14px' }}>{p}</p>)}
        <div style={{ marginTop: 30, fontFamily: 'var(--hand)', fontSize: 32, color: 'var(--ink-soft)' }}>{m.opening.signoff}</div>
      </div>

      <div style={{ position: 'absolute', bottom: 28, left: '50%', transform: 'translateX(-50%)', fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.24em', color: 'var(--ink-faded)', textAlign: 'center' }}>
        SCROLL<br/>↓
      </div>
      <Tape at="tl" color="yellow" size="long" style={{ top: 30, left: 60, transform: 'rotate(-8deg)' }} />
    </section>
  );
}

// ── A single chapter — long, scrollable, dense layered ───────────
function DirA_Chapter({ chapter, registerSection }) {
  const ref = useRefA(null);
  useEffectA(() => {
    if (ref.current && registerSection) registerSection(chapter.id, ref.current);
  }, [chapter.id]);

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

  const themeClass = chapter.theme ? `theme-${chapter.theme}` : '';

  return (
    <section
      ref={ref}
      data-chapter-id={chapter.id}
      data-screen-label={chapter.eyebrow}
      className={themeClass}
      style={{ position: 'relative', padding: '10px 0 28px' }}
    >
      {chapter.theme && <div className="theme-bg" />}
      {chapter.theme && window.ChapterOrnaments && <ChapterOrnaments theme={chapter.theme} />}
      {/* sticky chapter marker */}
      <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={{ position: 'relative', padding: '40px 60px 14px', minHeight: 220 }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.3em', color: 'var(--ink-faded)', marginBottom: 18 }}>
            {chapter.place}
          </div>
          <h2 style={{ fontFamily: 'var(--display)', fontSize: 78, lineHeight: 1, margin: '0 0 24px', fontWeight: 400, letterSpacing: '-0.015em', maxWidth: 760 }}>
            {chapter.title}
          </h2>
          {chapter.notes && chapter.notes[0] && (
            <Note size={30} rotate={-2} style={{ maxWidth: 520, color: 'var(--ink-soft)' }}>
              {chapter.notes[0]}
            </Note>
          )}
          {chapter.ticket && (
            <Ticket rotate={-2} style={{ marginTop: 24 }}>{chapter.ticket}</Ticket>
          )}
          <Tape at="tl" color="yellow" style={{ top: 50, left: 30, transform: 'rotate(-6deg)' }} />
        </div>
      </Reveal>

      {/* photo spread — varied layouts */}
      <DirA_PhotoSpread chapter={chapter} />

      {/* second note, if present */}
      {chapter.notes && chapter.notes[1] && (
        <Reveal>
          <div style={{ padding: '14px 60px 18px', textAlign: 'center' }}>
            <Note size={36} rotate={1.5} style={{ maxWidth: 580, margin: '0 auto', lineHeight: 1.15 }}>
              {chapter.notes[1]}
            </Note>
          </div>
        </Reveal>
      )}

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

// Photo spread — supports `group` (cluster of photos), `comment` (handwritten note next to photo),
// `pairWith` (comparison photo), `layout: 'hero' | 'wide' | 'final'`.
function DirA_PhotoSpread({ chapter }) {
  const photos = chapter.photos || [];

  // Build render units: groups become a single unit; ungrouped photos are solo units.
  const units = [];
  const seen = new Set();
  photos.forEach((p, i) => {
    if (seen.has(i)) return;
    if (p.divider) {
      seen.add(i);
      units.push({ kind: 'divider', label: p.divider, sub: p.dividerSub, end: p.dividerEnd, mini: p.dividerKind === 'mini' });
      return;
    }
    if (p.group) {
      const groupPhotos = photos.filter((q, j) => q.group === p.group && (seen.add(j), true));
      units.push({ kind: 'group', id: p.group, photos: groupPhotos });
    } else {
      seen.add(i);
      units.push({ kind: 'solo', photo: p });
    }
  });

  const tapeOrder = ['tl','tr','tc','bl','br'];

  const groupNotes = chapter.groupNotes || {};

  return (
    <Reveal>
      <div style={{ position: 'relative', padding: '0 60px 30px', display: 'flex', flexDirection: 'column', gap: 56 }}>
        {units.map((u, ui) => {
          if (u.kind === 'divider') {
            if (u.mini) {
              return (
                <div key={`d-${ui}`} style={{ display: 'flex', alignItems: 'center', gap: 18, padding: '6px 0', justifyContent: 'center' }}>
                  <div style={{ flex: '0 1 140px', height: 1, background: 'var(--ink-faded)', opacity: 0.5 }} />
                  <div style={{ fontFamily: 'var(--hand)', fontSize: 44, color: 'var(--ink-soft)', lineHeight: 1, transform: 'rotate(-2deg)' }}>
                    {u.label}
                  </div>
                  <div style={{ flex: '0 1 140px', height: 1, background: 'var(--ink-faded)', opacity: 0.5 }} />
                </div>
              );
            }
            return (
              <div key={`d-${ui}`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding: '12px 0' }}>
                <div style={{ width: 80, height: 1, background: 'var(--ink-faded)', opacity: 0.45 }} />
                <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.3em', color: 'var(--ink-faded)', textTransform: 'uppercase' }}>
                  {u.end ? '— end side quest —' : '— side quest —'}
                </div>
                {!u.end && (
                  <div style={{ fontFamily: 'var(--hand)', fontSize: 36, color: 'var(--ink-soft)', transform: 'rotate(-1.5deg)', textAlign: 'center', maxWidth: 640 }}>
                    {u.label}
                  </div>
                )}
                {!u.end && u.sub && (
                  <div style={{ fontFamily: 'var(--serif)', fontSize: 16, fontStyle: 'italic', color: 'var(--ink-faded)', textAlign: 'center', maxWidth: 540 }}>
                    {u.sub}
                  </div>
                )}
                <div style={{ width: 80, height: 1, background: 'var(--ink-faded)', opacity: 0.45 }} />
              </div>
            );
          }
          if (u.kind === 'group') {
            // Food group gets a centered note inserted between its two photos
            if (u.id === 'food' && u.photos.length === 2) {
              return (
                <div key={`g-${ui}`} style={{ display: 'flex', flexWrap: 'nowrap', gap: '40px 50px', justifyContent: 'center', alignItems: 'center' }}>
                  <PhotoUnit photo={u.photos[0]} rotate={u.photos[0].rotate} tapeAt="tl" />
                  <Note size={26} rotate={-3} style={{ whiteSpace: 'nowrap', textAlign: 'center', color: 'var(--ink-soft)', flexShrink: 0 }}>
                    ← mmmm can't wait to have this again soon →
                  </Note>
                  <PhotoUnit photo={u.photos[1]} rotate={u.photos[1].rotate} tapeAt="tr" nudge={28} />
                </div>
              );
            }
            const gNote = groupNotes[u.id];
            const tightPair = u.photos.length === 2;
            return (
              <div key={`g-${ui}`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: gNote ? 22 : 0 }}>
                <div style={{ display: 'flex', flexWrap: tightPair ? 'nowrap' : 'wrap', gap: '32px 44px', justifyContent: 'center', alignItems: 'flex-start' }}>
                  {u.photos.map((p, i) => (
                    <PhotoUnit
                      key={i}
                      photo={p}
                      rotate={p.rotate}
                      tapeAt={tapeOrder[(ui + i) % 5]}
                      nudge={i % 2 === 1 ? 28 : 0}
                      hideNote={!!gNote}
                    />
                  ))}
                </div>
                {gNote && (
                  <div style={{
                    fontFamily: 'var(--hand)', fontSize: 28, color: 'var(--ink-soft)',
                    lineHeight: 1.18, textAlign: 'center', maxWidth: 640,
                    transform: 'rotate(-1.5deg)',
                  }}>
                    <span style={{ color: 'var(--rose)', marginRight: 8 }}>↑</span>{gNote}
                  </div>
                )}
              </div>
            );
          }
          const p = u.photo;
          if (p.layout === 'final') {
            return (
              <div key={`s-${ui}`} style={{ display: 'flex', justifyContent: 'center' }}>
                <PhotoUnit photo={p} rotate={p.rotate} tapeAt="tc" size="large" />
              </div>
            );
          }
          if (p.layout === 'with-journal') {
            const flip = ui % 2 === 0;
            return (
              <div key={`j-${ui}`} style={{ display: 'flex', flexWrap: 'wrap', gap: '40px 70px', justifyContent: 'center', alignItems: 'center', flexDirection: flip ? 'row' : 'row-reverse' }}>
                <PhotoUnit photo={p} rotate={p.rotate} tapeAt={flip ? 'tl' : 'tr'} />
                <JournalEntry heading={p.journal?.heading} body={p.journal?.body} />
              </div>
            );
          }
          if (p.pairWith) {
            return (
              <div key={`p-${ui}`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 40 }}>
                <div style={{ display: 'flex', flexWrap: 'nowrap', gap: '40px 70px', justifyContent: 'center', alignItems: 'flex-start' }}>
                  <PhotoUnit photo={p.pairWith} rotate={p.pairWith.rotate} tapeAt="tl" caption={p.pairWith.sub} />
                  <Note size={26} rotate={-4} style={{ whiteSpace: 'nowrap', textAlign: 'center', color: 'var(--ink-soft)', alignSelf: 'center', flexShrink: 0 }}>
                    ← then ····· now →
                  </Note>
                  <PhotoUnit photo={p} rotate={p.rotate} tapeAt="tr" caption={p.sub} />
                </div>
                {p.journalAfter && <JournalEntry heading={p.journalAfter.heading} body={p.journalAfter.body} narrow />}
              </div>
            );
          }
          return (
            <div key={`x-${ui}`} style={{ display: 'flex', justifyContent: 'center' }}>
              <PhotoUnit photo={p} rotate={p.rotate} tapeAt={tapeOrder[ui % 5]} />
            </div>
          );
        })}
      </div>
    </Reveal>
  );
}

// Photo + optional margin note, contained flex unit.
function PhotoUnit({ photo, rotate, tapeAt, size, caption, nudge = 0, hideNote = false }) {
  const p = photo;
  const note = hideNote ? null : (p.marginNote || p.comment);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, marginTop: nudge, maxWidth: Math.max(p.w + 40, 240) }}>
      <Polaroid rotate={rotate} tape tapeAt={tapeAt} size={size}>
        <PhotoPlaceholder label={p.label} w={p.w} h={p.h} src={p.src} video={p.video} banner={p.banner} />
        {caption && <div className="caption">{caption}</div>}
      </Polaroid>
      {note && (
        <div style={{
          fontFamily: 'var(--hand)', fontSize: 26, color: 'var(--ink-soft)',
          lineHeight: 1.15, textAlign: 'center', maxWidth: p.w + 40,
          transform: `rotate(${rotate < 0 ? 1.5 : -1.5}deg)`, marginTop: 4,
        }}>
          {p.noArrow ? note : <><span style={{ color: 'var(--rose)', marginRight: 6 }}>↑</span>{note}</>}
        </div>
      )}
    </div>
  );
}

// A short journal entry rendered beside a photo — serif body, eyebrow heading.
function JournalEntry({ heading, body, narrow }) {
  return (
    <div style={{ maxWidth: narrow ? 460 : 380, fontFamily: 'var(--serif)' }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.3em', color: 'var(--ink-faded)', marginBottom: 14, textTransform: 'uppercase' }}>
        {heading}
      </div>
      <div style={{ fontSize: 19, lineHeight: 1.55, color: 'var(--ink-soft)', textWrap: 'pretty' }}>
        {body}
      </div>
    </div>
  );
}

// Handwritten comment that floats next to a polaroid with a hand-drawn arrow.
function PhotoComment({ text, side = 'right' }) {
  const isRight = side === 'right';
  return (
    <div style={{
      position: 'absolute',
      [isRight ? 'left' : 'right']: '100%',
      [isRight ? 'marginLeft' : 'marginRight']: 16,
      top: 30,
      width: 200,
      transform: `rotate(${isRight ? -3 : 3}deg)`,
      fontFamily: 'var(--hand)',
      fontSize: 24,
      color: 'var(--ink-soft)',
      lineHeight: 1.15,
      pointerEvents: 'none',
    }}>
      <span style={{
        display: 'inline-block',
        marginRight: isRight ? 4 : 0,
        marginLeft: isRight ? 0 : 4,
        color: 'var(--rose)',
      }}>
        {isRight ? '←' : '→'}
      </span>
      {text}
    </div>
  );
}

// Final chapter — closing letter
function DirA_Final({ chapter, sectionRef }) {
  return (
    <section ref={sectionRef} data-chapter-id={chapter.id} style={{ position: 'relative', padding: '20px 0 120px' }}>
      <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: '90px 80px', display: 'flex', alignItems: 'center', gap: 70 }}>
          <div style={{ flex: '0 0 auto', position: 'relative' }}>
            <Polaroid rotate={chapter.photos[0].rotate} 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} />
              <div className="caption">still you.</div>
            </Polaroid>
            <Sticker rotate={-15} style={{ position: 'absolute', top: -28, right: -28, fontSize: 36, color: 'var(--rose)' }}>♡</Sticker>
          </div>
          <div style={{ flex: 1, maxWidth: 500 }}>
            <Eyebrow style={{ marginBottom: 14 }}>{chapter.place}</Eyebrow>
            <h2 style={{ fontFamily: 'var(--display)', fontSize: 72, lineHeight: 1.0, margin: '0 0 30px', fontWeight: 400 }}>
              {chapter.title}
            </h2>
            <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: 26, fontFamily: 'var(--hand)', fontSize: 30, color: 'var(--ink-soft)' }}>{chapter.signoff}</div>
            <div style={{ fontFamily: 'var(--hand)', fontSize: 30, color: 'var(--ink-soft)' }}>{chapter.signoff2}</div>
          </div>
        </div>
      </Reveal>
    </section>
  );
}

function DirectionA({ tweaks, registerSection, fullViewport }) {
  const m = window.MEMORIES;
  if (fullViewport) {
    return (
      <div className={`memory-doc paper-bg memory-doc-full ${tweaks.grain ? 'grain-overlay' : ''}`}>
        <DirA_Opening registerSection={registerSection} />
        <Stitch style={{ margin: '0 80px' }} />
        {m.chapters.map((c) => (
          <DirA_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="a">
        <DirA_Opening registerSection={registerSection} />
        <Stitch style={{ margin: '0 80px' }} />
        {m.chapters.map((c) => (
          <DirA_Chapter key={c.id} chapter={c} registerSection={registerSection} />
        ))}
      </div>
    </div>
  );
}

window.DirectionA = DirectionA;
