import '../css/app.css';
import '../assets/scss/style.scss';
import '../assets/css/style.css';
import {createInertiaApp} from '@inertiajs/react';
import {createRoot} from 'react-dom/client';
import {resolvePageComponent} from 'laravel-vite-plugin/inertia-helpers';
import {Toaster} from 'react-hot-toast';
import { router } from '@inertiajs/react';

import '../assets/libs/simplebar/simplebar.min.css';
import '../assets/libs/@simonwep/pickr/themes/nano.min.css';
import '../assets/libs/jsvectormap/jsvectormap.min.css';

const appName = import.meta.env.VITE_APP_NAME || "UFANIS LAW FIRM";

function initLegacyScripts() {
    // Scripts with optional `waitFor` selectors: only load the script if any of the selectors exist on the page.
    // If `waitFor` is omitted, the script will always be loaded.
    const scripts: { path: string; waitFor?: string[] }[] = [
        { path: '../assets/js/main.js' },
        { path: '../assets/libs/@popperjs/core/umd/popper.min.js' },
        { path: '../assets/libs/@simonwep/pickr/pickr.es5.min.js' },
        { path: '../assets/js/defaultmenu.js', waitFor: ['.main-menu'] },
        { path: '../assets/js/sticky.js', waitFor: ['.header', '.app-sidebar'] },
        { path: '../assets/js/switch.js' },
        { path: '../assets/libs/preline/preline.js' },
        { path: '../assets/libs/simplebar/simplebar.min.js' },
        { path: '../assets/js/custom.js', waitFor: ['#loader', '#year', '.main-menu', '#sidebar-scroll'] },
        { path: '../assets/js/custom-switcher.js', waitFor: ['#hs-overlay-switcher'] },
    ];

    const loadScriptOnce = (href: string) =>
        new Promise<void>((resolve, reject) => {
            try {
                const selector = `script[data-legacy-src="${href}"]`;
                if (document.querySelector(selector)) return resolve();
                const s = document.createElement('script');
                s.src = href;
                s.async = false;
                s.setAttribute('data-legacy-src', href);
                s.onload = () => resolve();
                s.onerror = (err) => {
                    // Provide extra diagnostics for server errors (helps debug 500 responses from Vite)
                    try {
                        // eslint-disable-next-line no-console
                        console.warn('legacy script onerror', href, err);
                        // Try to fetch the resource to log status and response body (if any)
                        fetch(href, { cache: 'no-store' })
                            .then(async (res) => {
                                if (!res.ok) {
                                    const text = await res.text().catch(() => '<no body>');
                                    // eslint-disable-next-line no-console
                                    console.warn('legacy script fetch diagnostics', href, res.status, text);
                                }
                            })
                            .catch(() => {
                                // ignore fetch diagnostics failure
                            });
                    } catch (e) {
                        // ignore
                    }
                    reject(err);
                };
                document.head.appendChild(s);
            } catch (err) {
                reject(err as any);
            }
        });

    // Wait for some known DOM elements that legacy scripts expect before loading.
    // If they don't appear within timeoutMs, proceed anyway (fallback).
    const waitForSelectors = (selectors: string[], timeoutMs = 3000) =>
        new Promise<void>((resolve) => {
            try {
                const start = Date.now();
                const check = () => {
                    for (const s of selectors) {
                        if (document.querySelector(s)) {
                            return resolve();
                        }
                    }
                    if (Date.now() - start >= timeoutMs) return resolve();
                    requestAnimationFrame(check);
                };
                check();
            } catch (e) {
                resolve();
            }
        });

    (async () => {
        // selectors commonly used by legacy scripts; wait for any to exist
        await waitForSelectors([".main-menu", "#hs-overlay-switcher", ".header", "#loader"], 3000);
        for (const p of scripts) {
            // If the script is page-specific and none of its selectors exist, skip loading it.
            if (p.waitFor && p.waitFor.length > 0) {
                let found = false;
                for (const sel of p.waitFor) {
                    if (document.querySelector(sel)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    // Skip this script for the current page
                    // eslint-disable-next-line no-console
                    console.debug('Skipping legacy script (no selectors matched):', p.path);
                    continue;
                }
            }
            const href = new URL(p.path, import.meta.url).href;
            try {
                // sequential load to preserve execution order
                // eslint-disable-next-line no-await-in-loop
                await loadScriptOnce(href);

                // If we just loaded Preline after the page load, its auto-init (which
                // runs on window.load) won't have executed. Call its static init helper
                // so components like dropdowns are initialized.
                try {
                    if (href.includes('preline')) {
                        // Preline exposes HSStaticMethods.autoInit on the window
                        // Use a safe any cast because TS doesn't know about it here
                        (window as any).HSStaticMethods?.autoInit?.();
                    }
                } catch (e) {
                    // ignore initialization errors, but keep other scripts loading
                    // eslint-disable-next-line no-console
                    console.warn('preline autoInit failed', href, e);
                }
            } catch (err) {
                // Log but don't throw — legacy scripts are optional
                // eslint-disable-next-line no-console
                console.warn('legacy script failed to load', href, err);
            }
        }
    })();
}

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) =>
        resolvePageComponent(
            `./Pages/${name}.tsx`,
            import.meta.glob('./Pages/**/*.tsx')
        ),
    setup({ el, App, props }) {
        const root = createRoot(el);
        root.render(
            <>
                <App {...props} />
                <Toaster
                    position="top-right"
                    toastOptions={{
                        duration: 4000,
                        style: { fontSize: '0.875rem' },
                    }}
                />
            </>
        );

        // Run legacy scripts after initial render
        initLegacyScripts();

        // Re-run legacy scripts on every Inertia navigation
        router.on('finish', () => {
            // Prevent duplicates if needed
            setTimeout(initLegacyScripts, 50);
        });
    },
    progress: {
        color: '#6bbaff',
    },
});

