import { useEffect, useState } from "react";
import MainShell from "./components/MainShell";
import AnnotationPage from "./pages/AnnotationPage";
import SecondaryWindow from "./windows/SecondaryWindow";

function App() {
  const [theme, setTheme] = useState(() => localStorage.getItem("theme") || "light");
  const [activeTab, setActiveTab] = useState("clone");
  const [activeKnowledge, setActiveKnowledge] = useState("全部");
  const [activeSkill, setActiveSkill] = useState("全部");
  const [settingSection, setSettingSection] = useState("基础配置");
  const [route, setRoute] = useState(() => window.location.hash.replace("#", "") || "/");

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

  useEffect(() => {
    const onStorage = (event) => {
      if (event.key === "theme" && event.newValue) {
        setTheme(event.newValue);
      }
    };

    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  useEffect(() => {
    const onHashChange = () => setRoute(window.location.hash.replace("#", "") || "/");
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, []);

  const isWindowRoute = route.startsWith("/window/");
  const isAnnotationRoute = route === "/annotate";

  return (
    <div className="min-h-dvh overflow-hidden rounded-[12px] bg-page text-text">
      {isAnnotationRoute ? (
        <AnnotationPage />
      ) : isWindowRoute ? (
        <SecondaryWindow
          route={route}
          theme={theme}
          setTheme={setTheme}
          settingSection={settingSection}
          setSettingSection={setSettingSection}
        />
      ) : (
        <MainShell
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          theme={theme}
          setTheme={setTheme}
          activeKnowledge={activeKnowledge}
          setActiveKnowledge={setActiveKnowledge}
          activeSkill={activeSkill}
          setActiveSkill={setActiveSkill}
        />
      )}
    </div>
  );
}

export default App;
