import { Switch, Route, Router } from "wouter";
import { useHashLocation } from "wouter/use-hash-location";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider, useQuery, useMutation } from "@tanstack/react-query";
import { TooltipProvider } from "@/components/ui/tooltip";
import NotFound from "@/pages/not-found";
import RecordPage from "@/pages/Record";
import LibraryPage from "@/pages/Library";
import DetailPage from "@/pages/Detail";
import SettingsPage from "@/pages/Settings";
import { AppProvider, useApp } from "@/lib/app-context";
import { AppShell } from "@/components/AppShell";
import { Onboarding } from "@/components/Onboarding";
import { useEffect } from "react";
import type { Settings } from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";

function AppRouter() {
  return (
    <Switch>
      <Route path="/" component={RecordPage} />
      <Route path="/bibliothek" component={LibraryPage} />
      <Route path="/aufnahme/:id" component={DetailPage} />
      <Route path="/einstellungen" component={SettingsPage} />
      <Route component={NotFound} />
    </Switch>
  );
}

function ThemedShell() {
  const { setTheme } = useApp();
  const { data: settings, isLoading } = useQuery<Settings>({ queryKey: ["/api/settings"] });

  const resetMutation = useMutation({
    mutationFn: async () => apiRequest("PATCH", "/api/settings", { onboardingDone: 0 }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["/api/settings"] }),
  });

  // Apply persisted theme.
  useEffect(() => {
    if (settings?.theme === "dark" || settings?.theme === "light") {
      setTheme(settings.theme);
    }
  }, [settings?.theme, setTheme]);

  // Dev shortcut to reset onboarding (Shift+Cmd+O).
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "O" && e.shiftKey && (e.metaKey || e.ctrlKey)) resetMutation.mutate();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [resetMutation]);

  if (isLoading) {
    return <div className="h-full flex items-center justify-center text-sm text-muted-foreground">Lade…</div>;
  }

  const showOnboarding = settings?.onboardingDone === 0;

  return (
    <>
      <AppShell>
        <AppRouter />
      </AppShell>
      {showOnboarding && <Onboarding onDone={() => queryClient.invalidateQueries({ queryKey: ["/api/settings"] })} />}
    </>
  );
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <TooltipProvider>
        <AppProvider>
          <Router hook={useHashLocation}>
            <ThemedShell />
          </Router>
        </AppProvider>
      </TooltipProvider>
    </QueryClientProvider>
  );
}

export default App;
