/* global React, SuguruKotoba */
const { useState, useEffect, useRef } = React;

// ---------- Kotoba loader overlay ----------
// Shows while a puzzle is being generated. Presents a Japanese word and asks the
// user to pick the correct meaning (in their active language) from 3 choices.
// Rounds rotate every ~6s or after an answer.
function KotobaLoader({ t, lang, onSkip, visible, progress }) {
  const [round, setRound] = useState(() => SuguruKotoba.pickRound(lang));
  const [answered, setAnswered] = useState(null); // romaji of picked
  const [solvedCount, setSolvedCount] = useState(0);
  const [streak, setStreak] = useState(0);
  const seenRef = useRef(new Set());
  const timeoutRef = useRef(null);

  // Auto-advance after answer
  useEffect(() => {
    if (!visible) return;
    if (answered) {
      timeoutRef.current = setTimeout(() => next(), 1400);
      return () => clearTimeout(timeoutRef.current);
    }
    // If user doesn't answer, gently advance after a while
    timeoutRef.current = setTimeout(() => next(), 9000);
    return () => clearTimeout(timeoutRef.current);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [round, answered, visible]);

  // Reset when opened
  useEffect(() => {
    if (visible) {
      seenRef.current = new Set();
      setRound(SuguruKotoba.pickRound(lang));
      setAnswered(null);
      setSolvedCount(0);
      setStreak(0);
    }
  }, [visible, lang]);

  function next() {
    seenRef.current.add(round.target.romaji);
    setRound(SuguruKotoba.pickRound(lang, seenRef.current));
    setAnswered(null);
  }

  function pick(romaji) {
    if (answered) return;
    setAnswered(romaji);
    if (romaji === round.target.romaji) {
      setSolvedCount(s => s + 1);
      setStreak(s => s + 1);
    } else {
      setStreak(0);
    }
  }

  if (!visible) return null;

  const isCorrect = answered === round.target.romaji;
  const meaning = SuguruKotoba.meaningFor(round.target, lang);

  return (
    <div className="kotoba-overlay" role="dialog" aria-label={t.loading || 'Generating'}>
      <div className="kotoba-card">
        <div className="kotoba-head">
          <div className="kotoba-label">
            <span className="kanji-dot">言</span>
            <span>{t.kotoba_title || 'Kotoba'}</span>
          </div>
          <div className="kotoba-prog">
            <span className="kotoba-dots">
              {[0,1,2].map(i => (
                <span key={i} className={`kd kd-${i}`} />
              ))}
            </span>
            <span className="kotoba-gen">{t.generating}</span>
          </div>
        </div>

        {progress && progress.total > 1 && (
          <div className="kotoba-batch">
            <div className="kotoba-batch-label">
              <span>{t.generating}</span>
              <span className="kotoba-batch-count">
                {progress.done} / {progress.total}
              </span>
            </div>
            <div className="kotoba-batch-bar">
              <div
                className="kotoba-batch-fill"
                style={{width: `${(progress.done / progress.total) * 100}%`}}
              />
            </div>
          </div>
        )}

        <div className="kotoba-word">
          <div className="kotoba-jp" lang="ja">{round.target.jp}</div>
          <div className="kotoba-kana" lang="ja">{round.target.kana}</div>
          <div className="kotoba-romaji">{round.target.romaji}</div>
        </div>

        <div className="kotoba-prompt">{t.kotoba_prompt || 'Choose the meaning'}</div>

        <div className="kotoba-choices">
          {round.choices.map((w) => {
            const picked = answered === w.romaji;
            const isAnswer = w.romaji === round.target.romaji;
            let cls = 'kotoba-choice';
            if (answered) {
              if (isAnswer) cls += ' correct';
              else if (picked) cls += ' wrong';
              else cls += ' faded';
            }
            return (
              <button key={w.romaji} className={cls}
                disabled={!!answered}
                onClick={() => pick(w.romaji)}>
                <span className="kc-text">{SuguruKotoba.meaningFor(w, lang)}</span>
                {answered && isAnswer && <span className="kc-mark">✓</span>}
                {answered && picked && !isAnswer && <span className="kc-mark">✕</span>}
              </button>
            );
          })}
        </div>

        {answered && (
          <div className={`kotoba-feedback ${isCorrect ? 'ok' : 'no'}`}>
            {isCorrect
              ? (t.kotoba_correct || 'Yes — that is') + ` "${meaning}".`
              : (t.kotoba_wrong || 'The answer is') + ` "${meaning}".`}
          </div>
        )}

        <div className="kotoba-foot">
          <div className="kotoba-stats">
            <span>{t.kotoba_learned || 'Learned'}: <b>{solvedCount}</b></span>
            {streak >= 3 && <span className="streak">🔥 {streak}</span>}
          </div>
          {onSkip && (
            <button className="kotoba-skip ghost-btn" onClick={onSkip}>
              {t.cancel || 'Cancel'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

window.KotobaLoader = KotobaLoader;
