import { useState, useEffect, useCallback } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useAppStore } from "@/stores/app-store";
import { useBoardStore } from "@/stores/board-store";
import { AppShell } from "@/components/layout/AppShell";
import { BoardList } from "@/components/boards/BoardList";
import { BoardView } from "@/components/board/BoardView";
import { CommandPalette } from "@/components/command-palette/CommandPalette";
import { SettingsDialog } from "@/components/settings/SettingsDialog";
import { ToastContainer } from "@/components/toast/ToastContainer";
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";

export default function App() {
  const initialized = useAppStore((s) => s.initialized);
  const init = useAppStore((s) => s.init);
  const view = useAppStore((s) => s.view);

  const [settingsOpen, setSettingsOpen] = useState(false);

  useEffect(() => {
    init();
  }, [init]);

  // Flush pending board saves before the app window closes
  useEffect(() => {
    const unlisten = getCurrentWindow().onCloseRequested(async () => {
      useBoardStore.getState().closeBoard();
    });
    return () => {
      unlisten.then((fn) => fn());
    };
  }, []);

  // Listen for custom event to open settings from TopBar or command palette
  useEffect(() => {
    function handleOpenSettings() {
      setSettingsOpen(true);
    }
    document.addEventListener("open-settings-dialog", handleOpenSettings);
    return () => {
      document.removeEventListener("open-settings-dialog", handleOpenSettings);
    };
  }, []);

  const handleOpenSettings = useCallback(() => {
    setSettingsOpen(true);
  }, []);

  useKeyboardShortcuts();

  if (!initialized) {
    return (
      <div className="flex h-screen items-center justify-center bg-pylon-bg">
        <span className="font-heading text-lg text-pylon-text-secondary">
          Loading...
        </span>
      </div>
    );
  }

  return (
    <>
      <AppShell>
        {view.type === "board-list" ? <BoardList /> : <BoardView />}
      </AppShell>
      <CommandPalette onOpenSettings={handleOpenSettings} />
      <SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} />
      <ToastContainer />
    </>
  );
}
