import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AppRouter } from '@/routes';
import { setUnauthorizedHandler } from '@/api/client';
import { useAuthStore } from '@/store/authStore';
import { useThemeStore } from '@/store/themeStore';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 1,
      staleTime: 5 * 60 * 1000,
      refetchOnWindowFocus: false,
    },
  },
});

export default function App() {
  const { logout } = useAuthStore();
  const loadThemeFromStorage = useThemeStore((s) => s.loadFromStorage);

  React.useEffect(() => {
    setUnauthorizedHandler(() => {
      logout();
      window.location.href = '/login';
    });
  }, [logout]);

  // Load theme from localStorage on app start
  React.useEffect(() => {
    loadThemeFromStorage();
  }, [loadThemeFromStorage]);

  return (
    <QueryClientProvider client={queryClient}>
      <AppRouter />
    </QueryClientProvider>
  );
}
