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

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy';

const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
const loaderId = 'global-page-loader';
const loaderDelayMs = 200;
let loaderShowTimer = null;
let loaderPending = false;

const ensureGlobalLoader = () => {
    let loader = document.getElementById(loaderId);
    if (loader) return loader;

    loader = document.createElement('div');
    loader.id = loaderId;
    loader.className = 'global-page-loader';
    loader.setAttribute('aria-live', 'polite');
    loader.setAttribute('aria-busy', 'true');
    loader.innerHTML = `
        <div class="global-page-loader__box">
            <span class="global-page-loader__spinner" aria-hidden="true"></span>
            <span class="global-page-loader__text">Loading...</span>
        </div>
    `;
    document.body.appendChild(loader);

    return loader;
};

const setGlobalLoaderVisible = (visible) => {
    const loader = ensureGlobalLoader();
    loader.classList.toggle('is-visible', !!visible);
};

const scheduleGlobalLoader = () => {
    loaderPending = true;
    if (loaderShowTimer) {
        clearTimeout(loaderShowTimer);
    }

    loaderShowTimer = setTimeout(() => {
        if (loaderPending) {
            setGlobalLoaderVisible(true);
        }
    }, loaderDelayMs);
};

const clearGlobalLoader = () => {
    loaderPending = false;
    if (loaderShowTimer) {
        clearTimeout(loaderShowTimer);
        loaderShowTimer = null;
    }
    setGlobalLoaderVisible(false);
};

const applyBranding = (pageProps = {}) => {
    const branding = pageProps?.branding || {};
    const root = document.documentElement;
    const hexToRgb = (hex, fallback) => {
        const source = typeof hex === 'string' ? hex.trim() : '';
        const normalized = /^#[0-9a-fA-F]{6}$/.test(source) ? source : fallback;
        const raw = normalized.replace('#', '');
        const r = Number.parseInt(raw.slice(0, 2), 16);
        const g = Number.parseInt(raw.slice(2, 4), 16);
        const b = Number.parseInt(raw.slice(4, 6), 16);

        return `${r} ${g} ${b}`;
    };

    root.style.setProperty('--brand-primary', branding.primary_color || '#0f172a');
    root.style.setProperty('--brand-secondary', branding.secondary_color || '#1e293b');
    root.style.setProperty('--brand-accent', branding.accent_color || '#0ea5e9');
    root.style.setProperty('--brand-surface', branding.surface_color || '#f8fafc');
    root.style.setProperty('--brand-text', branding.text_color || '#0f172a');
    root.style.setProperty('--brand-primary-rgb', hexToRgb(branding.primary_color, '#0f172a'));
    root.style.setProperty('--brand-secondary-rgb', hexToRgb(branding.secondary_color, '#1e293b'));
    root.style.setProperty('--brand-accent-rgb', hexToRgb(branding.accent_color, '#0ea5e9'));
    root.style.setProperty('--brand-surface-rgb', hexToRgb(branding.surface_color, '#f8fafc'));
    root.style.setProperty('--brand-text-rgb', hexToRgb(branding.text_color, '#0f172a'));

    const faviconUrl = branding.favicon_url;
    if (faviconUrl) {
        let favicon = document.querySelector('link[rel=\"icon\"]');
        if (!favicon) {
            favicon = document.createElement('link');
            favicon.setAttribute('rel', 'icon');
            document.head.appendChild(favicon);
        }
        favicon.setAttribute('href', faviconUrl);
    }
};

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
    setup({ el, App, props, plugin }) {
        ensureGlobalLoader();
        applyBranding(props?.initialPage?.props || {});

        document.addEventListener('inertia:navigate', (event) => {
            applyBranding(event?.detail?.page?.props || {});
        });

        document.addEventListener('inertia:start', () => {
            scheduleGlobalLoader();
        });

        document.addEventListener('inertia:finish', () => {
            clearGlobalLoader();
        });

        window.addEventListener('beforeunload', () => {
            setGlobalLoaderVisible(true);
        });

        // Avoid raw Inertia error modal for expired CSRF/session (419).
        document.addEventListener('inertia:invalid', (event) => {
            const status = event?.detail?.response?.status;
            if (status !== 419) return;
            event.preventDefault();
            window.location.reload();
        });

        const app = createApp({ render: () => h(App, props) })
            .use(plugin)
            .use(ZiggyVue)
            .mount(el);

        requestAnimationFrame(() => clearGlobalLoader());

        return app;
    },
    progress: {
        color: '#4B5563',
    },
});
