// screens-learn.jsx — 02a · FIRST EXPOSURE: learning a brand-new word.
// Teaching, not testing — everything is shown, audio stays the hero.
// Three templates by word type:
//   concrete  → picturable noun: image anchor + word + audio
//   abstract  → sound-alike mnemonic + one example phrase
//   function  → grammatical word: meaning through three tiny examples

const PP_LEARN = {
  concrete: {
    step: 1, tagTone: 'primary', tag: 'Noun · picturable',
    word: 'māja', gloss: 'house', pron: 'MAH-ya', seed: 'maja',
  },
  abstract: {
    step: 2, tagTone: 'good', tag: 'Adjective · abstract',
    word: 'brīvs', gloss: 'free · available', pron: 'BREEVS', seed: 'brivs',
  },
  function: {
    step: 3, tagTone: 'neutral', tag: 'Preposition · grammatical',
    word: 'uz', gloss: 'on · to · toward', pron: 'ooz', seed: 'uz',
  },
};

const PP_LEARN_EXAMPLES = {
  abstract: [
    { pre: 'Vai esi ', w: 'brīvs', post: ' rīt?', en: 'Are you free tomorrow?', seed: 'vai-esi-brivs' },
  ],
  function: [
    { pre: 'Grāmata ir ', w: 'uz', post: ' galda.', en: 'The book is on the table.', seed: 'gramata-uz-galda' },
    { pre: 'Es eju ', w: 'uz', post: ' veikalu.', en: 'I\u2019m going to the store.', seed: 'es-eju-uz-veikalu' },
    { pre: 'Paskatīties ', w: 'uz', post: ' mani.', en: 'Look at me.', seed: 'paskatities-uz-mani' },
  ],
};

function LearnTag({ T, tone, text }) {
  const c = tone === 'primary' ? { bg: T.primarySoft, fg: T.primary, bd: hexA(T.primary, 0.3) }
    : tone === 'good' ? { bg: T.goodSoft, fg: T.good, bd: hexA(T.good, 0.35) }
    : { bg: 'transparent', fg: T.sub, bd: T.hair };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', padding: '5px 12px', borderRadius: 99,
      background: c.bg, border: `1px solid ${c.bd}`, color: c.fg,
      fontFamily: PP_UI, fontSize: 11, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase',
    }}>{text}</span>
  );
}

function WordLearnScreen({ T, t, kind = 'concrete' }) {
  const head = ppHeadFont(t);
  const d = PP_LEARN[kind] || PP_LEARN.concrete;
  const examples = PP_LEARN_EXAMPLES[kind] || [];
  const [playing, setPlaying] = React.useState(false);
  const [speed, setSpeed] = React.useState(1);
  const [exPlay, setExPlay] = React.useState(null);

  const playEx = (i) => { setExPlay(i); setTimeout(() => setExPlay(p => (p === i ? null : p)), 1400 / speed); };

  const ExampleRow = ({ ex, i }) => (
    <div onClick={() => playEx(i)} style={{ display: 'flex', alignItems: 'center', gap: 13, cursor: 'pointer', width: '100%' }}>
      <PlayOrb theme={T} size={34} filled={false} playing={exPlay === i} />
      <div style={{ flex: 1, textAlign: 'left' }}>
        <div style={{ fontFamily: head, fontSize: 19, fontWeight: 500, letterSpacing: -0.2, color: T.ink }}>
          {ex.pre}<b style={{ color: T.primary, fontWeight: 500 }}>{ex.w}</b>{ex.post}
        </div>
        <div style={{ fontFamily: PP_UI, fontSize: 13, color: T.sub, marginTop: 2 }}>{ex.en}</div>
      </div>
    </div>
  );

  return (
    <Screen theme={T}>
      <SessionTop theme={T} step={d.step} total={12} />

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 8 }}>
        {/* eyebrow + word-type tag */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontFamily: PP_UI, fontSize: 12, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase', color: T.faint }}>New word</span>
          <LearnTag T={T} tone={d.tagTone} text={d.tag} />
        </div>

        {/* concrete: the picture IS the meaning */}
        {kind === 'concrete' && (
          <div style={{ width: '100%', height: 180, marginTop: 18, borderRadius: 24, overflow: 'hidden', border: `0.5px solid ${T.hair}`, boxShadow: T.shadow }}>
            <img src={T.dark ? 'assets/house-night.svg' : 'assets/house.svg'} alt="a house" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          </div>
        )}

        {/* the word */}
        <div style={{ marginTop: kind === 'concrete' ? 18 : 24 }}>
          <span style={{ fontFamily: head, fontSize: 52, fontWeight: 500, letterSpacing: -0.8, lineHeight: 1 }}>{d.word}</span>
        </div>
        <div style={{ fontFamily: PP_UI, fontSize: 17, color: T.sub, marginTop: 9 }}>
          {d.gloss} <span style={{ color: T.faint }}>&middot; {d.pron}</span>
        </div>

        {/* abstract: sound-alike mnemonic */}
        {kind === 'abstract' && (
          <div style={{ width: '100%', marginTop: 22, background: T.surface, borderRadius: 20, padding: '16px 18px', border: `0.5px solid ${T.hair}`, boxShadow: T.shadow }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span style={{ fontFamily: PP_UI, fontSize: 11, fontWeight: 600, letterSpacing: 1.2, textTransform: 'uppercase', color: T.faint }}>Sounds like</span>
              <span style={{ fontFamily: head, fontSize: 21, fontWeight: 600, color: T.ink }}>&ldquo;brew&rdquo;</span>
            </div>
            <div style={{ fontFamily: head, fontStyle: 'italic', fontSize: 15.5, color: T.sub, marginTop: 8, lineHeight: 1.45 }}>
              picture a free round of beers &mdash; the bartender says &ldquo;this one&rsquo;s on me&rdquo;
            </div>
          </div>
        )}

        {/* examples — one for abstract, three for function words */}
        {examples.length > 0 && (
          <div style={{ width: '100%', marginTop: kind === 'function' ? 24 : 18, display: 'flex', flexDirection: 'column', gap: 16 }}>
            {examples.map((ex, i) => <ExampleRow key={i} ex={ex} i={i} />)}
          </div>
        )}

        {/* audio hero — tap to hear */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, marginTop: kind === 'function' ? 26 : 24 }}>
          {kind === 'concrete' && (
            <div style={{ width: 240 }}>
              <Waveform seed={d.seed} played={playing ? 0.66 : 0} height={44} count={36} theme={T} style={t.wave || 'bars'} />
            </div>
          )}
          <PlayOrb theme={T} size={kind === 'concrete' ? 66 : 58} playing={playing} onClick={() => setPlaying(p => !p)} />
          <SpeedChip theme={T} size="sm" value={speed} onChange={setSpeed} />
          <span style={{ fontFamily: PP_UI, fontSize: 13, color: T.faint, fontWeight: 500 }}>Tap to hear</span>
        </div>
      </div>

      {/* bottom */}
      <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>
  );
}

// ═══════════════════════════════════════════════════════════════════
// 02a-R · PICTURE REVIEW — the next time a learned picture-word returns.
// Core loop on a concrete noun: picture (meaning) + audio in →
// pick the word (meaning out) → say it (audio out).
// ═══════════════════════════════════════════════════════════════════
function WordPicReviewScreen({ T, t, initialStage = 'choose' }) {
  const head = ppHeadFont(t);
  const [stage, setStage] = React.useState(initialStage); // choose → speak → rec → result
  const [choice, setChoice] = React.useState(null);
  const [playing, setPlaying] = React.useState(false);
  const [speed, setSpeed] = React.useState(1);
  const [playWho, setPlayWho] = React.useState(null);

  const correct = 'māja';
  const options = [
    { lv: 'māja', en: 'house' },
    { lv: 'maize', en: 'bread' },
    { lv: 'jūra', en: 'sea' },
    { lv: 'mašīna', en: 'car' },
  ];
  const right = choice === correct;
  const pickedEn = choice ? options.find(o => o.lv === choice).en : '';
  const houseSrc = T.dark ? 'assets/house-night.svg' : 'assets/house.svg';

  const playOne = (who, ms) => { setPlayWho(who); setTimeout(() => setPlayWho(w => (w === who ? null : w)), ms); };
  const playBoth = () => {
    const nativeMs = 1100 / speed;
    setPlayWho('native');
    setTimeout(() => setPlayWho('you'), nativeMs);
    setTimeout(() => setPlayWho(null), nativeMs + 1100);
  };

  const CompareRow = ({ icon, label, who, seed }) => (
    <div onClick={() => playOne(who, who === 'native' ? 1100 / speed : 1100)} style={{ display: 'flex', alignItems: 'center', gap: 14, background: T.surface, borderRadius: 18, padding: '13px 18px', border: `0.5px solid ${playWho === who ? hexA(T.primary, 0.4) : T.hair}`, boxShadow: T.shadow, cursor: 'pointer' }}>
      <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>
  );

  // picture stays small once we're past the pick — the word becomes the hero
  const PicThumb = ({ size = 116 }) => (
    <div style={{ width: size, height: size, borderRadius: 20, overflow: 'hidden', border: `0.5px solid ${T.hair}`, boxShadow: T.shadow }}>
      <img src={houseSrc} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
    </div>
  );

  return (
    <Screen theme={T}>
      <SessionTop theme={T} step={4} 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; picture</div>

        {stage === 'choose' && (
          <>
            {/* meaning cue = the picture; audio in = tap to hear */}
            <div style={{ width: '100%', height: 168, marginTop: 18, borderRadius: 24, overflow: 'hidden', border: `0.5px solid ${T.hair}`, boxShadow: T.shadow }}>
              <img src={houseSrc} alt="picture clue" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
              <PlayOrb theme={T} size={44} filled={false} playing={playing} onClick={() => setPlaying(p => !p)} />
              <SpeedChip theme={T} size="sm" value={speed} onChange={setSpeed} />
            </div>
            <div style={{ fontFamily: PP_UI, fontSize: 14.5, color: T.sub, marginTop: 14 }}>Which word names it?</div>

            <div style={{ width: '100%', marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {options.map(o => {
                const isPicked = choice === o.lv;
                const isCorrect = o.lv === correct;
                let bg = T.surface, bd = T.hair, fg = T.ink;
                if (choice) {
                  if (isCorrect) { bg = T.goodSoft; bd = hexA(T.good, 0.5); fg = T.good; }
                  else if (isPicked) { bg = T.dark ? 'rgba(224,116,138,0.12)' : 'rgba(158,43,58,0.07)'; bd = hexA('#C0485A', 0.45); fg = '#C0485A'; }
                  else { fg = T.faint; }
                }
                return (
                  <button key={o.lv} disabled={!!choice} onClick={() => setChoice(o.lv)} style={{
                    minHeight: 52, borderRadius: 16, cursor: choice ? 'default' : 'pointer',
                    background: bg, border: `1.5px solid ${bd}`, color: fg,
                    fontFamily: head, fontSize: 19, fontWeight: 500,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, padding: '0 12px',
                    boxShadow: choice ? 'none' : T.shadow,
                  }}>
                    {o.lv}
                    {choice && isCorrect && <Icon name="check" size={17} color={T.good} sw={2.4} />}
                  </button>
                );
              })}
            </div>

            <div style={{ height: 20, marginTop: 12, fontFamily: PP_UI, fontSize: 13.5, fontWeight: 500, color: right ? T.good : T.sub, textAlign: 'center' }}>
              {choice && (right
                ? <>That&rsquo;s it &mdash; now say it out loud.</>
                : <>It&rsquo;s <b style={{ fontFamily: head, fontWeight: 600, color: T.ink }}>māja</b> &mdash; <b style={{ fontFamily: head, fontWeight: 600 }}>{choice}</b> means &ldquo;{pickedEn}&rdquo;.</>)}
            </div>
          </>
        )}

        {(stage === 'speak' || stage === 'rec') && (
          <>
            <div style={{ marginTop: 8 }}><PicThumb /></div>
            <div style={{ marginTop: 16 }}>
              <span style={{ fontFamily: head, fontSize: 50, fontWeight: 500, letterSpacing: -0.8, lineHeight: 1 }}>māja</span>
            </div>
            <div style={{ fontFamily: PP_UI, fontSize: 13.5, color: T.faint, marginTop: 9 }}>house &middot; MAH-ya</div>

            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 11, marginTop: 22 }}>
              <PlayOrb theme={T} size={52} filled={false} playing={playing} onClick={() => setPlaying(p => !p)} />
              <SpeedChip theme={T} size="sm" value={speed} onChange={setSpeed} />
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: 24 }}>
              <MicOrb theme={T} rec={stage === 'rec'} onClick={() => setStage(stage === 'rec' ? 'result' : 'rec')} />
              <div style={{ height: 18, fontFamily: PP_UI, fontSize: 13, color: stage === 'rec' ? '#C0485A' : T.faint, marginTop: 12, fontWeight: stage === 'rec' ? 600 : 400 }}>
                {stage === 'rec' ? 'Listening… tap to stop' : 'Now say it'}
              </div>
            </div>
          </>
        )}

        {stage === 'result' && (
          <>
            <div style={{ marginTop: 8 }}><PicThumb size={104} /></div>
            <div style={{ marginTop: 14 }}>
              <span style={{ fontFamily: head, fontSize: 48, fontWeight: 500, letterSpacing: -0.8, lineHeight: 1 }}>māja</span>
            </div>
            <div style={{ fontFamily: PP_UI, fontSize: 15, color: T.sub, marginTop: 9 }}>house &middot; <span style={{ color: T.faint }}>MAH-ya</span></div>

            <div style={{ width: '100%', marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <CompareRow icon="speaker" label="Native" who="native" seed="maja-native" />
              <CompareRow icon="mic" label="You" who="you" seed="maja-you" />
            </div>
            <button onClick={playBoth} style={{
              display: 'flex', alignItems: 'center', gap: 8, padding: '11px 20px', borderRadius: 99, cursor: 'pointer', marginTop: 14,
              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 style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: T.goodSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="check" size={13} color={T.good} sw={2.4} />
              </div>
              <span style={{ fontFamily: PP_UI, fontSize: 14, fontWeight: 500, color: T.sub }}>
                {right
                  ? <>Sounded right &mdash; next review in <b style={{ color: T.ink, fontWeight: 700 }}>5 days</b>.</>
                  : <>Sounded right &mdash; the missed pick brings it back in <b style={{ color: T.ink, fontWeight: 700 }}>2 days</b>.</>}
              </span>
            </div>
          </>
        )}
      </div>

      {/* bottom */}
      <div style={{ paddingBottom: 30 }}>
        {stage === 'choose' ? (
          choice ? (
            <button onClick={() => setStage('speak')} 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', gap: 9,
              boxShadow: `0 8px 20px ${hexA(T.primary, 0.26)}`,
            }}><Icon name="mic" size={19} color={T.onPrimary} /> Now say it</button>
          ) : (
            <div style={{ textAlign: 'center', fontFamily: PP_UI, fontSize: 13.5, color: T.faint, fontWeight: 500, padding: '18px 0' }}>
              Name the picture, then say it — that&rsquo;s the full loop.
            </div>
          )
        ) : stage === 'result' ? (
          <button style={{
            width: '100%', height: 56, borderRadius: 18, border: 'none', cursor: 'pointer',
            background: T.good, color: '#fff', fontFamily: PP_UI, fontSize: 17, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
            boxShadow: `0 8px 20px ${hexA(T.good, 0.26)}`,
          }}>
            <Icon name="check" size={19} color="#fff" />
            Continue
          </button>
        ) : (
          <div style={{ textAlign: 'center', fontFamily: PP_UI, fontSize: 13.5, color: T.faint, fontWeight: 500, padding: '18px 0' }}>
            Speaking it closes the loop.
          </div>
        )}
      </div>
    </Screen>
  );
}

Object.assign(window, { WordLearnScreen, WordPicReviewScreen });
