/* Language Partner — bank-aware UI: live hooks, the "Build vocabulary" panel,
   manual word entry, and the typed conjugation cell. Exported to window so
   screens.jsx can use them as bare identifiers. */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

/* re-render whenever the word bank changes */
function useBank(langId) {
  const [, force] = useStateB(0);
  useEffectB(() => window.LPBank.subscribe(() => force(v => v + 1)), []);
  return {
    words: window.LPBank.all(langId),
    counts: window.LPBank.counts(langId),
    version: window.LPBank.version,
  };
}

/* re-render as today's practice time ticks up */
function useDailyTime() {
  const [, force] = useStateB(0);
  useEffectB(() => window.LPTime.subscribe(() => force(v => v + 1)), []);
  const minutes = window.LPTime.todayMinutes();
  const goal = window.LPTime.goalMinutes();
  return { minutes, goal, pct: Math.min(100, Math.round((minutes / goal) * 100)) };
}

/* accent-forgiving comparison: base letters must match, diacritics may differ */
function baseEq(a, b) {
  const n = s => (s || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/\s+/g, " ");
  return n(a) === n(b);
}

/* the idiom shown today — rotates through Helen's + the seed one, by the day */
function dailyIdiom(seedLang) {
  const pool = [...(window.LPBank.idioms(seedLang.id) || []), ...(seedLang.idiom ? [seedLang.idiom] : [])];
  if (!pool.length) return null;
  const day = Math.floor(Date.now() / 86400000);
  return pool[day % pool.length];
}

const ES_THEMES = ["(auto — mix it up)", "politics", "economics", "birds", "trees", "medicine", "science"];

/* ---------- the build-vocabulary panel ---------- */
function BuildVocab({ lang, accent, onGenerated }) {
  const { counts } = useBank(lang.id);
  const connected = window.LPApi && window.LPApi.isConfigured();
  const reliable = window.LPBank.AI_RELIABLE[lang.id];
  const noun = lang.learnKind === "letters" ? "words" : (lang.learnKind === "glyphs" ? "signs" : "words");

  const [open, setOpen] = useStateB(false);
  const [mode, setMode] = useStateB(reliable ? "generate" : "manual");
  const [focus, setFocus] = useStateB("");
  const [esTheme, setEsTheme] = useStateB(ES_THEMES[0]);
  const [busy, setBusy] = useStateB(false);
  const [status, setStatus] = useStateB(null); // {ok, msg}

  const pct = Math.min(100, Math.round((counts.total / counts.goal) * 100));

  async function generate() {
    if (busy) return;
    setBusy(true); setStatus(null);
    try {
      const f = lang.id === "es" ? (esTheme === ES_THEMES[0] ? "" : esTheme) : focus;
      const r = await window.LPBank.generate(lang, 15, { focus: f });
      setStatus({ ok: true, msg: `Added ${r.added} ${noun}${r.skipped ? ` · skipped ${r.skipped} you already had` : ""}.` });
      if (onGenerated) onGenerated();
    } catch (e) {
      setStatus({ ok: false, msg: e.message || "Couldn't reach Helen." });
    } finally { setBusy(false); }
  }

  return (
    <div className="build" style={{ "--accent": accent }}>
      <div className="build-top" onClick={() => setOpen(o => !o)}>
        <div className="build-bar-wrap">
          <div className="build-bar-head">
            <span className="build-count"><b style={{ color: accent }}>{counts.total}</b> / {counts.goal} {noun}</span>
            <span className="build-pct">{pct}%</span>
          </div>
          <div className="build-bar"><span className="build-fill" style={{ width: pct + "%", background: accent }} /></div>
        </div>
        <button className="build-toggle" style={{ color: accent }} aria-label="Add words">
          <Icon name={open ? "chevron" : "plus"} size={20} />
        </button>
      </div>

      {open ? (
        <div className="build-body">
          {reliable ? (
            <div className="build-modes">
              <button className={"build-mode" + (mode === "generate" ? " on" : "")} onClick={() => setMode("generate")}
                style={mode === "generate" ? { borderColor: accent, color: accent } : null}>Generate with Helen</button>
              <button className={"build-mode" + (mode === "manual" ? " on" : "")} onClick={() => setMode("manual")}
                style={mode === "manual" ? { borderColor: accent, color: accent } : null}>Add my own</button>
            </div>
          ) : (
            <div className="build-caution">
              Helen can't reliably invent {lang.name} {noun}, so add the ones you trust here — she'll still weave them into reading and translation practice.
            </div>
          )}

          {reliable && mode === "generate" ? (
            !connected ? (
              <div className="build-caution">Connect Helen in Settings to generate {noun} automatically.</div>
            ) : (
              <div className="build-gen">
                {lang.id === "es" ? (
                  <label className="build-field">
                    <span className="build-label">Theme</span>
                    <select className="field-select" value={esTheme} onChange={e => setEsTheme(e.target.value)} disabled={busy}>
                      {ES_THEMES.map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                  </label>
                ) : (
                  <label className="build-field">
                    <span className="build-label">Focus <span className="build-opt">(optional)</span></span>
                    <input className="field-input" value={focus} disabled={busy}
                      placeholder="e.g. food, the body, weather — blank for auto"
                      onChange={e => setFocus(e.target.value)} />
                  </label>
                )}
                <button className="btn-primary build-go" onClick={generate} disabled={busy}
                  style={{ background: accent }}>
                  {busy ? "Helen is choosing 15…" : "Generate 15 " + noun}
                </button>
                <div className="build-hint">New {noun} get harder as your bank grows — common words first, advanced later.</div>
              </div>
            )
          ) : null}

          {(!reliable || mode === "manual") ? (
            <AddWordForm lang={lang} accent={accent} noun={noun} onAdded={() => { if (onGenerated) onGenerated(); }} setStatus={setStatus} />
          ) : null}

          {status ? <div className={"build-status " + (status.ok ? "ok" : "no")}>{status.msg}</div> : null}
        </div>
      ) : null}
    </div>
  );
}

function AddWordForm({ lang, accent, noun, onAdded, setStatus }) {
  const [glyph, setGlyph] = useStateB("");
  const [roman, setRoman] = useStateB("");
  const [gloss, setGloss] = useStateB("");
  const [ex, setEx] = useStateB("");
  const glyphRef = useRefB(null);

  function submit() {
    const r = window.LPBank.addOne(lang.id, { glyph, roman, gloss, ex });
    if (!r.ok) { setStatus({ ok: false, msg: r.reason }); return; }
    setStatus({ ok: true, msg: `Added “${r.word.glyph}.”` });
    setGlyph(""); setRoman(""); setGloss(""); setEx("");
    if (glyphRef.current) glyphRef.current.focus();
    if (onAdded) onAdded();
  }

  return (
    <div className="addform">
      <div className="addform-grid">
        <label className="build-field">
          <span className="build-label">Word {lang.learnKind === "glyphs" ? "/ signs" : ""}</span>
          <input ref={glyphRef} className="field-input" data-lang={lang.id} value={glyph}
            placeholder="as written" onChange={e => setGlyph(e.target.value)} />
        </label>
        <label className="build-field">
          <span className="build-label">Pronunciation <span className="build-opt">(optional)</span></span>
          <input className="field-input" value={roman} placeholder="how to say it" onChange={e => setRoman(e.target.value)} />
        </label>
      </div>
      <label className="build-field">
        <span className="build-label">Meaning</span>
        <input className="field-input" value={gloss} placeholder="English meaning" onChange={e => setGloss(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter") submit(); }} />
      </label>
      <label className="build-field">
        <span className="build-label">Example <span className="build-opt">(optional)</span></span>
        <input className="field-input" data-lang={lang.id} value={ex} placeholder="a short sentence" onChange={e => setEx(e.target.value)} />
      </label>
      <button className="btn-ghost addform-go" onClick={submit} disabled={!glyph.trim() || !gloss.trim()}
        style={{ borderColor: accent, color: accent }}>
        <Icon name="plus" size={18} /> Add to my {noun}
      </button>
    </div>
  );
}

/* typed conjugation cell — accent-forgiving spelling check */
function ConjInputCell({ form, langId, accent, reveal, attempt }) {
  const [val, setVal] = useStateB("");
  useEffectB(() => { setVal(""); }, [attempt]);
  const ok = baseEq(val, form.f);
  const state = !reveal ? "" : ok ? " correct" : " wrong";
  return (
    <div className={"conj-cell typed" + state} style={reveal && ok ? { borderColor: accent } : null}>
      <span className="conj-pron">{form.p}</span>
      {!reveal ? (
        <input className="conj-input" data-lang={langId} value={val} placeholder="type…"
          onChange={e => setVal(e.target.value)} spellCheck={false} autoCapitalize="off" autoCorrect="off" />
      ) : (
        <span className="conj-typed-result">
          <span className="conj-typed-mine" data-lang={langId} style={{ color: ok ? accent : "var(--paper-fade)" }}>
            {val.trim() || "—"}
          </span>
          {ok ? <Icon name="check" size={16} style={{ color: accent }} /> :
            <span className="conj-typed-right" data-lang={langId}>{form.f}</span>}
        </span>
      )}
    </div>
  );
}

Object.assign(window, { useBank, useDailyTime, baseEq, dailyIdiom, BuildVocab, AddWordForm, ConjInputCell });
