/* 課程提案 V2：以日文語尾手帖為主題的 8 題學習流程 */

const NOTEBOOK_PATTERNS = [
  {
    id: "kamo",
    ending: "かも",
    short: "未定",
    title: "暫時保留判斷",
    description: "在這段對話裡，說話者只有線索，還不把推測當成事實。",
    example: "またバカになったかも。",
    translation: "可能又故障了。",
  },
  {
    id: "janai",
    ending: "んじゃない？",
    short: "推測",
    title: "邀請對方一起判斷",
    description: "在這段對話裡，說話者提出判斷，也留空間讓對方回應。",
    example: "また勝手に直るんじゃない？",
    translation: "應該又會自己恢復吧？",
  },
  {
    id: "yone",
    ending: "よね",
    short: "共識",
    title: "確認彼此都知道",
    description: "說話者已有判斷，再向對方確認共同認知。",
    example: "外に干すの、嫌いだよね。",
    translation: "你很討厭曬在外面，對吧。",
  },
  {
    id: "rise",
    ending: "？↗",
    short: "提問",
    title: "用升調留下問號",
    description: "日常口語省略「か」，靠語尾升調形成問題。",
    example: "外に干す？",
    translation: "要曬在外面嗎？",
  },
];

const NOTEBOOK_QUESTIONS = [
  {
    id: "n1",
    pattern: "kamo",
    kind: "choice",
    label: "先聽語氣",
    title: "這句話有多確定？",
    speaker: "咲子 → 充",
    context: "烘乾剛停下來，咲子摸到衣服還是濕的。",
    prompt: "<ruby>乾燥<rt>かんそう</rt></ruby>、またバカになったかも。",
    options: ["已經確定故障", "可能故障，還不確定", "要求對方修理"],
    answer: "可能故障，還不確定",
    note: "「かも」刻意保留不確定，不把推測說成事實。",
  },
  {
    id: "n2",
    pattern: "kamo",
    kind: "arrange",
    label: "自己說一次",
    title: "排成保留語氣的句子",
    speaker: "咲子 → 充",
    context: "她只有眼前的線索，還不確定機器真的壞了。",
    prompt: "烘乾功能可能又故障了。",
    answer: ["乾燥、", "また", "バカに", "なった", "かも。"],
    bank: ["乾燥、", "また", "バカに", "なった", "かも。", "よね。"],
    note: "把「かも」放在普通形後面，整句就不會說得太滿。",
  },
  {
    id: "n3",
    pattern: "janai",
    kind: "listen",
    label: "聽對話關係",
    title: "充想表達什麼？",
    speaker: "充 → 咲子",
    context: "咲子擔心機器故障；充想起它上次自己恢復了。",
    prompt: "また<ruby>勝手<rt>かって</rt></ruby>に<ruby>直<rt>なお</rt></ruby>るんじゃない？",
    options: ["命令對方修好", "提出可能的發展", "確認已發生的事"],
    answer: "提出可能的發展",
    note: "在這段對話與語調裡，「んじゃない？」把推測交給對方一起判斷；換一個語調也可能帶有反問。",
  },
  {
    id: "n4",
    pattern: "janai",
    kind: "choice",
    label: "選對句尾",
    title: "哪個回答最像在提出推測？",
    speaker: "充 → 咲子",
    context: "充提出自己的判斷，並期待咲子回應。",
    prompt: "また<ruby>勝手<rt>かって</rt></ruby>に<ruby>直<rt>なお</rt></ruby>る＿＿",
    options: ["かも。", "んじゃない？", "よね。"],
    answer: "んじゃない？",
    note: "這裡不是獨自猜測，而是把推測說給對方聽。",
  },
  {
    id: "n5",
    pattern: "yone",
    kind: "choice",
    label: "辨認共同認知",
    title: "咲子已經知道哪件事？",
    speaker: "咲子 → 充",
    context: "如果不用烘乾，就得把衣服拿到外面曬。",
    prompt: "<ruby>外<rt>そと</rt></ruby>に<ruby>干<rt>ほ</rt></ruby>すの、<ruby>嫌<rt>きら</rt></ruby>いだよね。",
    options: ["對方討厭曬在外面", "對方想買新洗衣機", "對方不會使用烘乾"],
    answer: "對方討厭曬在外面",
    note: "「よね」不是第一次詢問，而是確認雙方已有的共同認知。",
  },
  {
    id: "n6",
    pattern: "yone",
    kind: "arrange",
    label: "讓語氣自然",
    title: "排成確認共識的句子",
    speaker: "咲子 → 充",
    context: "她記得充不喜歡把衣服曬在外面，現在再次確認。",
    prompt: "你很討厭曬在外面，對吧。",
    answer: ["外に", "干すの、", "嫌い", "だよね。"],
    bank: ["外に", "干すの、", "嫌い", "だよね。", "かも。", "ください。"],
    note: "句尾的「よね」同時帶有自己的判斷與向對方確認。",
  },
  {
    id: "n7",
    pattern: "rise",
    kind: "listen",
    label: "只聽語尾",
    title: "升調讓這句話變成什麼？",
    speaker: "咲子 → 充",
    context: "咲子提出替代做法，等充決定。",
    prompt: "<ruby>外<rt>そと</rt></ruby>に<ruby>干<rt>ほ</rt></ruby>す？",
    options: ["建議", "問題", "命令"],
    answer: "問題",
    note: "口語可以省略「か」；最後的升調就是問號。",
  },
  {
    id: "n8",
    pattern: "rise",
    kind: "choice",
    label: "情境驗收",
    title: "哪句最適合日常對話？",
    speaker: "你 → 家人",
    context: "洗衣機不能烘乾，你想問家人要不要拿出去曬。",
    prompt: "你想問家人「要拿去曬嗎？」",
    options: ["外に干す？", "外に干すかも。", "外に干すよね。"],
    answer: "外に干す？",
    note: "簡短的普通形加升調，最符合家人之間的自然提問。",
  },
];

function NotebookPatternTabs({ activeId, collected = [], onSelect }) {
  return (
    <div className="notebook-tabs" aria-label="四種句尾語氣">
      {NOTEBOOK_PATTERNS.map((pattern) => {
        const isActive = pattern.id === activeId;
        const isCollected = collected.includes(pattern.id);
        const className = `${isActive ? "active" : ""}${isCollected ? " collected" : ""}`;
        const content = (
          <>
            <span>{pattern.ending}</span>
            {isCollected ? <i>✓</i> : null}
          </>
        );
        return onSelect ? (
          <button
            key={pattern.id}
            type="button"
            className={className}
            aria-pressed={isActive}
            onClick={() => onSelect(pattern.id)}
          >
            {content}
          </button>
        ) : (
          <div key={pattern.id} className={className} aria-label={`${pattern.ending}：${isCollected ? "已收集" : "尚未收集"}`}>
            {content}
          </div>
        );
      })}
    </div>
  );
}

function NotebookCover() {
  const [activeId, setActiveId] = React.useState("kamo");
  const active = NOTEBOOK_PATTERNS.find((pattern) => pattern.id === activeId);

  return (
    <div className="notebook-cover">
      <div className="notebook-cover__eyebrow">家庭洗衣 · 語尾手帖</div>
      <h1>同一句情境，<br /><em>語尾</em>決定你的態度。</h1>
      <p>點右側的句尾籤，先感受四種說法的距離。</p>

      <section className="notebook-live zen-card">
        <div className="notebook-live__binding" aria-hidden="true"><i /><i /><i /></div>
        <div className="notebook-live__number">UNIT 1 · N4</div>
        <div className="notebook-live__sentence">
          <span><ruby>乾燥<rt>かんそう</rt></ruby>、またバカになった</span>
          <strong>{active.ending}</strong>
        </div>
        <div className="notebook-live__reading">
          <small>{active.short}</small>
          <strong>{active.title}</strong>
          <p>{active.description}</p>
          <div><span>{active.example}</span><span>{active.translation}</span></div>
        </div>
        <NotebookPatternTabs activeId={activeId} onSelect={setActiveId} />
      </section>

      <div className="notebook-cover__promise">
        <span>8 題</span>
        <p><strong>不背四條規則</strong>，而是練到聽見語尾就知道對方的態度。</p>
      </div>
    </div>
  );
}

function NotebookArrange({ question, selected, setSelected, checked }) {
  return (
    <div className="notebook-arrange">
      <div className="notebook-arrange__answer">
        {selected.length ? selected.map((tile, index) => (
          <button
            key={`${tile}-${index}`}
            type="button"
            disabled={checked}
            onClick={() => setSelected((items) => items.filter((_, itemIndex) => itemIndex !== index))}
          >
            {tile}
          </button>
        )) : <span>依序點選詞塊組成句子</span>}
      </div>
      <div className="notebook-arrange__bank">
        {question.bank.map((tile, index) => {
          const usedCount = selected.filter((item) => item === tile).length;
          const priorCount = question.bank.slice(0, index).filter((item) => item === tile).length;
          const used = usedCount > priorCount;
          return (
            <button
              key={`${tile}-${index}`}
              type="button"
              className={used ? "used" : ""}
              disabled={checked || used}
              onClick={() => setSelected((items) => [...items, tile])}
            >
              {tile}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function NotebookExercise({ question, index, choice, setChoice, selected, setSelected, checked, onSpeak }) {
  const pattern = NOTEBOOK_PATTERNS.find((item) => item.id === question.pattern);
  return (
    <div className="notebook-exercise">
      <NotebookPatternTabs
        activeId={checked ? question.pattern : null}
        collected={NOTEBOOK_PATTERNS.slice(0, Math.floor(index / 2)).map((item) => item.id)}
      />

      <div className="notebook-exercise__meta">
        <span>{question.label}</span>
      </div>
      <h1>{question.title}</h1>
      <div className="notebook-context">
        <strong>{question.speaker}</strong>
        <span>{question.context}</span>
      </div>

      <section className={`notebook-prompt zen-card${question.kind === "listen" ? " notebook-prompt--listen" : ""}`}>
        <div className="notebook-prompt__pattern">{checked ? pattern.short : "情境"}</div>
        {question.kind === "listen" ? (
          <button type="button" className="notebook-prompt__audio" onClick={onSpeak}>
            <Icon name="volume" size={25} />
            <span>播放句子</span>
          </button>
        ) : null}
        {question.kind !== "listen" || checked ? (
          <div className="notebook-prompt__text" dangerouslySetInnerHTML={{ __html: question.prompt }} />
        ) : <div className="notebook-prompt__hidden">先聽完整句子，再判斷說話者的態度。</div>}
        {question.kind !== "listen" && /[\u3040-\u30ff\u4e00-\u9faf]/.test(question.prompt) ? (
          <button type="button" className="notebook-prompt__speak" onClick={onSpeak}>
            <Icon name="volume" size={16} /> 聽一次
          </button>
        ) : null}
      </section>

      {question.kind === "arrange" ? (
        <NotebookArrange question={question} selected={selected} setSelected={setSelected} checked={checked} />
      ) : (
        <div className="notebook-options">
          {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" : "",
              ].filter(Boolean).join(" ")}
              onClick={() => setChoice(option)}
            >
              <span>{option}</span>
              {checked && option === question.answer ? <i>✓</i> : null}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function NotebookFeedback({ correct, question }) {
  const answer = Array.isArray(question.answer) ? question.answer.join("") : question.answer;
  return (
    <div className={`notebook-feedback notebook-feedback--${correct ? "correct" : "wrong"}`} role="status">
      <div className="notebook-feedback__mark">{correct ? "✓" : "!"}</div>
      <div>
        <strong>{correct ? "這個語氣對了" : `正解：${answer}`}</strong>
        <p>{question.note}</p>
      </div>
    </div>
  );
}

function NotebookComplete({ score, missedPatterns, navigate, onRestart }) {
  const needsReview = missedPatterns.length > 0;
  return (
    <div className="notebook-complete">
      <div className="notebook-complete__book">
        <span>家庭洗衣</span>
        <strong>語尾手帖</strong>
        <div className="notebook-complete__seal">修了</div>
      </div>
      <h1>{needsReview ? `${missedPatterns.length} 張句尾籤，還要再聽一次。` : "四張句尾籤，收進手帖。"}</h1>
      <p>{needsReview ? "已完成本次練習；待複習的句尾會排進下一輪，不把答完當成學會。" : "現在聽到句尾，你能分辨對方是在保留、推測、確認，還是直接提問。"}</p>
      <div className="notebook-complete__score">
        <strong>{score}<span>/8</span></strong>
        <small>第一次作答正確</small>
      </div>
      <div className="notebook-complete__patterns">
        {NOTEBOOK_PATTERNS.map((pattern) => {
          const review = missedPatterns.includes(pattern.id);
          return (
            <div key={pattern.id} className={review ? "review" : ""}>
              <span>{pattern.ending}</span><small>{review ? "待複習" : pattern.short}</small>
            </div>
          );
        })}
      </div>
      <ZenButton variant="primary" block onClick={() => navigate("/lesson/idle")}>複習本課單字</ZenButton>
      <ZenButton variant="outline" block onClick={onRestart}>再練一次</ZenButton>
    </div>
  );
}

function LessonUnitNotebookV2Page({ navigate, onBack }) {
  const toast = useToast();
  const [view, setView] = React.useState("cover");
  const [index, setIndex] = React.useState(0);
  const [choice, setChoice] = React.useState(null);
  const [selected, setSelected] = React.useState([]);
  const [checked, setChecked] = React.useState(false);
  const [correct, setCorrect] = React.useState(false);
  const [score, setScore] = React.useState(0);
  const [missedPatterns, setMissedPatterns] = React.useState([]);
  const question = NOTEBOOK_QUESTIONS[index];
  const hasAnswer = question.kind === "arrange" ? selected.length > 0 : Boolean(choice);

  const resetAnswer = () => {
    setChoice(null);
    setSelected([]);
    setChecked(false);
    setCorrect(false);
  };

  const checkAnswer = () => {
    const isCorrect = question.kind === "arrange"
      ? JSON.stringify(selected) === JSON.stringify(question.answer)
      : choice === question.answer;
    setCorrect(isCorrect);
    setChecked(true);
    if (isCorrect) setScore((current) => current + 1);
    else setMissedPatterns((items) => [...new Set([...items, question.pattern])]);
  };

  const next = () => {
    if (index === NOTEBOOK_QUESTIONS.length - 1) {
      setView("complete");
      return;
    }
    setIndex((current) => current + 1);
    resetAnswer();
  };

  const restart = () => {
    setIndex(0);
    setScore(0);
    setMissedPatterns([]);
    resetAnswer();
    setView("lesson");
  };

  const footer = view === "cover"
    ? <ZenButton variant="primary" block onClick={() => setView("lesson")}>開始 8 題語氣練習</ZenButton>
    : view === "lesson"
      ? checked
        ? <ZenButton variant="primary" block onClick={next}>{index === NOTEBOOK_QUESTIONS.length - 1 ? "收進語尾手帖" : "下一題"}</ZenButton>
        : <ZenButton variant="primary" block disabled={!hasAnswer} onClick={checkAnswer}>確認這個語氣</ZenButton>
      : null;

  return (
    <CourseShell
      title="語尾手帖 · V2"
      mode="notebook"
      progress={view === "lesson" ? `${index + 1}/8` : view === "complete" ? "完成" : "N4"}
      onBack={view === "cover" ? (onBack || (() => navigate("/hub"))) : () => setView("cover")}
      footer={footer}
    >
      {view === "cover" ? <NotebookCover /> : null}
      {view === "lesson" ? (
        <div className="notebook-lesson">
          <div
            className="notebook-progress"
            role="progressbar"
            aria-label="課程作答進度"
            aria-valuemin="1"
            aria-valuemax={NOTEBOOK_QUESTIONS.length}
            aria-valuenow={index + 1}
          >
            <i style={{ width: `${((index + 1) / NOTEBOOK_QUESTIONS.length) * 100}%` }} />
          </div>
          <NotebookExercise
            question={question}
            index={index}
            choice={choice}
            setChoice={setChoice}
            selected={selected}
            setSelected={setSelected}
            checked={checked}
            onSpeak={() => toast.push(`（Mock）播放：${question.prompt.replace(/<[^>]+>/g, "")}`, "success")}
          />
          {checked ? <NotebookFeedback correct={correct} question={question} /> : null}
        </div>
      ) : null}
      {view === "complete" ? <NotebookComplete score={score} missedPatterns={missedPatterns} navigate={navigate} onRestart={restart} /> : null}
    </CourseShell>
  );
}

Object.assign(window, { LessonUnitNotebookV2Page });
