import './bootstrap';
import '../css/app.css';
import { createRoot } from 'react-dom/client';
import { createInertiaApp } from '@inertiajs/react';
import { router } from '@inertiajs/react';
import React, { useState, useEffect } from 'react';

const pages = import.meta.glob('./Pages/**/*.jsx');

// Simple Navigation Preloader Component
function NavigationPreloader({ show, primaryColor = '#667eea', secondaryColor = '#764ba2' }) {
  if (!show) return null;

  return (
    <div className="fixed inset-0 z-[9999] bg-white/80 dark:bg-zinc-900/80 backdrop-blur-sm flex items-center justify-center">
      <div className="flex flex-col items-center space-y-4">
        <div
          className="w-8 h-8 border-2 border-gray-200 dark:border-zinc-700 rounded-full animate-spin"
          style={{ borderTopColor: primaryColor }}
        />
        <p className="text-sm text-gray-600 dark:text-gray-400">Loading...</p>
      </div>
    </div>
  );
}

createInertiaApp({
    resolve: async (name) => {
        const pagePath = `./Pages/${name}.jsx`;
        const pageLoader = pages[pagePath];

        if (!pageLoader) {
            console.error(`Page not found: ${pagePath}`);
            console.error('Available pages:', Object.keys(pages));
            throw new Error(`Page not found: ${name}`);
        }

        const page = await pageLoader();
        return page.default;
    },
    setup({ el, App, props }) {
        const root = createRoot(el);

        // Navigation Preloader State
        let showNavPreloader = false;

        // Create App with Navigation Preloader
        function AppWithPreloader(appProps) {
          const [navLoading, setNavLoading] = useState(false);

          useEffect(() => {
            // Check if preloader is enabled before showing navigation loader
            const preloaderEnabled = appProps.initialPage?.props?.site_settings?.preloader_enabled === "1";

            if (!preloaderEnabled) return;

            const startHandler = () => setNavLoading(true);
            const finishHandler = () => setNavLoading(false);

            router.on('start', startHandler);
            router.on('finish', finishHandler);
            router.on('error', finishHandler);

            return () => {
              router.off('start', startHandler);
              router.off('finish', finishHandler);
              router.off('error', finishHandler);
            };
          }, [appProps.initialPage?.props?.site_settings?.preloader_enabled]);

          const primaryColor = appProps.initialPage?.props?.site_settings?.primary_color ?? '#667eea';
          const preloaderEnabled = appProps.initialPage?.props?.site_settings?.preloader_enabled === "1";

          return (
            <>
              {preloaderEnabled && (
                <NavigationPreloader show={navLoading} primaryColor={primaryColor} />
              )}
              <App {...appProps} />
            </>
          );
        }

        root.render(<AppWithPreloader {...props} />);
    },
});

