import React, { useEffect, Suspense } from 'react';
import { BrowserRouter, useLocation } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { LoadingProvider, useNavigationLoading, useLoading } from './shared/contexts/LoadingContext';
import { CookieConsentProvider } from './shared/contexts/CookieConsentContext';
import { CurrencyProvider } from './features/payments/contexts/CurrencyContext';
import { CompanySettingsProvider } from './shared/contexts/CompanySettingsContext';
import { ThemeProvider } from './shared/contexts/ThemeContext';
import { AuthModalProvider } from './features/auth/contexts/AuthModalContext';
import { AntibotProvider } from './features/auth/contexts/AntibotContext';
import { StepUpAuthProvider } from './features/auth/contexts/StepUpAuthContext';
import { RoomProvider } from './features/rooms/contexts/RoomContext';
import { logDebug } from './shared/utils/errorReporter';
import OfflineIndicator from './shared/components/OfflineIndicator';
import CookieConsentBanner from './shared/components/CookieConsentBanner';
import CookiePreferencesModal from './shared/components/CookiePreferencesModal';
import AnalyticsLoader from './shared/components/AnalyticsLoader';
import Loading from './shared/components/Loading';
import Preloader from './shared/components/Preloader';
import ScrollToTop from './shared/components/ScrollToTop';
import AuthModalManager from './features/auth/components/AuthModalManager';
import StepUpAuthManager from './features/auth/components/StepUpAuthManager';
import useAuthStore from './store/useAuthStore';
import useFavoritesStore from './store/useFavoritesStore';
import AppRouter from './routes/AppRouter';

// Component to track navigation changes - must be inside Router
const NavigationTracker: React.FC = () => {
  const { pathname } = useLocation();
  const { setNavigationLoading } = useLoading();
  
  useEffect(() => {
    setNavigationLoading(true);
    const timer = setTimeout(() => {
      setNavigationLoading(false);
    }, 300);
    return () => clearTimeout(timer);
  }, [pathname, setNavigationLoading]);
  
  return null;
};

// Wrapper component to use navigation loading hook inside CompanySettingsProvider
const PreloaderWrapper: React.FC = () => {
  const { isLoading } = useNavigationLoading();
  return <Preloader isLoading={isLoading} />;
};

function App() {
  const { 
    isAuthenticated, 
    userInfo, 
    logout, 
    initializeAuth 
  } = useAuthStore();
  
  const { 
    fetchFavorites, 
    syncGuestFavorites,
    loadGuestFavorites,
  } = useFavoritesStore();

  useEffect(() => {
    initializeAuth().catch((error) => {
      logDebug('Auth initialization failed', { error: error instanceof Error ? error.message : String(error) });
    });
  }, [initializeAuth]);

  useEffect(() => {
    if (isAuthenticated) {
      syncGuestFavorites().then(() => {
        fetchFavorites();
      });
    } else {
      loadGuestFavorites();
    }
  }, [
    isAuthenticated, 
    fetchFavorites, 
    syncGuestFavorites,
    loadGuestFavorites,
  ]);

  const handleLogout = async () => {
    await logout();
  };

  return (
    <LoadingProvider>
      <CookieConsentProvider>
        <CurrencyProvider>
          <ThemeProvider>
            <CompanySettingsProvider>
              <AntibotProvider>
                <AuthModalProvider>
                  <StepUpAuthProvider>
                    <RoomProvider>
                      <BrowserRouter
                        future={{
                          v7_startTransition: true,
                          v7_relativeSplatPath: true,
                        }}
                      >
                        <PreloaderWrapper />
                        <ScrollToTop />
                        <NavigationTracker />
                        <Suspense fallback={<Loading fullScreen text="Loading page..." />}>
                          <AppRouter
                            isAuthenticated={isAuthenticated}
                            userInfo={userInfo}
                            onLogout={handleLogout}
                          />
                          <ToastContainer 
                            position="top-right"
                            autoClose={3000}
                            hideProgressBar={false}
                            newestOnTop
                            closeOnClick
                            rtl={false}
                            pauseOnFocusLoss
                            draggable
                            pauseOnHover
                            theme="light"
                            toastClassName="rounded-lg shadow-lg"
                            bodyClassName="text-sm font-medium"
                          />
                          <OfflineIndicator />
                          <CookieConsentBanner />
                          <CookiePreferencesModal />
                          <AnalyticsLoader />
                          <AuthModalManager />
                          <StepUpAuthManager />
                        </Suspense>
                      </BrowserRouter>
                    </RoomProvider>
                  </StepUpAuthProvider>
                </AuthModalProvider>
              </AntibotProvider>
            </CompanySettingsProvider>
          </ThemeProvider>
        </CurrencyProvider>
      </CookieConsentProvider>
    </LoadingProvider>
  );
}

export default App;
