import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap';
import '../css/app.css';

import { createInertiaApp, router } from '@inertiajs/react';
import type { ComponentType } from 'react';
import { createRoot } from 'react-dom/client';

const pages = import.meta.glob<{ default: ComponentType }>('./Pages/**/*.tsx');

type SharedTheme = {
    primaryColor: string;
    accentColor: string;
    backgroundColor: string;
    surfaceColor: string;
    textColor: string;
    headingFontFamily: string;
    bodyFontFamily: string;
    borderRadius: number;
};

const applyTheme = (theme?: SharedTheme | null) => {
    if (!theme) return;

    const root = document.documentElement;
    const values: Record<string, string> = {
        '--theme-primary': theme.primaryColor,
        '--theme-accent': theme.accentColor,
        '--theme-background': theme.backgroundColor,
        '--theme-surface': theme.surfaceColor,
        '--theme-text': theme.textColor,
        '--theme-heading-font': theme.headingFontFamily,
        '--theme-body-font': theme.bodyFontFamily,
        '--theme-radius': `${theme.borderRadius}px`,
        '--sage': theme.primaryColor,
        '--sage-deep': theme.primaryColor,
        '--ice-blue': theme.accentColor,
        '--ice-blue-deep': theme.accentColor,
        '--cream': theme.backgroundColor,
        '--warm-white': theme.surfaceColor,
        '--ink': theme.textColor,
    };

    Object.entries(values).forEach(([property, value]) => root.style.setProperty(property, value));
    root.dataset.wedsterTheme = 'active';
    document.querySelector('meta[name="theme-color"]')?.setAttribute('content', theme.primaryColor);
};

createInertiaApp({
    title: (title) => (title ? `${title} · Wedster` : 'Wedster'),
    resolve: async (name) => {
        const loadPage = pages[`./Pages/${name}.tsx`];

        if (!loadPage) {
            throw new Error(`Unknown Inertia page: ${name}`);
        }

        return (await loadPage()).default;
    },
    setup({ el, App, props }) {
        applyTheme((props.initialPage.props as { theme?: SharedTheme | null }).theme);
        router.on('navigate', (event) => {
            applyTheme((event.detail.page.props as { theme?: SharedTheme | null }).theme);
        });
        createRoot(el).render(<App {...props} />);
    },
});

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        void navigator.serviceWorker.register('/sw.js').catch(() => undefined);
    });
}
