function App() {
  const [processIndex, setProcessIndex] = React.useState(() => {
    const saved = Number.parseInt(localStorage.getItem("pcb-textbook-process") || "0", 10);
    return Number.isFinite(saved) && saved >= 0 && saved < PCB_PROCESSES.length ? saved : 0;
  });
  const [platingSubIndex, setPlatingSubIndex] = React.useState(() => {
    const saved = Number.parseInt(localStorage.getItem("pcb-textbook-plating-sub") || "2", 10);
    return Number.isFinite(saved) && saved >= 0 && saved < PLATING_SUBSTAGES.length ? saved : 2;
  });
  const [autoPlay, setAutoPlay] = React.useState(false);
  const [defectMode, setDefectMode] = React.useState(false);
  const [depthMode, setDepthMode] = React.useState("quick");
  const [activeTab, setActiveTab] = React.useState("flow");
  const [theme, setTheme] = React.useState(() => localStorage.getItem("pcb-textbook-theme") || "light");

  const process = PCB_PROCESSES[processIndex];
  const stage = process.id === "plating" ? process.subStages[platingSubIndex] : process;
  const previous = PCB_PROCESSES[(processIndex - 1 + PCB_PROCESSES.length) % PCB_PROCESSES.length];
  const next = PCB_PROCESSES[(processIndex + 1) % PCB_PROCESSES.length];

  const navigateToProcess = (index) => {
    setAutoPlay(false);
    setProcessIndex(index);
  };

  React.useEffect(() => {
    localStorage.setItem("pcb-textbook-process", String(processIndex));
    setActiveTab("flow");
    window.requestAnimationFrame(() => {
      document.querySelector(`[data-process-index="${processIndex}"]`)?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
    });
  }, [processIndex]);

  React.useEffect(() => {
    localStorage.setItem("pcb-textbook-plating-sub", String(platingSubIndex));
    if (process.id === "plating") setActiveTab("flow");
  }, [platingSubIndex]);

  React.useEffect(() => {
    document.documentElement.dataset.theme = theme;
    localStorage.setItem("pcb-textbook-theme", theme);
  }, [theme]);

  React.useEffect(() => {
    if (!autoPlay) return undefined;
    const timer = window.setInterval(() => {
      setProcessIndex((current) => (current + 1) % PCB_PROCESSES.length);
    }, 4800);
    return () => window.clearInterval(timer);
  }, [autoPlay]);

  React.useEffect(() => {
    const handleKey = (event) => {
      if (event.key === "ArrowRight") navigateToProcess((processIndex + 1) % PCB_PROCESSES.length);
      if (event.key === "ArrowLeft") navigateToProcess((processIndex - 1 + PCB_PROCESSES.length) % PCB_PROCESSES.length);
      if (event.key.toLowerCase() === "d") setDefectMode((current) => !current);
      if (event.code === "Space" && event.target === document.body) {
        event.preventDefault();
        setAutoPlay((current) => !current);
      }
    };
    window.addEventListener("keydown", handleKey);
    return () => window.removeEventListener("keydown", handleKey);
  }, [processIndex]);

  return (
    <main className="app-shell">
      <header className="topbar">
        <div>
          <p className="eyebrow">PCB EXECUTIVE VISUAL TEXTBOOK · 12 PROCESS MAP</p>
          <h1 className="brand-title">PCB 공정 현미경 <span>원판에서 출하까지</span></h1>
        </div>
        <div className="top-controls">
          <button className="control-button" onClick={() => window.print()} aria-label="현재 화면 인쇄">PRINT</button>
          <button className="control-button" onClick={() => setTheme(theme === "light" ? "dark" : "light")} aria-label="화면 테마 변경">{theme === "light" ? "DARK" : "LIGHT"}</button>
        </div>
      </header>

      <PositionBar processIndex={processIndex} process={process} stage={stage} previous={previous} next={next}></PositionBar>
      <ProcessRail processIndex={processIndex} setProcessIndex={navigateToProcess}></ProcessRail>

      <section className="hero-grid" data-screen-label={`${process.step} ${process.title}`}>
        <div className="visual-zone">
          <StageHeader stage={stage}></StageHeader>
          {process.id === "plating" && (
            <SubProcessRail subStages={process.subStages} subIndex={platingSubIndex} setSubIndex={setPlatingSubIndex}></SubProcessRail>
          )}
          <div className="microscope">
            <CrossSection processIndex={processIndex} platingSubIndex={platingSubIndex} defectMode={defectMode}></CrossSection>
          </div>
          <footer className="visual-footer">
            <div className="legend" aria-label="단면 색상 범례">
              <span className="legend-item"><i className="legend-swatch copper"></i>구리</span>
              <span className="legend-item"><i className="legend-swatch resin"></i>절연재</span>
              <span className="legend-item"><i className="legend-swatch chem"></i>화학 작용</span>
              <span className="legend-item"><i className="legend-swatch danger"></i>결함</span>
            </div>
            <Playback processIndex={processIndex} setProcessIndex={navigateToProcess} autoPlay={autoPlay} setAutoPlay={setAutoPlay}></Playback>
          </footer>
        </div>

        <ExplanationPanel
          stage={stage}
          defectMode={defectMode}
          onDefectMode={setDefectMode}
          depthMode={depthMode}
          onDepthMode={setDepthMode}
        ></ExplanationPanel>
      </section>

      <KnowledgeDock stage={stage} activeTab={activeTab} setActiveTab={setActiveTab}></KnowledgeDock>

      <footer className="source-note">
        <span><strong>이동</strong> 상단 12공정 클릭 · 이전/다음 버튼 · ← → 키보드</span>
        <span><strong>보기</strong> Space 자동재생 · D 정상/불량 · 도금은 4개 세부단계 선택</span>
      </footer>
    </main>
  );
}

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