import { createInertiaApp, router } from '@inertiajs/react';
import { InertiaNavigationLoader } from '@/components/inertia-navigation-loader';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import { applyJabesWomenTheme } from '@/hooks/use-jabes-women';
import { initializeTheme } from '@/hooks/use-appearance';
import type { User } from '@/types/auth';
import AdminShellLayout from '@/layouts/admin/admin-shell-layout';
import AppLayout from '@/layouts/app-layout';
import AuthLayout from '@/layouts/auth-layout';
import MaintenanceLayout from '@/layouts/maintenance-layout';
import PublicLayout from '@/layouts/public-layout';
import SettingsLayout from '@/layouts/settings/layout';

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

createInertiaApp({
    title: (title) => (title ? `${title} - ${appName}` : appName),
    layout: (name) => {
        switch (true) {
            case name === 'maintenance':
                return MaintenanceLayout;
            case name.startsWith('legal/'):
                return PublicLayout;
            case name.startsWith('confirmations/'):
                return AuthLayout;
            case name.startsWith('auth/'):
                return AuthLayout;
            case name.startsWith('settings/'):
                return [AppLayout, SettingsLayout];
            case name.startsWith('admin/'):
                return [AppLayout, AdminShellLayout];
            default:
                return AppLayout;
        }
    },
    strictMode: true,
    withApp(app) {
        return (
            <TooltipProvider delayDuration={0}>
                {app}
                <InertiaNavigationLoader />
                <Toaster />
            </TooltipProvider>
        );
    },
    progress: false,
});

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

router.on('navigate', (event) => {
    const user = event.detail.page.props.auth?.user as User | undefined;
    applyJabesWomenTheme(user?.jabes_women_enabled === true);
});
