// screens-phrase.jsx — Phrase card v2: leaner, one focus per screen.
// locked (subtle hint) → unlock moment (calm, auto-continues) → hear (input first)
// → meaning check (idioms ONLY) → say it (mature production review).
// Transparent phrase: "Es dzeru kafiju." (skips meaning check)
// Idiomatic phrase:  "Man garšo kafija." = "I like coffee." (words don't add up)

const PP_PHRASES = {
  clear: {
    words: [
      { lv: 'Es', known: true },
      { lv: 'dzeru', lemma: 'dzert', known: false },
      { lv: 'kafiju', known: true },
    ],
    en: 'I drink coffee.',
    seed: 'es-dzeru-kafiju',
  },
  idiom: {
    words: [
      { lv: 'Man', known: true },
      { lv: 'garšo', lemma: 'garšot', known: false },
      { lv: 'kafija', known: true },
    ],
    en: 'I like coffee.',
    seed: 'man-garso-kafija',
  },
};

// one-time keyframes for the unlock moment (gated on reduced motion)
if (typeof document !== 'undefined' && !document.getElementById('pp-phrase-kf')) {
  const s = document.createElement('style');
  s.id = 'pp-phrase-kf';
  s.textContent = `
    @keyframes ppUnlockBloom { 0% { transform: scale(0.7); opacity: 0.5; } 100% { transform: scale(1.6); opacity: 0; } }
    @keyframes ppUnlockPop { 0% { transform: scale(0.72); opacity: 0; } 60% { transform: scale(1.06); opacity: 1; } 100% { transform: scale(1); opacity: 1; } }
    @keyframes ppRise { 0% { transform: translateY(10px); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } }
    @keyframes ppFillOnce { 0% { width: 0; } 100% { width: 100%; } }
    @media (prefers-reduced-motion: reduce) {
      .pp-unlock-bloom, .pp-unlock-pop, .pp-rise, .pp-fill-once { animation: none !important; opacity: 1 !important; transform: none !important; }
      .pp-fill-once { width: 100% !important; }
    }`;
  document.head.appendChild(s);
}

// soft two-note chime (WebAudio) — quiet, short
function ppChime() {
  try {
    const ctx = new (window.AudioContext || window.webkitAudioContext)();
    const t0 = ctx.currentTime;
    [[659.3, 0], [880, 0.13]].forEach(([f, d]) => {
      const o = ctx.createOscillator(), g = ctx.createGain();
      o.type = 'sine'; o.frequency.value = f;
      g.gain.setValueAtTime(0, t0 + d);
      g.gain.linearRampToValueAtTime(0.07, t0 + d + 0.02);
      g.gain.exponentialRampToValueAtTime(0.0001, t0 + d + 1.1);
      o.connect(g); g.connect(ctx.destination);
      o.start(t0 + d); o.stop(t0 + d + 1.2);
    });
  } catch (e) { /* no audio in this context */ }
}

// serif phrase line; the one new word subtly highlighted
function PhraseLine({ T, t, phrase = PP_PHRASES.clear, dim = false, highlightNew = true, size = 34 }) {
  const head = ppHeadFont(t);
  return (
    <div style={{ fontFamily: head, fontSize: size, fontWeight: 500, letterSpacing: -0.5, lineHeight: 1.25, textAlign: 'center', color: dim ? T.faint : T.ink }}>
      {phrase.words.map((w, i) => (
        <React.Fragment key={i}>
          {i > 0 && ' '}
          <span style={{
            color: dim ? T.faint : (!w.known && highlightNew ? T.primary : T.ink),
            borderBottom: !w.known && highlightNew && !dim ? `2px solid ${hexA(T.primary, 0.35)}` : 'none',
            paddingBottom: !w.known && highlightNew && !dim ? 2 : 0,
          }}>{w.lv}</span>
        </React.Fragment>
      ))}
      <span style={{ color: dim ? T.faint : T.ink }}>.</span>
    </div>
  );
}

// ── 1 · LOCKED — a subtle hint, nothing to dwell on ──────────────────────
function PhraseLocked({ T, t }) {
  return (
    <Screen theme={T}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, paddingTop: 66, paddingBottom: 6 }}>
        <button style={{ width: 32, height: 32, borderRadius: '50%', border: 'none', cursor: 'pointer', background: T.dark ? 'rgba(255,255,255,0.06)' : 'rgba(26,39,51,0.05)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="close" size={17} color={T.sub} />
        </button>
        <span style={{ fontFamily: PP_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: T.faint }}>Upcoming phrase</span>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 60 }}>
        <PhraseLine T={T} t={t} dim size={32} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 28 }}>
          <Icon name="lock" size={15} color={T.faint} />
          <span style={{ fontFamily: PP_UI, fontSize: 15, color: T.sub }}>
            1 word to go — learn <b style={{ fontFamily: ppHeadFont(t), fontWeight: 600, color: T.ink }}>dzert</b>
          </span>
        </div>
        <div style={{ fontFamily: PP_UI, fontSize: 13, color: T.faint, marginTop: 10 }}>
          It appears here as &ldquo;dzeru&rdquo;.
        </div>
      </div>
    </Screen>
  );
}

// ── 2 · UNLOCK MOMENT — one restrained animation + soft chime, then flows on ──
function PhraseUnlock({ T, t }) {
  const [run, setRun] = React.useState(0); // replay key
  const replay = () => { setRun(r => r + 1); ppChime(); };
  return (
    <Screen theme={T}>
      <SessionTop theme={T} step={7} total={12} />
      <div key={run} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 8 }}>
        {/* single bloom ring + orb — earned, not celebratory */}
        <div style={{ position: 'relative', width: 140, height: 140, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div className="pp-unlock-bloom" style={{
            position: 'absolute', width: 110, height: 110, borderRadius: '50%',
            border: `1.5px solid ${hexA(T.primary, 0.4)}`, opacity: 0,
            animation: 'ppUnlockBloom 1.4s cubic-bezier(.2,.6,.3,1) .25s 1 forwards',
          }} />
          <div style={{ position: 'absolute', width: 96, height: 96, borderRadius: '50%', background: T.primarySoft }} />
          <button className="pp-orb pp-unlock-pop" onClick={replay} aria-label="Replay chime" style={{
            position: 'relative', width: 64, height: 64, borderRadius: '50%', border: 'none', cursor: 'pointer',
            background: T.primary, boxShadow: `0 8px 24px ${hexA(T.primary, T.dark ? 0.45 : 0.3)}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            animation: 'ppUnlockPop .7s cubic-bezier(.34,1.4,.5,1) 1 both',
          }}>
            <Icon name="unlock" size={25} color={T.onPrimary} sw={1.9} />
          </button>
        </div>

        <div className="pp-rise" style={{ fontFamily: PP_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.6, textTransform: 'uppercase', color: T.primary, marginTop: 28, animation: 'ppRise .6s ease .5s 1 both' }}>
          Phrase unlocked
        </div>
        <div className="pp-rise" style={{ marginTop: 16, animation: 'ppRise .6s ease .65s 1 both' }}>
          <PhraseLine T={T} t={t} size={32} />
        </div>
        <div className="pp-rise" style={{ fontFamily: PP_UI, fontSize: 14.5, color: T.sub, marginTop: 14, animation: 'ppRise .6s ease .8s 1 both' }}>
          You know all its words now.
        </div>
      </div>

      {/* no button — it flows straight into hearing it */}
      <div style={{ paddingBottom: 42, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 110, height: 3, borderRadius: 99, background: T.dark ? 'rgba(255,255,255,0.09)' : 'rgba(26,39,51,0.08)', overflow: 'hidden' }}>
          <div className="pp-fill-once" style={{ height: '100%', width: 0, borderRadius: 99, background: T.primary, animation: 'ppFillOnce 2.4s linear 1s 1 forwards' }} />
        </div>
        <span style={{ fontFamily: PP_UI, fontSize: 12.5, color: T.faint }}>Hearing it&hellip;</span>
      </div>
    </Screen>
  );
}

// ── 3 · HEAR — first exposure, input first ───────────────────────────────
function PhraseHear({ T, t }) {
  const phrase = PP_PHRASES.clear;
  const [playing, setPlaying] = React.useState(false);
  const [shown, setShown] = React.useState(false);
  const [speed, setSpeed] = React.useState(1);
  return (
    <Screen theme={T}>
      <SessionTop theme={T} step={8} total={12} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 8 }}>
        <div style={{ fontFamily: PP_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: T.faint }}>New phrase</div>

        <div style={{ marginTop: 22 }}>
          <PhraseLine T={T} t={t} phrase={phrase} size={34} />
        </div>
        <div style={{ fontFamily: PP_UI, fontSize: 13, color: T.faint, marginTop: 12 }}>
          <b style={{ fontFamily: ppHeadFont(t), fontWeight: 600, color: T.primary }}>dzert</b>, here as &ldquo;dzeru&rdquo;
        </div>

        {/* audio hero */}
        <div style={{ width: '100%', marginTop: 32, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
          <div style={{ width: '78%' }}>
            <Waveform seed={phrase.seed} played={playing ? 0.62 : 0} height={58} count={44} theme={T} style={t.wave || 'bars'} />
          </div>
          <PlayOrb theme={T} size={78} playing={playing} onClick={() => setPlaying(p => !p)} />
          <SpeedChip theme={T} value={speed} onChange={setSpeed} />
        </div>

        {/* meaning — demoted, behind a tap */}
        <div style={{ height: 70, marginTop: 24, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', gap: 7 }}>
          {shown ? (
            <span style={{ fontFamily: PP_UI, fontSize: 19, fontWeight: 500, color: T.sub }}>{phrase.en}</span>
          ) : (
            <button onClick={() => setShown(true)} style={{
              display: 'flex', alignItems: 'center', gap: 8, padding: '10px 18px', borderRadius: 99, cursor: 'pointer',
              background: 'transparent', border: `1.5px solid ${T.hair}`, color: T.sub,
              fontFamily: PP_UI, fontSize: 14, fontWeight: 600,
            }}>
              <Icon name="text" size={16} color={T.sub} /> Show meaning
            </button>
          )}
        </div>
      </div>

      <div style={{ paddingBottom: 30, display: 'flex', flexDirection: 'column', gap: 11 }}>
        <div style={{ textAlign: 'center', fontFamily: PP_UI, fontSize: 13.5, color: T.faint, fontWeight: 500 }}>
          First review <b style={{ color: T.sub, fontWeight: 600 }}>tomorrow</b>.
        </div>
        <button style={{
          width: '100%', height: 56, borderRadius: 18, border: 'none', cursor: 'pointer',
          background: T.primary, color: T.onPrimary, fontFamily: PP_UI, fontSize: 17, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 8px 20px ${hexA(T.primary, 0.26)}`,
        }}>Continue</button>
      </div>
    </Screen>
  );
}

// ── 4 · MEANING CHECK — only for idiomatic phrases ───────────────────────
function PhraseMeaning({ T, t }) {
  const phrase = PP_PHRASES.idiom;
  const [playing, setPlaying] = React.useState(false);
  const [picked, setPicked] = React.useState(null);
  const [speed, setSpeed] = React.useState(1);
  const options = [
    { en: 'I taste the coffee.', ok: false },
    { en: 'I like coffee.', ok: true },
    { en: 'I\u2019m making coffee.', ok: false },
  ];
  return (
    <Screen theme={T}>
      <SessionTop theme={T} step={9} total={12} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 8 }}>
        <div style={{ fontFamily: PP_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: T.faint }}>
          New phrase <span style={{ color: T.primary }}>&middot; idiom</span>
        </div>

        <div style={{ marginTop: 20 }}>
          <PhraseLine T={T} t={t} phrase={phrase} size={32} />
        </div>

        {/* compact audio row — already modeled, stays close */}
        <div style={{ width: '84%', marginTop: 24, display: 'flex', alignItems: 'center', gap: 12 }}>
          <PlayOrb theme={T} size={46} playing={playing} onClick={() => setPlaying(p => !p)} />
          <div style={{ flex: 1 }}>
            <Waveform seed={phrase.seed} played={playing ? 0.62 : 0} height={34} count={36} theme={T} style={t.wave || 'bars'} />
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>
          <SpeedChip theme={T} size="sm" value={speed} onChange={setSpeed} />
        </div>

        <div style={{ fontFamily: ppHeadFont(t), fontSize: 20, fontWeight: 500, color: T.sub, marginTop: 34, letterSpacing: -0.2 }}>
          What does it mean?
        </div>

        <div style={{ width: '100%', marginTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {options.map((o, i) => {
            const on = picked === i;
            const good = on && o.ok;
            return (
              <button key={i} onClick={() => setPicked(i)} style={{
                width: '100%', minHeight: 54, borderRadius: 17, cursor: 'pointer', padding: '0 18px',
                background: good ? T.goodSoft : (on ? (T.dark ? 'rgba(255,255,255,0.06)' : 'rgba(26,39,51,0.04)') : T.surface),
                border: `1.5px solid ${good ? hexA(T.good, 0.5) : (on ? T.faint : T.hair)}`,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                fontFamily: PP_UI, fontSize: 16, fontWeight: 500, color: T.ink, textAlign: 'left',
                boxShadow: T.shadow,
              }}>
                {o.en}
                {good && <Icon name="check" size={18} color={T.good} sw={2.4} />}
              </button>
            );
          })}
        </div>

        <div style={{ height: 24, marginTop: 16, fontFamily: PP_UI, fontSize: 13, color: T.faint, textAlign: 'center' }}>
          {picked !== null && options[picked].ok && <>Word-for-word it&rsquo;s &ldquo;to-me tastes coffee&rdquo; &mdash; garšot points backwards.</>}
        </div>
      </div>

      <div style={{ paddingBottom: 30 }}>
        <button disabled={picked === null || !options[picked].ok} style={{
          width: '100%', height: 56, borderRadius: 18, border: 'none', cursor: 'pointer',
          background: picked !== null && options[picked].ok ? T.primary : (T.dark ? 'rgba(255,255,255,0.07)' : 'rgba(26,39,51,0.06)'),
          color: picked !== null && options[picked].ok ? T.onPrimary : T.faint,
          fontFamily: PP_UI, fontSize: 17, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: picked !== null && options[picked].ok ? `0 8px 20px ${hexA(T.primary, 0.26)}` : 'none',
          transition: 'background .2s, color .2s',
        }}>Continue</button>
      </div>
    </Screen>
  );
}

// ── 5 · SAY IT — mature production review: speak, compare, self-rate ─────
function PhraseSayIt({ T, t }) {
  const phrase = PP_PHRASES.clear;
  const REC = '#C0485A';
  const [stage, setStage] = React.useState('cue'); // cue → rec → compare
  const [rated, setRated] = React.useState(null);  // 'good' | 'again'
  const [playWho, setPlayWho] = React.useState(null); // 'native' | 'you'
  const [speed, setSpeed] = React.useState(1);

  const playBoth = () => {
    const nativeMs = 1300 / speed; // slowed native model takes longer
    setPlayWho('native');
    setTimeout(() => setPlayWho('you'), nativeMs);
    setTimeout(() => setPlayWho(null), nativeMs + 1300);
  };

  const CompareRow = ({ icon, label, who, seed }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, background: T.surface, borderRadius: 18, padding: '13px 18px', border: `0.5px solid ${T.hair}`, boxShadow: T.shadow }}>
      <Icon name={icon} size={18} color={playWho === who ? T.primary : T.faint} />
      <span style={{ fontFamily: PP_UI, fontSize: 13, fontWeight: 600, color: playWho === who ? T.ink : T.sub, width: 48 }}>{label}</span>
      <div style={{ flex: 1 }}>
        <Waveform seed={seed} played={playWho === who ? 0.7 : 0} height={26} count={32} theme={T} style={t.wave || 'bars'} />
      </div>
    </div>
  );

  return (
    <Screen theme={T}>
      <SessionTop theme={T} step={10} total={12} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 8 }}>
        <div style={{ fontFamily: PP_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: T.faint }}>Review &middot; say it</div>

        {stage !== 'compare' ? (
          <>
            {/* production cue: English in, Latvian out */}
            <div style={{ fontFamily: PP_UI, fontSize: 26, fontWeight: 500, color: T.ink, marginTop: 26, letterSpacing: -0.3 }}>{phrase.en}</div>
            <div style={{ fontFamily: PP_UI, fontSize: 14.5, color: T.sub, marginTop: 12 }}>Say it in Latvian.</div>

            <button className="pp-orb" onClick={() => setStage(stage === 'rec' ? 'compare' : 'rec')} aria-label={stage === 'rec' ? 'Stop recording' : 'Record'} style={{
              position: 'relative', width: 84, height: 84, borderRadius: '50%', cursor: 'pointer', marginTop: 44,
              background: stage === 'rec' ? (T.dark ? 'rgba(224,116,138,0.14)' : 'rgba(158,43,58,0.07)') : 'transparent',
              border: `1.5px solid ${stage === 'rec' ? hexA(REC, 0.55) : T.hair}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {stage === 'rec' && [0, 1].map(i => (
                <div key={i} className="pp-voice-ring" style={{
                  position: 'absolute', width: 84, height: 84, borderRadius: '50%',
                  border: `1.5px solid ${REC}`, animation: `ppVoiceRing 2.4s ease-out ${i * 1.2}s infinite`,
                }} />
              ))}
              {stage === 'rec'
                ? <span style={{ width: 26, height: 26, borderRadius: 8, background: REC }} />
                : <Icon name="mic" size={30} color={T.sub} sw={1.8} />}
            </button>
            <div style={{ height: 20, fontFamily: PP_UI, fontSize: 13, color: stage === 'rec' ? REC : T.faint, marginTop: 16, fontWeight: stage === 'rec' ? 600 : 400 }}>
              {stage === 'rec' ? 'Listening\u2026 tap to stop' : 'Tap to record'}
            </div>
          </>
        ) : (
          <>
            <div style={{ marginTop: 20 }}>
              <PhraseLine T={T} t={t} phrase={phrase} size={29} highlightNew={false} />
            </div>
            <div style={{ fontFamily: PP_UI, fontSize: 14.5, color: T.sub, marginTop: 10 }}>{phrase.en}</div>

            {/* native + you, back-to-back */}
            <div style={{ width: '100%', marginTop: 26, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <CompareRow icon="speaker" label="Native" who="native" seed={phrase.seed} />
              <CompareRow icon="mic" label="You" who="you" seed="es-dzeru-you" />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18 }}>
              <button onClick={playBoth} style={{
                display: 'flex', alignItems: 'center', gap: 8, padding: '11px 20px', borderRadius: 99, cursor: 'pointer',
                background: 'transparent', border: `1.5px solid ${hexA(T.primary, 0.45)}`, color: T.primary,
                fontFamily: PP_UI, fontSize: 14, fontWeight: 600,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill={T.primary}><path d="M6 4.5v15a1 1 0 0 0 1.5.87l12-7.5a1 1 0 0 0 0-1.74l-12-7.5A1 1 0 0 0 6 4.5z" /></svg>
                Play back-to-back
              </button>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>
              <SpeedChip theme={T} size="sm" value={speed} onChange={setSpeed} />
            </div>
            <div style={{ height: 16, marginTop: 8, fontFamily: PP_UI, fontSize: 11.5, color: T.faint }}>
              {speed < 1 && <>Slows the native voice only.</>}
            </div>

            <div style={{ height: 22, marginTop: 12, fontFamily: PP_UI, fontSize: 13.5, fontWeight: 500, color: rated === 'good' ? T.good : T.sub }}>
              {rated === 'good' && <>Next review in <b style={{ fontWeight: 700 }}>9 days</b>.</>}
              {rated === 'again' && <>We&rsquo;ll come back to it in <b style={{ fontWeight: 700, color: T.ink }}>10 minutes</b>.</>}
            </div>
          </>
        )}
      </div>

      <div style={{ paddingBottom: 30 }}>
        {stage !== 'compare' ? (
          <button onClick={() => setStage('compare')} style={{
            width: '100%', height: 48, borderRadius: 18, border: 'none', cursor: 'pointer',
            background: 'transparent', color: T.faint, fontFamily: PP_UI, fontSize: 14.5, fontWeight: 600,
          }}>Show the phrase</button>
        ) : (
          <div style={{ display: 'flex', gap: 12 }}>
            <button onClick={() => setRated('again')} style={{
              flex: 1, height: 56, borderRadius: 18, cursor: 'pointer',
              background: rated === 'again' ? (T.dark ? 'rgba(255,255,255,0.08)' : 'rgba(26,39,51,0.06)') : 'transparent',
              border: `1.5px solid ${T.hair}`, color: T.sub, fontFamily: PP_UI, fontSize: 16, fontWeight: 600,
            }}>Not yet</button>
            <button onClick={() => setRated('good')} style={{
              flex: 1, height: 56, borderRadius: 18, border: 'none', cursor: 'pointer',
              background: rated === 'good' ? T.good : T.primary, color: '#fff', fontFamily: PP_UI, fontSize: 16, fontWeight: 600,
              boxShadow: `0 8px 20px ${hexA(rated === 'good' ? T.good : T.primary, 0.24)}`, transition: 'background .2s',
            }}>Got it</button>
          </div>
        )}
      </div>
    </Screen>
  );
}

function PhraseScreen({ T, t, state = 'hear' }) {
  if (state === 'locked') return <PhraseLocked T={T} t={t} />;
  if (state === 'unlock') return <PhraseUnlock T={T} t={t} />;
  if (state === 'meaning') return <PhraseMeaning T={T} t={t} />;
  if (state === 'sayit' || state === 'review') return <PhraseSayIt T={T} t={t} />;
  return <PhraseHear T={T} t={t} />;
}

Object.assign(window, { PhraseScreen });
