/**
 * soft-nav.js
 * Intercepts internal navigation clicks and swaps #page-content via fetch,
 * keeping the Three.js black hole canvas alive permanently.
 */
(function () {
    'use strict';

    // Pages to skip soft-nav for (will do a normal full reload).
    const EXCLUDED_PATHS = [
        '/admin',
        '/organizer',
        '/finance',
        '/debug.php',
        '/test',
    ];

    // Track loaded script URLs so we don't double-load global scripts
    const loadedScripts = new Set();
    // Pre-seed with already-loaded scripts on first page load
    document.querySelectorAll('script[src]').forEach(s => loadedScripts.add(s.src));

    const overlay = document.getElementById('page-transition-overlay');
    const TRANSITION_MS = 220;

    function withTransition(callback) {
        const content = document.getElementById('page-content');
        if (content) content.classList.add('fading');
        if (overlay) overlay.classList.add('visible');
        setTimeout(callback, TRANSITION_MS);
    }

    function finishTransition() {
        const content = document.getElementById('page-content');
        if (content) {
            content.offsetHeight;
            content.classList.remove('fading');
        }
        if (overlay) overlay.classList.remove('visible');
    }

    /**
     * Re-execute <script> tags found inside the newly swapped content.
     * innerHTML injection does NOT execute scripts — we must clone them.
     */
    function reExecuteScripts(containerEl) {
        const scripts = containerEl.querySelectorAll('script');
        const promises = [];

        scripts.forEach(oldScript => {
            const newScript = document.createElement('script');

            // Copy all attributes
            Array.from(oldScript.attributes).forEach(attr => {
                newScript.setAttribute(attr.name, attr.value);
            });

            if (oldScript.src) {
                // External script — only load once per session to avoid re-registering event listeners
                if (loadedScripts.has(newScript.src)) {
                    return;
                }
                loadedScripts.add(newScript.src);
                promises.push(new Promise(resolve => {
                    newScript.onload = resolve;
                    newScript.onerror = resolve;
                    document.body.appendChild(newScript);
                }));
            } else {
                // Inline script — execute it
                newScript.textContent = oldScript.textContent;
                document.body.appendChild(newScript);
            }

            // Remove the old dead script tag from the content area to keep DOM clean
            oldScript.remove();
        });

        return Promise.all(promises);
    }

    // ── Slug → blackhole theme mapping ───────────────────────────────────────
    const SLUG_THEMES = {
        'sparkx-startup-pitching':             'green',
        'stellar-hackthon':                    'purple',
        'battleclipse-esports':                'purple',
        'protonova-project-competition':       'orange',
        'ninja-coders-take-the-ninja-road':    'red',
        'codeburst-competative-programming':   'golden',
        'junior-shark-pitch-beyond-the-stars': 'pink',
        'infinity-lab-technical-workshop':     'teal',
    };

    /**
     * Read the current URL and apply the matching blackhole theme.
     * Falls back to 'default' for any unrecognised page.
     */
    function applyPageTheme() {
        if (typeof window.blackholeSetTheme !== 'function') return;

        const params = new URLSearchParams(window.location.search);
        const slug   = params.get('slug') || '';
        const theme  = SLUG_THEMES[slug] || 'default';
        window.blackholeSetTheme(theme, 1500);
    }

    function normalizePath(pathname) {
        let p = (pathname || '/').replace(/\/index\.php$/i, '/');
        if (!p.endsWith('/')) p += '/';
        return p;
    }

    function scrollToHashOrTop(targetUrl) {
        let hash = '';
        try {
            const parsed = new URL(targetUrl || window.location.href, window.location.origin);
            hash = parsed.hash ? parsed.hash.substring(1) : '';
        } catch (e) {
            hash = window.location.hash ? window.location.hash.substring(1) : '';
        }

        if (hash) {
            const targetEl = document.getElementById(hash);
            if (targetEl) {
                setTimeout(() => {
                    targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }, 120);
                return;
            }
        }

        window.scrollTo({ top: 0, behavior: 'instant' });
    }

    function reinitPage(targetUrl) {
        // Re-run Lucide icon rendering on new content
        if (window.lucide) {
            try { window.lucide.createIcons(); } catch (e) {}
        }

        // Call home page init if the function exists in scope (home.js was already loaded)
        if (typeof window.supernovaHomeInit === 'function') {
            // Only run it if the countdown element exists (i.e., we are on the home page)
            if (document.getElementById('sn-countdown')) {
                window.supernovaHomeInit();
            }
        }

        // Apply blackhole color theme for this page
        applyPageTheme();

        // Dispatch a custom event that other scripts can listen to
        document.dispatchEvent(new CustomEvent('soft-nav:content-loaded'));

        // Scroll to hash section or top of page
        scrollToHashOrTop(targetUrl);
    }

    function isSoftNavTarget(url) {
        try {
            const parsed = new URL(url, window.location.href);
            if (parsed.origin !== window.location.origin) return false;
            const ext = parsed.pathname.split('.').pop().toLowerCase();
            if (['pdf','zip','png','jpg','jpeg','gif','svg','webp','mp4','mov'].includes(ext)) return false;
            for (const ex of EXCLUDED_PATHS) {
                if (parsed.pathname.startsWith(ex)) return false;
            }
            return true;
        } catch (e) {
            return false;
        }
    }

    async function fetchPageContent(url) {
        const response = await fetch(url, {
            headers: { 'X-Soft-Nav': '1' },
            credentials: 'same-origin',
        });
        if (!response.ok) throw new Error('HTTP ' + response.status);
        const html = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        return { newContent: doc.getElementById('page-content'), newTitle: doc.title };
    }

    async function navigate(url, pushState) {
        try {
            withTransition(async function () {
                try {
                    const { newContent, newTitle } = await fetchPageContent(url);
                    if (!newContent) { window.location.href = url; return; }

                    const currentContent = document.getElementById('page-content');
                    if (currentContent) {
                        currentContent.innerHTML = newContent.innerHTML;
                        // Re-execute any <script> tags that were inside the new page content
                        await reExecuteScripts(currentContent);
                    }

                    if (newTitle) document.title = newTitle;
                    if (pushState) history.pushState({ softNav: true, url: url }, newTitle, url);

                    finishTransition();
                    reinitPage(url);
                } catch (err) {
                    console.warn('[soft-nav] fetch failed, hard reload:', err);
                    window.location.href = url;
                }
            });
        } catch (err) {
            window.location.href = url;
        }
    }

    document.addEventListener('click', function (e) {
        let anchor = e.target;
        while (anchor && anchor.tagName !== 'A') anchor = anchor.parentElement;
        if (!anchor) return;
        const href = anchor.getAttribute('href');
        if (!href) return;
        if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
        if (anchor.target === '_blank') return;

        // Pure local hash link (e.g. href="#schedule")
        if (href.startsWith('#')) {
            const hashId = href.substring(1);
            const targetEl = document.getElementById(hashId);
            if (targetEl) {
                e.preventDefault();
                targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
                history.pushState(null, '', href);
            }
            return;
        }

        const fullUrl = new URL(href, window.location.href).href;
        const parsedTarget = new URL(fullUrl);

        const currentPathNorm = normalizePath(window.location.pathname);
        const targetPathNorm  = normalizePath(parsedTarget.pathname);

        // Same page with a hash target (e.g. on home page clicking /#schedule or /index.php#committee)
        if (window.location.origin === parsedTarget.origin && currentPathNorm === targetPathNorm && parsedTarget.hash) {
            const hashId = parsedTarget.hash.substring(1);
            const targetEl = document.getElementById(hashId);
            if (targetEl) {
                e.preventDefault();
                targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
                history.pushState(null, '', fullUrl);
                return;
            }
        }

        if (!isSoftNavTarget(fullUrl)) return;
        e.preventDefault();
        navigate(fullUrl, true);
    });

    window.addEventListener('popstate', function () {
        navigate(window.location.href, false);
    });

    history.replaceState({ softNav: true, url: window.location.href }, document.title, window.location.href);
})();
