import React from 'react';
import { HashRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from 'sonner';

// Theme
import { ThemeProvider } from './contexts/ThemeContext';
import { BaseLayout } from './layouts/BaseLayout';

// Pages
import Shop from './pages/Shop';
import Product from './pages/Product';
import Cart from './pages/Cart';
import Checkout from './pages/Checkout';
import ThankYou from './pages/ThankYou';
import Account from './pages/Account';
import Wishlist from './pages/Wishlist';
import Login from './pages/Login';

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

// Get theme config from window (injected by PHP)
const getThemeConfig = () => {
  const config = (window as any).woonoowCustomer?.theme;

  // Default config if not provided
  return config || {
    mode: 'full',
    layout: 'modern',
    colors: {
      primary: '#3B82F6',
      secondary: '#8B5CF6',
      accent: '#10B981',
    },
    typography: {
      preset: 'professional',
    },
  };
};

// Get appearance settings from window
const getAppearanceSettings = () => {
  return (window as any).woonoowCustomer?.appearanceSettings || {};
};

// Get initial route from data attribute (set by PHP based on SPA mode)
const getInitialRoute = () => {
  const appEl = document.getElementById('woonoow-customer-app');
  const initialRoute = appEl?.getAttribute('data-initial-route');
  console.log('[WooNooW Customer] Initial route from data attribute:', initialRoute);
  console.log('[WooNooW Customer] App element:', appEl);
  console.log('[WooNooW Customer] All data attributes:', appEl?.dataset);
  return initialRoute || '/shop'; // Default to shop if not specified
};

// Router wrapper component that uses hooks requiring Router context
function AppRoutes() {
  const initialRoute = getInitialRoute();
  console.log('[WooNooW Customer] Using initial route:', initialRoute);

  return (
    <BaseLayout>
      <Routes>
        {/* Root route redirects to initial route based on SPA mode */}
        <Route path="/" element={<Navigate to={initialRoute} replace />} />

        {/* Shop Routes */}
        <Route path="/shop" element={<Shop />} />
        <Route path="/product/:slug" element={<Product />} />

        {/* Cart & Checkout */}
        <Route path="/cart" element={<Cart />} />
        <Route path="/checkout" element={<Checkout />} />
        <Route path="/order-received/:orderId" element={<ThankYou />} />

        {/* Wishlist - Public route accessible to guests */}
        <Route path="/wishlist" element={<Wishlist />} />

        {/* Login */}
        <Route path="/login" element={<Login />} />

        {/* My Account */}
        <Route path="/my-account/*" element={<Account />} />

        {/* Fallback to initial route */}
        <Route path="*" element={<Navigate to={initialRoute} replace />} />
      </Routes>
    </BaseLayout>
  );
}

function App() {
  const themeConfig = getThemeConfig();
  const appearanceSettings = getAppearanceSettings();
  const toastPosition = (appearanceSettings?.general?.toast_position || 'top-right') as any;

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider config={themeConfig}>
        <HashRouter>
          <AppRoutes />
        </HashRouter>

        {/* Toast notifications - position from settings */}
        <Toaster position={toastPosition} richColors />
      </ThemeProvider>
    </QueryClientProvider>
  );
}

export default App;
