// メインアプリ
const { useState: useState2, useEffect: useEffect2 } = React;
const { Header, StartScreen, QuestionScreen, ResultScreen } = window.Screens;

function App() {
  const [step, setStep] = useState2("start"); // start | question | result
  const [name, setName] = useState2("");
  const [qIndex, setQIndex] = useState2(0);
  const [answers, setAnswers] = useState2({});
  const [result, setResult] = useState2(null);

  function goHome() {
    setStep("start");
    setQIndex(0);
    setAnswers({});
    setResult(null);
  }

  function start() {
    setQIndex(0);
    setAnswers({});
    setResult(null);
    setStep("question");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function answerCurrent(choice) {
    const q = window.QUESTIONS[qIndex];
    const next = { ...answers, [q.id]: choice };
    setAnswers(next);
    setTimeout(() => {
      if (qIndex < window.QUESTIONS.length - 1) {
        setQIndex(qIndex + 1);
        window.scrollTo({ top: 0, behavior: "smooth" });
      } else {
        const r = window.Engine.diagnose({ characterName: name, answers: next });
        setResult(r);
        setStep("result");
        window.scrollTo({ top: 0, behavior: "smooth" });
      }
    }, 220);
  }

  function back() {
    if (qIndex > 0) {
      setQIndex(qIndex - 1);
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  }

  function retry() {
    start();
  }
  function editName() {
    setStep("start");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  return (
    <div className="app">
      <Header onHome={goHome} />
      {step === "start" && (
        <StartScreen name={name} setName={setName} onStart={start} />
      )}
      {step === "question" && (
        <QuestionScreen
          index={qIndex}
          question={window.QUESTIONS[qIndex]}
          answer={answers[window.QUESTIONS[qIndex].id]}
          onAnswer={answerCurrent}
          onBack={back}
          total={window.QUESTIONS.length}
        />
      )}
      {step === "result" && result && (
        <ResultScreen result={result} onRetry={retry} onEditName={editName} />
      )}

      <footer className="site-foot">
        <span>© 脳内メーカー風診断 / ジョークの心理テストです</span>
        <span className="foot-dot">·</span>
        <span>AI不使用・静的ロジック</span>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
