// scenes-mid.jsx — Scene 3 (synced reader) and Scene 4 (tap to save)

// ─────────────────────────────────────────────────────────────────────────────
// SCENE 3 — Synced reader (7 → 11s) [localTime 0..4]
// Phone-shaped placeholder with two columns. Words highlight in sync with
// a moving "audio cursor" that pulses.
// ─────────────────────────────────────────────────────────────────────────────
function SceneReader() {
  const { localTime } = useSprite();
  const L = useLang();
  const t = localTime;

  // Phone slides up
  const phoneY = animate({ from: 80, to: 0, start: 0, end: 0.6, ease: Easing.easeOutCubic })(t);
  const phoneOp = animate({ from: 0, to: 1, start: 0, end: 0.6 })(t);

  // Header label
  const labelOp = animate({ from: 0, to: 1, start: 0.4, end: 0.8 })(t);

  // Title
  const capOp = animate({ from: 0, to: 1, start: 0.5, end: 1.0 })(t) * animate({ from: 1, to: 0, start: 3.4, end: 3.9 })(t);

  // Words: arrays of (de, en) pairs. Highlight progresses linearly.
  const sentences = [
    { de: ['Am', 'Morgen', 'trinkt', 'sie', 'Kaffee.'], en: L.sentence_1_en },
    { de: ['Der', 'Hund', 'schläft', 'auf', 'dem', 'Sofa.'], en: L.sentence_2_en },
  ];

  // Cursor sweeps across both sentences from t=0.8 → t=3.4
  const sweepStart = 0.8;
  const sweepEnd = 3.4;
  const sweepT = clamp((t - sweepStart) / (sweepEnd - sweepStart), 0, 1);

  // Sentence 1 spans 0..0.5, sentence 2 spans 0.5..1
  const s1T = clamp(sweepT / 0.5, 0, 1);
  const s2T = clamp((sweepT - 0.5) / 0.5, 0, 1);

  // Active word index per sentence (DE)
  const s1de = Math.floor(s1T * sentences[0].de.length * 0.999);
  const s2de = Math.floor(s2T * sentences[1].de.length * 0.999);

  // Audio waveform pulse
  const wavePulse = (Math.sin(t * 14) + 1) / 2;

  // Exit
  const exitT = animate({ from: 0, to: 1, start: 3.6, end: 4.0, ease: Easing.easeInCubic })(t);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: PAL.paper,
      overflow: 'hidden',
      opacity: 1 - exitT * 0.5,
    }}>
      <Grain />

      {/* Caption — left side */}
      <div style={{
        position: 'absolute',
        left: 80, top: 120,
        opacity: capOp,
        maxWidth: 440,
      }}>
        <div style={{
          fontFamily: FONT_MONO,
          fontSize: 16,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          color: PAL.pop,
          marginBottom: 24,
        }}>
          {L.reader_kicker}
        </div>
        <div style={{
          fontFamily: FONT_DISPLAY,
          fontSize: 64,
          fontStyle: 'italic',
          color: PAL.ink,
          lineHeight: 1.0,
          letterSpacing: '-0.02em',
        }}>
          {L.reader_l1}<br/>{L.reader_l2}<br/>{L.reader_l3}
        </div>
        <div style={{
          marginTop: 36,
          fontFamily: FONT_SANS,
          fontSize: 22,
          color: PAL.inkSoft,
          lineHeight: 1.4,
        }}>
          {L.reader_sub_l1}<br/>{L.reader_sub_l2} <i>{L.reader_sub_l3}</i>
        </div>
      </div>

      {/* Phone-ish placeholder */}
      <div style={{
        position: 'absolute',
        right: 120, top: '50%',
        transform: `translateY(-50%) translateY(${phoneY}px)`,
        opacity: phoneOp,
        width: 720,
        height: 820,
        background: PAL.paper,
        border: `3px solid ${PAL.ink}`,
        borderRadius: 48,
        padding: 32,
        boxShadow: '0 30px 0 ' + PAL.ink,
      }}>
        {/* Notch */}
        <div style={{
          position: 'absolute',
          top: 0, left: '50%', transform: 'translate(-50%, -2px)',
          width: 140, height: 24,
          background: PAL.ink,
          borderRadius: '0 0 14px 14px',
        }} />

        {/* Header bar */}
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginTop: 24,
          marginBottom: 28,
          opacity: labelOp,
        }}>
          <div style={{
            fontFamily: FONT_MONO,
            fontSize: 14,
            color: PAL.inkSoft,
            letterSpacing: '0.12em',
          }}>{L.reader_label}</div>
          <div style={{
            fontFamily: FONT_MONO,
            fontSize: 14,
            color: PAL.inkSoft,
          }}>03 / 12</div>
        </div>

        {/* Two-column reader */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }}>
          {/* DE column */}
          <div>
            <div style={{
              fontFamily: FONT_MONO,
              fontSize: 12,
              letterSpacing: '0.14em',
              color: PAL.pop,
              marginBottom: 14,
            }}>DE</div>
            <SyncedSentence words={sentences[0].de} active={s1de} sweepActive={s1T > 0 && s1T < 1} sentenceDone={s1T >= 1} />
            <div style={{ height: 24 }} />
            <SyncedSentence words={sentences[1].de} active={s2de} sweepActive={s2T > 0 && s2T < 1} sentenceDone={s2T >= 1} />
          </div>
          {/* Translation column */}
          <div>
            <div style={{
              fontFamily: FONT_MONO,
              fontSize: 12,
              letterSpacing: '0.14em',
              color: PAL.inkSoft,
              marginBottom: 14,
            }}>{L.lang_label || 'EN'}</div>
            <PlainSentence text={sentences[0].en} dim={s1T > 0.95 ? 0.4 : 1} />
            <div style={{ height: 24 }} />
            <PlainSentence text={sentences[1].en} dim={s2T > 0.95 ? 0.4 : s2T === 0 ? 0.4 : 1} />
          </div>
        </div>

        {/* Audio waveform */}
        <div style={{
          position: 'absolute',
          left: 32, right: 32, bottom: 40,
          height: 70,
          background: PAL.paperDeep,
          borderRadius: 20,
          padding: '0 24px',
          display: 'flex',
          alignItems: 'center',
          gap: 16,
        }}>
          {/* Play button */}
          <div style={{
            width: 44, height: 44,
            background: PAL.pop,
            borderRadius: '50%',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{
              width: 0, height: 0,
              borderLeft: `12px solid ${PAL.paper}`,
              borderTop: '8px solid transparent',
              borderBottom: '8px solid transparent',
              marginLeft: 4,
            }} />
          </div>
          {/* Waveform bars */}
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 4, height: '100%' }}>
            {Array.from({ length: 36 }).map((_, i) => {
              const phase = (t * 6 - i * 0.3) % (Math.PI * 2);
              const h = 14 + Math.abs(Math.sin(phase)) * (26 + i % 4 * 4);
              const isPast = i / 36 < sweepT;
              return (
                <div key={i} style={{
                  width: 4,
                  height: h,
                  background: isPast ? PAL.pop : PAL.inkSoft,
                  opacity: isPast ? 1 : 0.35,
                  borderRadius: 2,
                }} />
              );
            })}
          </div>
          {/* Time */}
          <div style={{
            fontFamily: FONT_MONO,
            fontSize: 13,
            color: PAL.inkSoft,
            fontVariantNumeric: 'tabular-nums',
          }}>
            0:{String(Math.floor(sweepT * 38)).padStart(2,'0')} / 0:38
          </div>
        </div>
      </div>
    </div>
  );
}

function SyncedSentence({ words, active, sweepActive, sentenceDone }) {
  // Highlight the WHOLE sentence while voice reads it (in-sync with audio cursor),
  // not individual words. `sweepActive` = sentence is currently being read.
  // `sentenceDone` = sentence already finished (kept readable, dimmed slightly).
  const isReading = !!sweepActive;
  const isPast = !sweepActive && !!sentenceDone;
  return (
    <div style={{
      fontFamily: FONT_DISPLAY,
      fontSize: 30,
      lineHeight: 1.4,
      color: isReading ? PAL.paper : isPast ? PAL.ink : PAL.inkSoft,
      background: isReading ? PAL.pop : 'transparent',
      padding: isReading ? '6px 10px' : '6px 0',
      borderRadius: 6,
      transition: 'background 120ms, color 120ms, padding 120ms',
      display: 'inline-block',
    }}>
      {words.join(' ')}
    </div>
  );
}

function PlainSentence({ text, words, dim = 1 }) {
  return (
    <div style={{
      fontFamily: FONT_DISPLAY,
      fontSize: 28,
      lineHeight: 1.4,
      color: PAL.inkSoft,
      fontStyle: 'italic',
      opacity: dim,
    }}>
      {text || (words ? words.join(' ') : '')}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SCENE 4 — Tap to save (11 → 15s) [localTime 0..4]
// A finger taps words; they fly into a flashcard stack. Counter ticks.
// ─────────────────────────────────────────────────────────────────────────────
function SceneSave() {
  const { localTime } = useSprite();
  const L = useLang();
  const t = localTime;

  const capOp = animate({ from: 0, to: 1, start: 0.2, end: 0.7 })(t) * animate({ from: 1, to: 0, start: 3.4, end: 3.9 })(t);

  // 3 word taps
  const taps = [
    { word: 'spazieren', start: 0.7, x: 380, y: 360 },
    { word: 'gemütlich', start: 1.6, x: 580, y: 480 },
    { word: 'Frühstück', start: 2.5, x: 420, y: 600 },
  ];
  const passage = [
    { pre: L.save_passage_pre1, post: L.save_passage_post1, tap: taps[0] },
    { pre: L.save_passage_pre2, post: L.save_passage_post2, tap: taps[1] },
    { pre: L.save_passage_pre3, post: L.save_passage_post3, tap: taps[2] },
  ];

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: PAL.paperDeep,
      overflow: 'hidden',
    }}>
      <Grain />

      {/* Caption — right */}
      <div style={{
        position: 'absolute',
        right: 80, top: 200,
        opacity: capOp,
        maxWidth: 540,
        textAlign: 'right',
      }}>
        <div style={{
          fontFamily: FONT_MONO,
          fontSize: 16,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          color: PAL.pop,
          marginBottom: 24,
        }}>
          {L.save_kicker}
        </div>
        <div style={{
          fontFamily: FONT_DISPLAY,
          fontSize: 64,
          fontStyle: 'italic',
          color: PAL.ink,
          lineHeight: 1.0,
          letterSpacing: '-0.02em',
        }}>
          {L.save_l1}<br/>{L.save_l2}
        </div>
        <div style={{
          marginTop: 28,
          fontFamily: FONT_SANS,
          fontSize: 22,
          color: PAL.inkSoft,
          lineHeight: 1.4,
        }}>
          {L.save_sub_l1}<br/>{L.save_sub_l2}
        </div>
      </div>

      {/* Text passage — left */}
      <div style={{
        position: 'absolute',
        left: 80, top: 280,
        width: 720,
        fontFamily: FONT_DISPLAY,
        fontSize: 34,
        lineHeight: 1.5,
        color: PAL.ink,
      }}>
        Am Sonntag gehe ich gerne <Tappable word="spazieren" t={t} tapStart={0.7} />.
        Es ist <Tappable word="gemütlich" t={t} tapStart={1.6} />, mit Kaffee und Brot.
        Ein langes <Tappable word="Frühstück" t={t} tapStart={2.5} /> ist das Beste.
      </div>

      {/* Flashcard stack — bottom right */}
      <FlashcardStack t={t} taps={taps} cardLabel={L.save_card_label} counterLabel={L.save_counter_label} />

      {/* Flying words */}
      {taps.map((tap, i) => (
        <FlyingWord key={i} word={tap.word} startX={tap.x} startY={tap.y} t={t} startT={tap.start + 0.3} />
      ))}
    </div>
  );
}

function Tappable({ word, t, tapStart }) {
  const tapped = t > tapStart + 0.3;
  const tapProgress = clamp((t - tapStart) / 0.3, 0, 1);
  const scale = tapped ? 1 : (1 - Math.abs(Math.sin(tapProgress * Math.PI)) * 0.1);

  return (
    <span style={{
      display: 'inline-block',
      background: tapped ? 'transparent' : PAL.pop,
      color: tapped ? PAL.inkSoft : PAL.paper,
      padding: '2px 8px',
      borderRadius: 6,
      textDecorationLine: tapped ? 'line-through' : 'none',
      textDecorationColor: PAL.pop,
      transform: `scale(${scale})`,
      transition: 'all 200ms',
      fontStyle: 'italic',
    }}>
      {word}
    </span>
  );
}

function FlyingWord({ word, startX, startY, t, startT }) {
  const flyT = clamp((t - startT) / 0.7, 0, 1);
  if (flyT <= 0 || flyT >= 1) return null;

  const targetX = 1500;
  const targetY = 760;

  const eased = Easing.easeInOutCubic(flyT);
  const x = startX + (targetX - startX) * eased;
  // Arc trajectory
  const y = startY + (targetY - startY) * eased - Math.sin(flyT * Math.PI) * 120;

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      fontFamily: FONT_DISPLAY,
      fontStyle: 'italic',
      fontSize: 32,
      color: PAL.paper,
      background: PAL.pop,
      padding: '6px 14px',
      borderRadius: 8,
      transform: `scale(${1 - flyT * 0.4})`,
      opacity: 1 - flyT * 0.3,
    }}>
      {word}
    </div>
  );
}

function FlashcardStack({ t, taps, cardLabel = 'FLASHCARD', counterLabel = 'saved words' }) {
  // Count saved
  const saved = taps.filter(tap => t > tap.start + 0.95).length;
  const counterPulse = taps.find(tap => t > tap.start + 0.95 && t < tap.start + 1.2);
  const pulseScale = counterPulse ? 1 + Math.sin((t - counterPulse.start - 0.95) / 0.25 * Math.PI) * 0.15 : 1;

  return (
    <div style={{
      position: 'absolute',
      right: 80, bottom: 80,
      width: 360,
    }}>
      {/* Counter */}
      <div style={{
        textAlign: 'center',
        marginBottom: 20,
        transform: `scale(${pulseScale})`,
        transformOrigin: 'center bottom',
      }}>
        <div style={{
          fontFamily: FONT_MONO,
          fontSize: 14,
          color: PAL.inkSoft,
          letterSpacing: '0.14em',
          textTransform: 'uppercase',
          marginBottom: 6,
        }}>{counterLabel}</div>
        <div style={{
          fontFamily: FONT_DISPLAY,
          fontSize: 96,
          fontStyle: 'italic',
          color: PAL.pop,
          lineHeight: 1,
        }}>{saved}</div>
      </div>

      {/* Stack of cards */}
      <div style={{ position: 'relative', height: 200 }}>
        {taps.slice(0, saved).map((tap, i) => {
          const settle = clamp((t - tap.start - 0.95) / 0.4, 0, 1);
          const e = Easing.easeOutBack(settle);
          return (
            <div key={i} style={{
              position: 'absolute',
              left: 0, right: 0,
              top: i * 14 - (1 - e) * 60,
              transform: `rotate(${(i - 1) * 2}deg) scale(${0.9 + e * 0.1})`,
              opacity: e,
              background: PAL.paper,
              border: `2px solid ${PAL.ink}`,
              borderRadius: 14,
              padding: '20px 24px',
              fontFamily: FONT_DISPLAY,
              fontSize: 28,
              fontStyle: 'italic',
              color: PAL.ink,
              boxShadow: `4px 4px 0 ${PAL.ink}`,
            }}>
              <div style={{
                fontFamily: FONT_MONO,
                fontSize: 11,
                letterSpacing: '0.14em',
                color: PAL.pop,
                fontStyle: 'normal',
                marginBottom: 4,
              }}>{cardLabel}</div>
              {tap.word}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { SceneReader, SceneSave });
