import { useEffect } from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
import { useUIStore } from '@/stores/ui';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { PWAInstallBanner } from '@/components/pwa/PWAInstallBanner';
import { AppRouter } from '@/router';

export function App() {
  const { refreshUser } = useAuthStore();
  const { setTheme } = useUIStore();

  // Initialiser l'application
  useEffect(() => {
    // Vérifier l'authentification au chargement
    refreshUser();

    // Appliquer le thème au chargement
    const savedTheme = localStorage.getItem('ui-storage');
    if (savedTheme) {
      try {
        const parsed = JSON.parse(savedTheme);
        if (parsed.state?.theme) {
          setTheme(parsed.state.theme);
        }
      } catch (error) {
        console.error('Error parsing theme from localStorage:', error);
      }
    }
  }, [refreshUser, setTheme]);

  return (
    <ErrorBoundary>
      <Router>
        <AppRouter />
        {/* PWA Install Banner */}
        <PWAInstallBanner />
      </Router>
    </ErrorBoundary>
  );
}
