/* ============================================================
   flow.jsx — StudyFlow: the core learning loop (window.Flow)
   Used by both 학습(Study) and 복습(Review).
   Per expression:  ① AI 응용 예문 → ② 직접 작문 → ③ AI 평가 → ④ 난이도 평가
   ============================================================ */
const { useState: _uS, useEffect: _uE, useRef: _uR } = React;

function StudyFlow({ items, title, onReview, onExit }) {
  const { Button, IconButton, Icon, FormalityBadge, Tag, AiPill, Spinner } = window.UI;
  const AI = window.AI;

  const [idx, setIdx] = _uS(0);
  const expr = items[idx];

  // per-card state
  const [example, setExample] = _uS(null);    // {sentence, gloss}
  const [exLoading, setExLoading] = _uS(false);
  const [draft, setDraft] = _uS("");
  const [evalRes, setEvalRes] = _uS(null);
  const [evalLoading, setEvalLoading] = _uS(false);
  const [err, setErr] = _uS("");
  const [done, setDone] = _uS(false);
  const taRef = _uR(null);

  // load a fresh example whenever the card changes
  _uE(() => {
    if (!expr) return;
    setExample(null); setDraft(""); setEvalRes(null); setErr("");
    loadExample(true);
    // eslint-disable-next-line
  }, [expr && expr.id]);

  async function loadExample(useSeed) {
    setExLoading(true); setErr("");
    try {
      // fall back to a stored example first paint for speed, then AI
      const r = await AI.freshExample({ expression: expr.expression, meaning: expr.meaning, kind: expr.kind, avoid: [...(expr.examples || []), example && example.sentence].filter(Boolean) });
      setExample(r);
    } catch (e) {
      // fall back to a stored example if the model fails
      if (useSeed && expr.examples && expr.examples.length) setExample({ sentence: expr.examples[0], gloss: "" });
      else setErr("예문을 불러오지 못했어요. 다시 시도해 주세요.");
    } finally { setExLoading(false); }
  }

  async function runEval() {
    if (!draft.trim()) return;
    setEvalLoading(true); setErr("");
    try {
      const r = await AI.evaluateWriting({ expression: expr.expression, meaning: expr.meaning, sentence: draft.trim(), kind: expr.kind });
      setEvalRes(r);
    } catch (e) { setErr("평가를 불러오지 못했어요. 다시 시도해 주세요."); }
    finally { setEvalLoading(false); }
  }

  function rate(rating) {
    const updated = window.Store.applyReview(expr, rating);
    onReview(updated);
    if (idx + 1 >= items.length) setDone(true);
    else setIdx(idx + 1);
  }

  if (!items.length) {
    return <window.UI.EmptyState icon="check" title="복습할 표현이 없어요" sub="오늘 예정된 복습을 모두 마쳤어요. 표현을 더 추가하거나 내일 다시 만나요." action={<Button variant="ghost" onClick={onExit}>돌아가기</Button>} />;
  }

  if (done) {
    return (
      <div className="card rise" style={{ textAlign: "center", padding: "44px 24px" }}>
        <div style={{ width: 52, height: 52, borderRadius: 15, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
          <Icon name="check" size={26} stroke={2.4} />
        </div>
        <div className="h-lg" style={{ marginBottom: 6 }}>{items.length}개 표현을 모두 학습했어요</div>
        <div className="muted" style={{ marginBottom: 22 }}>각 표현의 다음 복습 일정이 업데이트됐어요.</div>
        <Button variant="primary" size="lg" onClick={onExit}>완료</Button>
      </div>
    );
  }

  const pct = Math.round((idx / items.length) * 100);

  return (
    <div>
      {/* header */}
      <div className="row between" style={{ marginBottom: 14 }}>
        <div className="row" style={{ gap: 10 }}>
          <span className="label" style={{ textTransform: "none", letterSpacing: 0, fontSize: 13, fontWeight: 650, color: "var(--ink-2)" }}>{title}</span>
          <span className="faint" style={{ fontSize: 13 }}>{idx + 1} / {items.length}</span>
        </div>
        <Button variant="quiet" size="sm" icon="x" onClick={onExit}>나가기</Button>
      </div>
      <div className="progress" style={{ marginBottom: 22 }}><i style={{ width: `${pct}%` }} /></div>

      <div className="card rise" key={expr.id} style={{ padding: 22 }}>
        {/* the expression */}
        <div className="row wrap" style={{ gap: 8, marginBottom: 6 }}>
          {expr.kind === "word" && <span className="badge" style={{ background: "var(--accent-soft)", color: "var(--accent-ink)" }}>단어</span>}
          <FormalityBadge value={expr.formality} />
          {(expr.tags || []).map((t) => <Tag key={t}>{t}</Tag>)}
        </div>
        <div className="h-xl" style={{ marginBottom: 4 }}>{expr.expression}</div>
        <div className="muted" style={{ fontSize: 16, marginBottom: 20 }}>{expr.meaning}</div>

        {/* ① 응용 예문 */}
        <div className="col" style={{ gap: 8, marginBottom: 22 }}>
          <div className="row between">
            <div className="row" style={{ gap: 8 }}><AiPill>응용 예문</AiPill></div>
            <Button variant="quiet" size="sm" icon="repeat" busy={exLoading} onClick={() => loadExample(false)}>다른 예문</Button>
          </div>
          <div style={{ background: "var(--surface-2)", borderRadius: "var(--r-md)", padding: "14px 16px", minHeight: 56 }}>
            {exLoading && !example ? (
              <div className="row faint" style={{ gap: 8, fontSize: 14 }}><Spinner /> 예문을 만드는 중…</div>
            ) : example ? (
              <div>
                <div style={{ fontSize: 16, fontWeight: 550, lineHeight: 1.5 }}>{example.sentence}</div>
                {example.gloss && <div className="faint" style={{ fontSize: 13.5, marginTop: 5 }}>{example.gloss}</div>}
              </div>
            ) : <div className="faint" style={{ fontSize: 14 }}>예문을 불러오는 중…</div>}
          </div>
        </div>

        {/* ② 직접 작문 */}
        <div className="field" style={{ marginBottom: evalRes ? 20 : 8 }}>
          <label>이 {expr.kind === "word" ? "단어" : "표현"}로 직접 문장을 만들어 보세요</label>
          <textarea ref={taRef} className="textarea" rows={3} placeholder={`"${expr.expression}" 를 넣어 문장을 써보세요…`}
            value={draft} onChange={(e) => setDraft(e.target.value)} disabled={evalLoading} />
        </div>

        {/* ③ AI 평가 */}
        {evalRes && (
          <div className="col rise" style={{ gap: 12, marginBottom: 20 }}>
            {!evalRes.usedExpression && (
              <div className="eval" style={{ background: "var(--warn-soft)", borderColor: "#eadfca" }}>
                <div className="eval-h" style={{ color: "var(--warn)" }}><Icon name="x" size={14} /> 표현 미사용</div>
                <div style={{ marginTop: 6, fontSize: 14.5 }}>이 문장에는 대상 표현이 들어있지 않아요. 표현을 넣어 다시 써볼까요?</div>
              </div>
            )}
            <div className="row" style={{ gap: 10, alignItems: "center" }}>
              <div className="label" style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-2)" }}>평가 점수</div>
              <div className="grow progress"><i style={{ width: `${evalRes.score}%` }} /></div>
              <div style={{ fontWeight: 750, fontSize: 16, letterSpacing: "-.02em" }}>{evalRes.score}</div>
            </div>
            <div className={"eval " + (evalRes.grammarOk ? "g" : "n")}>
              <div className="eval-h"><Icon name="check" size={14} /> 문법 정확성</div>
              <div style={{ marginTop: 6, fontSize: 14.5, lineHeight: 1.55 }}>{evalRes.grammar}</div>
            </div>
            <div className="eval n">
              <div className="eval-h"><Icon name="book" size={14} /> 자연스러움</div>
              <div style={{ marginTop: 6, fontSize: 14.5, lineHeight: 1.55 }}>{evalRes.naturalness}</div>
            </div>
            <div className="eval s">
              <div className="eval-h"><Icon name="sparkles" size={14} /> 더 나은 표현</div>
              <div style={{ marginTop: 6, fontSize: 15.5, fontWeight: 550, lineHeight: 1.5 }}>{evalRes.suggestion}</div>
              {evalRes.suggestionWhy && <div className="faint" style={{ fontSize: 13.5, marginTop: 5 }}>{evalRes.suggestionWhy}</div>}
            </div>
          </div>
        )}

        {err && <div style={{ color: "var(--bad)", fontSize: 13.5, marginBottom: 12 }}>{err}</div>}

        {/* actions */}
        {!evalRes ? (
          <div className="row" style={{ gap: 10 }}>
            <Button variant="primary" icon="sparkles" busy={evalLoading} disabled={!draft.trim()} onClick={runEval}>AI 평가 받기</Button>
            <Button variant="quiet" onClick={() => rate("hard")}>건너뛰기</Button>
          </div>
        ) : (
          <div>
            <div className="label" style={{ marginBottom: 9 }}>얼마나 익숙했나요? · 다음 복습 간격이 정해져요</div>
            <div className="row" style={{ gap: 10 }}>
              <Button variant="ghost" block onClick={() => rate("hard")} className="rate-hard">어려웠음</Button>
              <Button variant="ghost" block onClick={() => rate("good")}>보통</Button>
              <Button variant="primary" block onClick={() => rate("easy")}>쉬웠음</Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.Flow = { StudyFlow };
