/* Duolingo-like course experience — Redmine #12672
 * Maho original content + mascot, inspired by the interaction structure:
 * progress / energy / character prompt / word bank / feedback tray.
 */

const DUO_COURSE_QUESTIONS = [
  {
    id: "q1",
    kind: "choice",
    badge: "新單字",
    title: "選擇正確的翻譯",
    character: "aki",
    speech: "きょうだい",
    reading: "きょうだい",
    prompt: "兄弟姊妹",
    options: ["いつ", "きょうだい", "Wi-Fi"],
    answer: "きょうだい",
    note: "「きょうだい」泛指兄弟姊妹。",
  },
  {
    id: "q2",
    kind: "arrange",
    title: "翻譯這句話",
    character: "maho",
    speech: "おねえさんは いしゃですか。",
    reading: "おねえさんは いしゃですか。",
    answer: ["你", "姐姐", "是", "醫生", "嗎"],
    bank: ["你", "姐姐", "是", "醫生", "嗎", "喜歡", "做飯"],
    note: "「〜ですか」是禮貌疑問句。",
  },
  {
    id: "q3",
    kind: "choice",
    title: "選出日文翻譯",
    character: "ren",
    speech: "你姐姐",
    prompt: "你姐姐",
    options: ["カフェ", "きょうだい", "おねえさん"],
    answer: "おねえさん",
    note: "「おねえさん」可稱呼別人的姐姐。",
  },
  {
    id: "q4",
    kind: "arrange",
    title: "翻譯這句話",
    character: "saki",
    speech: "はい、あにが います。",
    reading: "はい、あにが います。",
    answer: ["是的", "我", "有", "哥哥"],
    bank: ["是的", "我", "有", "哥哥", "妹妹", "醫院"],
    note: "人或動物的「有／在」使用「います」。",
  },
  {
    id: "q5",
    kind: "fill",
    badge: "句型",
    title: "完成日文句子",
    character: "maho",
    speech: "きょうだいは います＿＿",
    prompt: "你有兄弟姊妹嗎？",
    options: ["か", "ね", "よ"],
    answer: "か",
    note: "句尾加「か」構成禮貌疑問。",
  },
  {
    id: "q6",
    kind: "listen",
    title: "聽音後選出意思",
    character: "aki",
    speech: "あねが います。",
    reading: "あねが います。",
    prompt: "（先聽聲音）",
    options: ["我有姐姐", "我有弟弟", "我是姐姐"],
    answer: "我有姐姐",
    note: "「あね」是說自己的姐姐。",
  },
  {
    id: "q7",
    kind: "arrange",
    title: "用日文說出這句話",
    character: "ren",
    speech: "我有一個妹妹。",
    prompt: "我有一個妹妹。",
    answer: ["いもうと", "が", "ひとり", "います"],
    bank: ["いもうと", "が", "ひとり", "います", "おねえさん", "です"],
    note: "兄弟姊妹的人數用「ひとり／ふたり」。",
  },
  {
    id: "q8",
    kind: "choice",
    title: "最後一題：選出自然回答",
    character: "saki",
    speech: "きょうだいは いますか。",
    reading: "きょうだいは いますか。",
    prompt: "你有兄弟姊妹嗎？",
    options: ["はい、あにが います。", "はい、あにですか。", "いいえ、います。"],
    answer: "はい、あにが います。",
    note: "肯定回答：はい＋家人＋が います。",
  },
];

function MahoCourseCharacter({ variant = "maho" }) {
  return (
    <div className={`maho-mascot maho-mascot--${variant}`} aria-hidden="true">
      <div className="mascot-shadow" />
      <div className="mascot-body">
        <span className="mascot-sleeve left" />
        <span className="mascot-sleeve right" />
        <span className="mascot-collar" />
      </div>
      <div className="mascot-head">
        <span className="mascot-ear left" />
        <span className="mascot-ear right" />
        <span className="mascot-hair" />
        <span className="mascot-eye left" />
        <span className="mascot-eye right" />
        <span className="mascot-mouth" />
      </div>
    </div>
  );
}

function DuoProgress({ index, energy, onClose }) {
  return (
    <div className="duo-top">
      <button type="button" className="duo-close" onClick={onClose}>×</button>
      <div className="duo-progress-track">
        <i style={{ width: `${((index + 1) / DUO_COURSE_QUESTIONS.length) * 100}%` }} />
      </div>
      <div className="duo-energy"><span>⚡</span>{energy}</div>
    </div>
  );
}

function SpeechPrompt({ question, onSpeak }) {
  return (
    <div className="duo-prompt-row">
      <MahoCourseCharacter variant={question.character} />
      <button type="button" className="duo-speech" onClick={onSpeak}>
        <Icon name="volume" size={22} />
        <span>{question.speech}</span>
      </button>
    </div>
  );
}

function ArrangeAnswer({ answer, selected, setSelected, checked }) {
  return (
    <>
      <div className="duo-answer-lines">
        <div className="duo-answer-drop">
          {selected.map((tile, idx) => (
            <button
              key={`${tile}-${idx}`}
              type="button"
              disabled={checked}
              onClick={() => setSelected((list) => list.filter((_, i) => i !== idx))}
            >
              {tile}
            </button>
          ))}
        </div>
        <div className="duo-answer-line" />
        <div className="duo-answer-line" />
      </div>
      <div className="duo-word-bank">
        {answer.bank.map((tile, idx) => {
          const usedCount = selected.filter((x) => x === tile).length;
          const priorCount = answer.bank.slice(0, idx).filter((x) => x === tile).length;
          const used = usedCount > priorCount;
          return (
            <button
              key={`${tile}-${idx}`}
              type="button"
              className={used ? "used" : ""}
              disabled={checked || used}
              onClick={() => setSelected((list) => [...list, tile])}
            >
              {used ? "" : tile}
            </button>
          );
        })}
      </div>
    </>
  );
}

function DuoFeedback({ correct, question, onContinue }) {
  return (
    <div className={`duo-feedback ${correct ? "correct" : "wrong"}`}>
      <div className="duo-feedback-title">
        <span>{correct ? "✓" : "!"}</span>
        <strong>{correct ? "答對了！" : "差一點！"}</strong>
      </div>
      <p>{correct ? question.note : `正確答案：${Array.isArray(question.answer) ? question.answer.join(" ") : question.answer}`}</p>
      {!correct ? <small>{question.note}</small> : null}
      <div className="duo-feedback-tools">
        <button type="button">答題解惑</button>
        <button type="button" aria-label="分享">↗</button>
        <button type="button" aria-label="回報">⚑</button>
      </div>
      <button type="button" className="duo-continue" onClick={onContinue}>繼續</button>
    </div>
  );
}

function LessonUnitPathPageDuo({ navigate, onBack }) {
  const toast = useToast();
  const [index, setIndex] = React.useState(0);
  const [selected, setSelected] = React.useState([]);
  const [choice, setChoice] = React.useState(null);
  const [checked, setChecked] = React.useState(false);
  const [correct, setCorrect] = React.useState(false);
  const [energy, setEnergy] = React.useState(25);
  const [score, setScore] = React.useState(0);
  const [finished, setFinished] = React.useState(false);
  const question = DUO_COURSE_QUESTIONS[index];

  const hasAnswer = question.kind === "arrange" ? selected.length > 0 : !!choice;

  const check = () => {
    const ok = question.kind === "arrange"
      ? JSON.stringify(selected) === JSON.stringify(question.answer)
      : choice === question.answer;
    setCorrect(ok);
    setChecked(true);
    if (ok) setScore((s) => s + 1);
    else setEnergy((e) => Math.max(0, e - 1));
  };

  const next = () => {
    if (index >= DUO_COURSE_QUESTIONS.length - 1) {
      setFinished(true);
      return;
    }
    setIndex((i) => i + 1);
    setSelected([]);
    setChoice(null);
    setChecked(false);
    setCorrect(false);
  };

  const restart = () => {
    setIndex(0);
    setSelected([]);
    setChoice(null);
    setChecked(false);
    setCorrect(false);
    setEnergy(25);
    setScore(0);
    setFinished(false);
  };

  if (finished) {
    return (
      <div className="zen-page duo-course duo-course-finish">
        <div className="duo-confetti">✦　･　✧　･　✦</div>
        <MahoCourseCharacter variant="maho" />
        <div className="duo-finish-seal">済</div>
        <small>UNIT 1 COMPLETE</small>
        <h1>家人與兄弟姊妹</h1>
        <p>你已經能聽懂、組句，也能自然回答家人相關問題。</p>
        <div className="duo-finish-stats">
          <div><strong>{score}/{DUO_COURSE_QUESTIONS.length}</strong><span>答對</span></div>
          <div><strong>{energy}</strong><span>剩餘能量</span></div>
          <div><strong>8</strong><span>新詞</span></div>
        </div>
        <div className="duo-finish-learned">
          <span>きょうだい</span><span>おねえさん</span><span>あに</span><span>いもうと</span>
        </div>
        <ZenButton variant="primary" block onClick={() => navigate("/lesson/idle")}>複習本課單字</ZenButton>
        <ZenButton variant="outline" block onClick={restart}>再練一次</ZenButton>
      </div>
    );
  }

  return (
    <div className="zen-page duo-course">
      <DuoProgress index={index} energy={energy} onClose={onBack || (() => navigate("/hub"))} />
      <div className="duo-exercise">
        {question.badge ? <div className="duo-new-word"><span>✦</span>{question.badge}</div> : null}
        <h1>{question.title}</h1>
        <SpeechPrompt
          question={question}
          onSpeak={() => toast.push(`（Mock）播放：${question.reading || question.speech}`, "success")}
        />

        {question.kind === "arrange" ? (
          <ArrangeAnswer answer={question} selected={selected} setSelected={setSelected} checked={checked} />
        ) : (
          <>
            {question.kind === "fill" ? (
              <div className="duo-fill-preview">
                <span>{question.speech.replace("＿＿", "")}</span>
                <i>{choice || "＿"}</i>
              </div>
            ) : null}
            <div className={`duo-choice-list ${question.kind === "fill" ? "compact" : ""}`}>
              {question.options.map((option) => (
                <button
                  key={option}
                  type="button"
                  disabled={checked}
                  className={`${choice === option ? "selected" : ""}${checked && option === question.answer ? " correct" : ""}${checked && choice === option && option !== question.answer ? " wrong" : ""}`}
                  onClick={() => setChoice(option)}
                >
                  {option}
                </button>
              ))}
            </div>
          </>
        )}
      </div>

      {!checked ? (
        <div className="duo-check-wrap">
          <button type="button" className="duo-check" disabled={!hasAnswer} onClick={check}>檢查</button>
        </div>
      ) : (
        <DuoFeedback correct={correct} question={question} onContinue={next} />
      )}
    </div>
  );
}

Object.assign(window, { LessonUnitPathPage: LessonUnitPathPageDuo });
