import { useEffect, lazy, Suspense } from 'react';
import { 
  BrowserRouter, 
  Routes, 
  Route, 
  Navigate 
} from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { GlobalLoadingProvider } from './contexts/GlobalLoadingContext';
import { CookieConsentProvider } from './contexts/CookieConsentContext';
import { CurrencyProvider } from './contexts/CurrencyContext';
import { CompanySettingsProvider } from './contexts/CompanySettingsContext';
import { AuthModalProvider } from './contexts/AuthModalContext';
import { NavigationLoadingProvider, useNavigationLoading } from './contexts/NavigationLoadingContext';
import OfflineIndicator from './components/common/OfflineIndicator';
import CookieConsentBanner from './components/common/CookieConsentBanner';
import CookiePreferencesModal from './components/common/CookiePreferencesModal';
import AnalyticsLoader from './components/common/AnalyticsLoader';
import Loading from './components/common/Loading';
import Preloader from './components/common/Preloader';
import ScrollToTop from './components/common/ScrollToTop';
import AuthModalManager from './components/modals/AuthModalManager';
import ResetPasswordRouteHandler from './components/auth/ResetPasswordRouteHandler';

import useAuthStore from './store/useAuthStore';
import useFavoritesStore from './store/useFavoritesStore';

import { LayoutMain } from './components/layout';
import AdminLayout from './pages/AdminLayout';

import { 
  ProtectedRoute, 
  AdminRoute,
  StaffRoute,
  AccountantRoute,
  CustomerRoute
} from './components/auth';

const HomePage = lazy(() => import('./pages/HomePage'));
const DashboardPage = lazy(() => import('./pages/customer/DashboardPage'));
const RoomListPage = lazy(() => import('./pages/customer/RoomListPage'));
const RoomDetailPage = lazy(() => import('./pages/customer/RoomDetailPage'));
const SearchResultsPage = lazy(() => import('./pages/customer/SearchResultsPage'));
const FavoritesPage = lazy(() => import('./pages/customer/FavoritesPage'));
const MyBookingsPage = lazy(() => import('./pages/customer/MyBookingsPage'));
const BookingSuccessPage = lazy(() => import('./pages/customer/BookingSuccessPage') as Promise<{ default: React.ComponentType<any> }>);
const BookingDetailPage = lazy(() => import('./pages/customer/BookingDetailPage'));
const FullPaymentPage = lazy(() => import('./pages/customer/FullPaymentPage'));
const PaymentConfirmationPage = lazy(() => import('./pages/customer/PaymentConfirmationPage'));
const PaymentResultPage = lazy(() => import('./pages/customer/PaymentResultPage'));
const PayPalReturnPage = lazy(() => import('./pages/customer/PayPalReturnPage'));
const PayPalCancelPage = lazy(() => import('./pages/customer/PayPalCancelPage'));
const BoricaReturnPage = lazy(() => import('./pages/customer/BoricaReturnPage'));
const InvoicePage = lazy(() => import('./pages/customer/InvoicePage'));
const ProfilePage = lazy(() => import('./pages/customer/ProfilePage'));
const LoyaltyPage = lazy(() => import('./pages/customer/LoyaltyPage'));
const GroupBookingPage = lazy(() => import('./pages/customer/GroupBookingPage'));
const AboutPage = lazy(() => import('./pages/AboutPage'));
const ContactPage = lazy(() => import('./pages/ContactPage'));
const PrivacyPolicyPage = lazy(() => import('./pages/PrivacyPolicyPage'));
const TermsPage = lazy(() => import('./pages/TermsPage'));
const RefundsPolicyPage = lazy(() => import('./pages/RefundsPolicyPage'));
const CancellationPolicyPage = lazy(() => import('./pages/CancellationPolicyPage'));
const AccessibilityPage = lazy(() => import('./pages/AccessibilityPage'));
const FAQPage = lazy(() => import('./pages/FAQPage'));

const AdminDashboardPage = lazy(() => import('./pages/admin/DashboardPage'));
const InvoiceManagementPage = lazy(() => import('./pages/admin/InvoiceManagementPage'));
const PaymentManagementPage = lazy(() => import('./pages/admin/PaymentManagementPage'));
const UserManagementPage = lazy(() => import('./pages/admin/UserManagementPage'));
const GuestProfilePage = lazy(() => import('./pages/admin/GuestProfilePage'));
const BookingManagementPage = lazy(() => import('./pages/admin/BookingManagementPage'));
const GroupBookingManagementPage = lazy(() => import('./pages/admin/GroupBookingManagementPage'));
const PageContentDashboardPage = lazy(() => import('./pages/admin/PageContentDashboard'));
const AnalyticsDashboardPage = lazy(() => import('./pages/admin/AnalyticsDashboardPage'));
const BusinessDashboardPage = lazy(() => import('./pages/admin/BusinessDashboardPage'));
const SettingsPage = lazy(() => import('./pages/admin/SettingsPage'));
const TaskManagementPage = lazy(() => import('./pages/admin/TaskManagementPage'));
const WorkflowManagementPage = lazy(() => import('./pages/admin/WorkflowManagementPage'));
const NotificationManagementPage = lazy(() => import('./pages/admin/NotificationManagementPage'));
const ReceptionDashboardPage = lazy(() => import('./pages/admin/ReceptionDashboardPage'));
const LoyaltyManagementPage = lazy(() => import('./pages/admin/LoyaltyManagementPage'));
const AdvancedRoomManagementPage = lazy(() => import('./pages/admin/AdvancedRoomManagementPage'));
const RatePlanManagementPage = lazy(() => import('./pages/admin/RatePlanManagementPage'));
const PackageManagementPage = lazy(() => import('./pages/admin/PackageManagementPage'));
const SecurityManagementPage = lazy(() => import('./pages/admin/SecurityManagementPage'));
const EmailCampaignManagementPage = lazy(() => import('./pages/admin/EmailCampaignManagementPage'));

const StaffDashboardPage = lazy(() => import('./pages/staff/DashboardPage'));
const StaffBookingManagementPage = lazy(() => import('./pages/staff/BookingManagementPage'));
const StaffReceptionDashboardPage = lazy(() => import('./pages/staff/ReceptionDashboardPage'));
const StaffPaymentManagementPage = lazy(() => import('./pages/staff/PaymentManagementPage'));
const StaffAnalyticsDashboardPage = lazy(() => import('./pages/staff/AnalyticsDashboardPage'));
const StaffLoyaltyManagementPage = lazy(() => import('./pages/staff/LoyaltyManagementPage'));
const StaffGuestProfilePage = lazy(() => import('./pages/staff/GuestProfilePage'));
const StaffAdvancedRoomManagementPage = lazy(() => import('./pages/staff/AdvancedRoomManagementPage'));
const ChatManagementPage = lazy(() => import('./pages/staff/ChatManagementPage'));
const StaffLayout = lazy(() => import('./pages/StaffLayout'));

const AccountantDashboardPage = lazy(() => import('./pages/accountant/DashboardPage'));
const AccountantPaymentManagementPage = lazy(() => import('./pages/accountant/PaymentManagementPage'));
const AccountantInvoiceManagementPage = lazy(() => import('./pages/accountant/InvoiceManagementPage'));
const AccountantAnalyticsDashboardPage = lazy(() => import('./pages/accountant/AnalyticsDashboardPage'));
const AccountantLayout = lazy(() => import('./pages/AccountantLayout'));

const NotFoundPage = lazy(() => import('./pages/NotFoundPage'));

// 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();
  }, [initializeAuth]);

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

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

  return (
    <GlobalLoadingProvider>
      <CookieConsentProvider>
        <CurrencyProvider>
          <CompanySettingsProvider>
            <AuthModalProvider>
      <BrowserRouter
        future={{
          v7_startTransition: true,
          v7_relativeSplatPath: true,
        }}
      >
        <NavigationLoadingProvider>
          <PreloaderWrapper />
          <ScrollToTop />
          <Suspense fallback={<Loading fullScreen text="Loading page..." />}>
          <Routes>
        {}
        <Route 
          path="/" 
          element={
            <LayoutMain 
              isAuthenticated={isAuthenticated}
              userInfo={userInfo}
              onLogout={handleLogout}
            />
          }
        >
          <Route index element={<HomePage />} />
          <Route 
            path="rooms" 
            element={<RoomListPage />} 
          />
          <Route 
            path="rooms/search" 
            element={<SearchResultsPage />} 
          />
          <Route 
            path="rooms/:room_number" 
            element={<RoomDetailPage />} 
          />
          <Route 
            path="favorites" 
            element={
              <CustomerRoute>
                <FavoritesPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="payment-result" 
            element={<PaymentResultPage />} 
          />
          <Route 
            path="payment/paypal/return" 
            element={<PayPalReturnPage />} 
          />
          <Route 
            path="payment/paypal/cancel" 
            element={<PayPalCancelPage />} 
          />
          <Route 
            path="payment/borica/return" 
            element={<BoricaReturnPage />} 
          />
          <Route 
            path="invoices/:id" 
            element={
              <ProtectedRoute>
                <InvoicePage />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="about" 
            element={<AboutPage />} 
          />
          <Route 
            path="contact" 
            element={<ContactPage />} 
          />
          <Route 
            path="privacy" 
            element={<PrivacyPolicyPage />} 
          />
          <Route 
            path="terms" 
            element={<TermsPage />} 
          />
          <Route 
            path="refunds" 
            element={<RefundsPolicyPage />} 
          />
          <Route 
            path="cancellation" 
            element={<CancellationPolicyPage />} 
          />
          <Route 
            path="accessibility" 
            element={<AccessibilityPage />} 
          />
          <Route 
            path="faq" 
            element={<FAQPage />} 
          />
          
          {}
          <Route 
            path="dashboard" 
            element={
              <ProtectedRoute>
                <DashboardPage />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="booking-success/:id" 
            element={
              <CustomerRoute>
                <BookingSuccessPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="bookings" 
            element={
              <CustomerRoute>
                <MyBookingsPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="bookings/:id" 
            element={
              <CustomerRoute>
                <BookingDetailPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="payment/:bookingId" 
            element={
              <CustomerRoute>
                <FullPaymentPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="payment-confirmation/:id" 
            element={
              <CustomerRoute>
                <PaymentConfirmationPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="profile" 
            element={
              <ProtectedRoute>
                <ProfilePage />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="loyalty" 
            element={
              <CustomerRoute>
                <LoyaltyPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="group-bookings" 
            element={
              <CustomerRoute>
                <GroupBookingPage />
              </CustomerRoute>
            } 
          />
        </Route>

        {}
        <Route 
          path="/reset-password/:token" 
          element={<ResetPasswordRouteHandler />} 
        />

        {}
        <Route 
          path="/admin" 
          element={
            <AdminRoute>
              <AdminLayout />
            </AdminRoute>
          }
        >
          <Route 
            index 
            element={<Navigate to="dashboard" replace />} 
          />
          <Route path="dashboard" element={<AdminDashboardPage />} />
          <Route 
            path="users" 
            element={<UserManagementPage />} 
          />
          <Route
            path="business" 
            element={<BusinessDashboardPage />} 
          />
          <Route 
            path="reception" 
            element={<ReceptionDashboardPage />} 
          />
          <Route 
            path="advanced-rooms" 
            element={<AdvancedRoomManagementPage />} 
          />
          <Route 
            path="page-content" 
            element={<PageContentDashboardPage />} 
          />
          <Route 
            path="analytics" 
            element={<AnalyticsDashboardPage />} 
          />
          <Route 
            path="tasks" 
            element={<TaskManagementPage />} 
          />
          <Route 
            path="workflows" 
            element={<WorkflowManagementPage />} 
          />
          <Route 
            path="notifications" 
            element={<NotificationManagementPage />} 
          />
          <Route
            path="settings" 
            element={<SettingsPage />} 
          />
          <Route
            path="invoices" 
            element={<InvoiceManagementPage />} 
          />
          <Route
            path="invoices/:id" 
            element={<InvoicePage />} 
          />
          <Route
            path="payments" 
            element={<PaymentManagementPage />} 
          />
          <Route
            path="loyalty" 
            element={<LoyaltyManagementPage />} 
          />
          <Route
            path="guest-profiles" 
            element={<GuestProfilePage />} 
          />
          <Route
            path="group-bookings" 
            element={<GroupBookingManagementPage />} 
          />
          <Route
            path="rate-plans" 
            element={<RatePlanManagementPage />} 
          />
          <Route
            path="packages" 
            element={<PackageManagementPage />} 
          />
          <Route
            path="security" 
            element={<SecurityManagementPage />} 
          />
          <Route
            path="email-campaigns" 
            element={<EmailCampaignManagementPage />} 
          />
        </Route>

        {}
        <Route 
          path="/staff" 
          element={
            <StaffRoute>
              <StaffLayout />
            </StaffRoute>
          }
        >
          <Route 
            index 
            element={<Navigate to="dashboard" replace />} 
          />
          <Route path="dashboard" element={<StaffDashboardPage />} />
          <Route 
            path="bookings" 
            element={<StaffBookingManagementPage />} 
          />
          <Route 
            path="reception" 
            element={<StaffReceptionDashboardPage />} 
          />
          <Route
            path="payments" 
            element={<StaffPaymentManagementPage />} 
          />
          <Route 
            path="reports" 
            element={<StaffAnalyticsDashboardPage />} 
          />
          <Route 
            path="chats" 
            element={<ChatManagementPage />} 
          />
          <Route
            path="loyalty" 
            element={<StaffLoyaltyManagementPage />} 
          />
          <Route
            path="guest-profiles" 
            element={<StaffGuestProfilePage />} 
          />
          <Route
            path="advanced-rooms" 
            element={<StaffAdvancedRoomManagementPage />} 
          />
        </Route>

        {/* Accountant Routes */}
        <Route 
          path="/accountant" 
          element={
            <AccountantRoute>
              <AccountantLayout />
            </AccountantRoute>
          }
        >
          <Route 
            index 
            element={<Navigate to="dashboard" replace />} 
          />
          <Route path="dashboard" element={<AccountantDashboardPage />} />
          <Route 
            path="payments" 
            element={<AccountantPaymentManagementPage />} 
          />
          <Route 
            path="invoices" 
            element={<AccountantInvoiceManagementPage />} 
          />
          <Route 
            path="reports" 
            element={<AccountantAnalyticsDashboardPage />} 
          />
        </Route>

        {}
        <Route 
          path="*" 
          element={<NotFoundPage />} 
        />
      </Routes>
      
          <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 />
        </Suspense>
        </NavigationLoadingProvider>
      </BrowserRouter>
            </AuthModalProvider>
          </CompanySettingsProvider>
        </CurrencyProvider>
      </CookieConsentProvider>
    </GlobalLoadingProvider>
  );
}

export default App;
