import '../css/app.css';

import { createInertiaApp } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createRoot } from 'react-dom/client';
import { ErrorBoundary } from 'react-error-boundary';
import { GA4Provider } from './Plugins/GA4Context.jsx'; // Updated import

import DetailedErrorFallback from './components/custom/detailed-error-fallback'; // Import your component
import { Toaster } from './components/ui/sonner';
import { initializeTheme } from './hooks/use-appearance';
import AuthDialog from './modules/auth/AuthDialog';
import { AxiosProvider } from './plugins/AxiosContext';
import { MittProvider } from './plugins/MittContext';

const appName = import.meta.env.VITE_APP_NAME || 'Laravel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./pages/${name}.tsx`, import.meta.glob('./pages/**/*.tsx')),
    setup({ el, App, props }) {
        const root = createRoot(el);

        const app = (
            <ErrorBoundary
                FallbackComponent={DetailedErrorFallback}
                onError={(error, errorInfo) => {
                    // Log to console for debugging
                    console.error('Error caught by boundary:', error, errorInfo);

                    // You could also send to an error reporting service here
                    // e.g., Sentry, LogRocket, etc.
                }}
                onReset={() => {
                    // Optional: Clear any error state in your app
                    console.log('Error boundary reset');
                }}
            >
                <GA4Provider>
                    <MittProvider>
                        <AxiosProvider>
                            <Toaster position="top-right" />
                            <AuthDialog />

                            <App {...props} />
                        </AxiosProvider>
                    </MittProvider>
                </GA4Provider>
            </ErrorBoundary>
        );

        root.render(app);
    },
    progress: {
        color: '#4B5563',
    },
});

initializeTheme();
