// App.jsx —— 主应用：路由 + 布局切换 + 解锁态
const App = () => {
  const [unlocked, setUnlocked] = React.useState(false);
  const [route, setRoute] = React.useState({ name: "home" }); // home | student:id | albums
  const [layout, setLayout] = React.useState(() => {
    try { return localStorage.getItem("cls17_layout") || "grid"; }
    catch { return "grid"; }
  });

  React.useEffect(() => {
    try { localStorage.setItem("cls17_layout", layout); } catch {}
  }, [layout]);

  React.useEffect(() => {
    if (sessionStorage.getItem("cls17_unlocked") === "1") setUnlocked(true);
  }, []);

  // HomePage 的 LayoutSwitcher 通过 window._app 读写
  window._app = { layout, setLayout };

  const handleUnlock = () => {
    setUnlocked(true);
    sessionStorage.setItem("cls17_unlocked", "1");
  };

  if (!unlocked) {
    return (
      <div className="page">
        <PasswordGate onUnlock={handleUnlock} classInfo={window.CLASS_INFO} />
      </div>
    );
  }

  const student = route.name === "student"
    ? window.CLASS_STUDENTS.find(s => s.id === route.id)
    : null;

  return (
    <div className="page">
      {route.name === "home" && (
        <HomePage
          classInfo={window.CLASS_INFO}
          students={window.CLASS_STUDENTS}
          layout={layout}
          onOpenStudent={(id) => { setRoute({ name: "student", id }); window.scrollTo(0, 0); }}
          onOpenAlbums={() => { setRoute({ name: "albums" }); window.scrollTo(0, 0); }}
        />
      )}
      {route.name === "student" && student && (
        <StudentDetail
          student={student}
          students={window.CLASS_STUDENTS}
          onClose={() => { setRoute({ name: "home" }); window.scrollTo(0, 0); }}
          onNav={(id) => { setRoute({ name: "student", id }); window.scrollTo(0, 0); }}
        />
      )}
      {route.name === "albums" && (
        <AlbumsPage
          albums={window.CLASS_ALBUMS}
          onClose={() => { setRoute({ name: "home" }); window.scrollTo(0, 0); }}
        />
      )}
    </div>
  );
};

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