import { createInertiaApp } from '@inertiajs/react';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import { initializeTheme } from '@/hooks/use-appearance';
import AppLayout from '@/layouts/app-layout';
import AuthLayout from '@/layouts/auth-layout';
import InspectionLayout from '@/layouts/inspection-layout';
import LaunchLayout from '@/layouts/launch-layout';
import StatusLayout from '@/layouts/status-layout';
import TicketLayout from '@/layouts/ticket-layout';
import SettingsLayout from '@/layouts/settings/layout';

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

/**
 * The name this installation runs under. A client changes it in
 * Settings -> Branding, so it is read from the root element rather than baked
 * in at build time; the shared Inertia props are not available to the title
 * callback.
 */
const brandName = () =>
    (typeof document === 'undefined'
        ? undefined
        : document.documentElement.dataset.brandName?.trim()) || appName;

void createInertiaApp({
    title: (title) => (title ? `${title} - ${brandName()}` : brandName()),
    layout: (name) => {
        switch (true) {
            case name.startsWith('auth/'):
                return AuthLayout;
            case name.startsWith('settings/'):
                return [AppLayout, SettingsLayout];
            case name.startsWith('ticket/'):
                return TicketLayout;
            // The crew's field report is public and has no CRM around it.
            case name.startsWith('inspections/public/'):
                return InspectionLayout;
            // The shared ticket status board: a username and password rather
            // than an account, so it carries the brand and nothing else.
            case name.startsWith('ticket-status/'):
                return StatusLayout;
            // The holding page a site wears before it is public. Nobody reading
            // it has an account, so it gets the brand and no chrome at all.
            case name === 'coming-soon':
                return LaunchLayout;
            default:
                return AppLayout;
        }
    },
    strictMode: true,
    withApp(app) {
        return (
            <TooltipProvider delayDuration={0}>
                {app}
                <Toaster />
            </TooltipProvider>
        );
    },
    progress: {
        color: '#4B5563',
    },
});

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