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

import { createInertiaApp } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createRoot } from 'react-dom/client';
import { initializeTheme } from './hooks/use-appearance';
import AppLayout from './layouts/app/AppLayout';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
import { Toaster } from 'react-hot-toast';
import { ConsentProvider } from './contexts/consent';
import CookieBanner from '@/components/consent/CookieBanner';
import React from 'react';

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

createInertiaApp({
    title: (title) => title ? `${title} - ${appName}` : appName,
    resolve: (name) =>
        resolvePageComponent(
            `./pages/${name}.tsx`,
            import.meta.glob('./pages/**/*.tsx')
        ).then((page: any) => {
            if (page?.default) {
                const Component = page.default;
                if (!Component.layout) {
                    Component.layout = (page: React.ReactNode) => <AppLayout>{page}</AppLayout>;
                }
            }

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

        // Sync i18n with initial locale from props
        if (
            props.initialPage &&
            props.initialPage.props &&
            typeof props.initialPage.props.locale === 'string'
        ) {
            i18n.changeLanguage(props.initialPage.props.locale);
        }

        root.render(
            <ConsentProvider>
                <I18nextProvider i18n={i18n}>
                    <App {...props} />
                    <CookieBanner />
                    <Toaster position="top-right" toastOptions={{ duration: 4000 }} />
                </I18nextProvider>
            </ConsentProvider>
        );
    },
    progress: {
        color: '#4B5563',
    },
});

// This will set light / dark mode on load...
initializeTheme();
