import { useEffect, useState } from "react";
import AppShell from "./components/layout/AppShell";
import Sidebar from "./components/layout/Sidebar";
import MobileHeader from "./components/layout/MobileHeader";
import EditorPane from "./components/editor/EditorPane";
import { useNotesStore } from "./store/notesStore";
import LoginPage from "./components/auth/LoginPage";
import { clearAuthHeader, getAuthHeader } from "./auth/authStore";

export default function App() {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [route, setRoute] = useState(window.location.pathname);
  const [isAuthed, setIsAuthed] = useState(Boolean(getAuthHeader()));
  const loadNotes = useNotesStore((state) => state.loadNotes);
  const notes = useNotesStore((state) => state.notes);

  useEffect(() => {
    const handlePop = () => setRoute(window.location.pathname);
    window.addEventListener("popstate", handlePop);
    return () => window.removeEventListener("popstate", handlePop);
  }, []);

  useEffect(() => {
    if (!isAuthed) {
      return;
    }
    void loadNotes();
  }, [loadNotes, isAuthed]);

  useEffect(() => {
    if (!isAuthed) {
      return;
    }
    const hasSyncing = notes.some((note) => note.sync.status === "syncing");
    if (!hasSyncing) {
      return;
    }
    const timer = setInterval(() => {
      void loadNotes();
    }, 2000);
    return () => clearInterval(timer);
  }, [isAuthed, notes, loadNotes]);

  const navigate = (path: string) => {
    window.history.pushState({}, "", path);
    setRoute(path);
  };

  const handleLoginSuccess = () => {
    setIsAuthed(true);
    navigate("/");
  };

  const handleLogout = () => {
    clearAuthHeader();
    setIsAuthed(false);
    navigate("/login");
  };

  if (!isAuthed || route === "/login") {
    return <LoginPage onSuccess={handleLoginSuccess} />;
  }

  return (
    <AppShell
      sidebar={<Sidebar onNoteSelect={() => setSidebarOpen(false)} />}
      header={
        <MobileHeader
          onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
          onLogout={handleLogout}
        />
      }
      sidebarOpen={sidebarOpen}
      onCloseSidebar={() => setSidebarOpen(false)}
    >
      <EditorPane />
    </AppShell>
  );
}
