
if (!window.__SPA_ENGINE__) {
    window.__SPA_ENGINE__ = true;

    (() => {
        window.__injectedScripts__ = [];
        document.addEventListener("click", function (e) {
            const link = e.target.closest("a[data-nav]");
            if (!link) return;

            e.preventDefault();

            const url = link.getAttribute("href");
            const current = location.pathname + location.search;
            const target = new URL(url, location.origin).pathname + new URL(url, location.origin).search;
            if (current === target) return;

            const container = document.getElementById("app-content");
            if (!container) return;

            container.classList.add("fade-out");

            fetch(url, { headers: { "X-Requested-With": "XMLHttpRequest" } })
                .then(r => r.text())
                .then(html => {
                    const temp = document.createElement("div");
                    temp.innerHTML = html;

                    const content = temp.querySelector("#app-content");
                    if (!content) return;

                    cleanupScripts();
                    container.innerHTML = content.innerHTML;

                    runScripts(temp);
                    setTimeout(() => {
                        initBootstrapUI(document);
                    }, 50);

                    rebindGlobalEvents();
                    initBootstrapUI(document);

                    history.pushState({}, "", url);
                    updateActiveTab(url);

                    document.getElementById('sidebar')?.classList.remove('active');
                    container.classList.remove("fade-out");

                    syncIndicatorWithUrl?.();
                    initBootstrapUI(document);

                    requestAnimationFrame(() => {
                        initBootstrapUI(document);
                        rebindGlobalEvents();
                    });

                });
        });

        function cleanupScripts() {
            window.__injectedScripts__.forEach(s => s.remove());
            window.__injectedScripts__ = [];
        }

        function runScripts(wrapper) {
            wrapper.querySelectorAll("script").forEach(oldScript => {
                const script = document.createElement("script");

                if (oldScript.src && oldScript.src.includes('bs.js')) {
                    return;
                }

                if (oldScript.src) {
                    const exists = document.querySelector(`script[src="${oldScript.src}"]`);
                    if (exists) return;
                }

                [...oldScript.attributes].forEach(attr => {
                    script.setAttribute(attr.name, attr.value);
                });

                if (!oldScript.src) {
                    script.textContent = `(function(){ ${oldScript.textContent} })();`;
                }

                document.body.appendChild(script);
                window.__injectedScripts__.push(script);
            });
        }

        function rebindGlobalEvents() {
            const drawer = document.getElementById('drawerTrigger');
            if (drawer) {
                const clone = drawer.cloneNode(true);
                drawer.replaceWith(clone);
                clone.addEventListener('click', () => toggleDrawer?.());
            }
            const loginBtn = document.getElementById('loginBtn');
            if (loginBtn) {
                const clone = loginBtn.cloneNode(true);
                loginBtn.replaceWith(clone);
            }
        }

        function initBootstrapUI(scope = document) {
            if (!window.bootstrap) return;

            scope.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(el => {
                const old = bootstrap.Dropdown.getInstance(el);
                if (old) old.dispose();
                new bootstrap.Dropdown(el);
            });

            scope.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
                const old = bootstrap.Tooltip.getInstance(el);
                if (old) old.dispose();
                new bootstrap.Tooltip(el);
            });

            scope.querySelectorAll('[data-bs-toggle="popover"]').forEach(el => {
                const old = bootstrap.Popover.getInstance(el);
                if (old) old.dispose();
                new bootstrap.Popover(el);
            });
        }

        window.addEventListener("popstate", () => {
            fetch(location.href, { headers: { "X-Requested-With": "XMLHttpRequest" } })
                .then(r => r.text())
                .then(html => {
                    const temp = document.createElement("div");
                    temp.innerHTML = html;

                    const content = temp.querySelector("#app-content");
                    if (!content) return;

                    cleanupScripts();
                    document.getElementById("app-content").innerHTML = content.innerHTML;
                    runScripts(temp);
                    initBootstrapUI(document);
                    rebindGlobalEvents();
                });
        });

        window.updateActiveTab = function (url) {
            document.querySelectorAll(".bottombar a").forEach(a => {
                a.classList.toggle("active", url === a.getAttribute("href"));
            });
        };
    })();
}