import '../css/app.css';
import { createInertiaApp, router } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createRoot } from 'react-dom/client';
import { initializeTheme } from './hooks/use-appearance';

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

type SharedSettings = {
    favicon?: string | null;
};

const faviconType = (url: string) => {
    const path = url.split('?')[0].toLowerCase();

    if (path.endsWith('.svg')) return 'image/svg+xml';
    if (path.endsWith('.ico')) return 'image/x-icon';
    if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg';

    return 'image/png';
};

const faviconUrl = (favicon?: string | null) => {
    if (!favicon) {
        return '/favicon.ico';
    }

    const normalizedUrl = favicon.startsWith('http') || favicon.startsWith('/') ? favicon : `/${favicon}`;
    const separator = normalizedUrl.includes('?') ? '&' : '?';

    return `${normalizedUrl}${separator}v=${encodeURIComponent(favicon)}`;
};

const setLinkHref = (rel: string, href: string) => {
    let link = document.querySelector<HTMLLinkElement>(`link[rel="${rel}"]`);

    if (!link) {
        link = document.createElement('link');
        link.rel = rel;
        document.head.appendChild(link);
    }

    link.href = href;

    if (rel !== 'apple-touch-icon') {
        link.type = faviconType(href);
    }
};

const updateFavicon = (settings?: SharedSettings | null) => {
    const href = faviconUrl(settings?.favicon);

    setLinkHref('icon', href);
    setLinkHref('shortcut icon', href);
    setLinkHref('apple-touch-icon', href);
};

// Dynamically update favicon from system settings on each navigation.
router.on('navigate', (event) => {
    updateFavicon(event.detail.page.props.settings as SharedSettings | null);
});

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

        updateFavicon(props.initialPage.props.settings as SharedSettings | null);
        root.render(<App {...props} />);
    },
    progress: {
        color: '#4B5563',
    },
});

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