var Router = (function() {
    'use strict';

    var contentEl = null;
    var currentPage = '';
    var isLoading = false;

    function init() {
        contentEl = document.getElementById('content');
        if (!contentEl) return;

        document.addEventListener('click', function(e) {
            var target = e.target.closest('[data-route]');
            if (!target) return;
            e.preventDefault();
            var page = target.getAttribute('data-route');
            if (page) navigate(page);
        });

        var initial = 'home';
        if (contentEl.innerHTML.trim() === '') {
            loadPage(initial, false);
        } else {
            currentPage = initial;
            updateActiveNav(initial);
        }
        if (window.location.hash) {
            history.replaceState(null, '', window.location.pathname);
        }
    }

    function getPageFromHash() {
        var hash = window.location.hash.replace('#', '').replace('/', '');
        if (!hash || !isValidPage(hash)) return null;
        return hash;
    }

    function isValidPage(name) {
        return typeof name === 'string' && /^[a-z0-9-]+$/.test(name) && name.length < 40;
    }

    var getCsrf = Bridge.getCsrf;

    function setCsrf(token) {
        var meta = document.querySelector('meta[name="csrf-token"]');
        if (meta && token) meta.setAttribute('content', token);
    }

    function navigate(page, data) {
        if (isLoading || !isValidPage(page)) return;
        loadPage(page, true, data);
    }

    function loadPage(page, pushHash, data) {
        if (isLoading) return;
        isLoading = true;

        contentEl.classList.add('loading');

        var body = {
            page: page,
            csrf: getCsrf()
        };

        if (data && typeof data === 'object') {
            for (var key in data) {
                if (data.hasOwnProperty(key)) {
                    body[key] = data[key];
                }
            }
        }

        fetch('/api/router.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(result) {
            if (result.html) {
                contentEl.innerHTML = result.html;
                executeScripts(contentEl);
                currentPage = result.page || page;

                if (result.csrf) setCsrf(result.csrf);

                updateActiveNav(currentPage);
                window.scrollTo(0, 0);

                if (typeof Telemetry !== 'undefined' && Telemetry.trackPage) {
                    Telemetry.trackPage(currentPage);
                }
            } else if (result.error) {
                contentEl.innerHTML = '<div class="error-message">' + escapeHtml(result.error) + '</div>';
            }
        })
        .catch(function(err) {
            contentEl.innerHTML = '<div class="error-message">Failed to load page. Please try again.</div>';
        })
        .finally(function() {
            isLoading = false;
            contentEl.classList.remove('loading');
        });
    }

    function executeScripts(container) {
        var scripts = container.querySelectorAll('script');
        for (var i = 0; i < scripts.length; i++) {
            var oldScript = scripts[i];
            var newScript = document.createElement('script');
            if (oldScript.src) {
                newScript.src = oldScript.src;
            } else {
                newScript.textContent = oldScript.textContent;
            }
            oldScript.parentNode.replaceChild(newScript, oldScript);
        }
    }

    function updateActiveNav(page) {
        var navLinks = document.querySelectorAll('[data-route]');
        for (var i = 0; i < navLinks.length; i++) {
            var link = navLinks[i];
            if (link.getAttribute('data-route') === page) {
                link.classList.add('active');
            } else {
                link.classList.remove('active');
            }
        }
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    }

    return {
        init: init,
        navigate: navigate,
        currentPage: function() { return currentPage; },
        getCsrf: getCsrf,
        setCsrf: setCsrf
    };
})();

document.addEventListener('DOMContentLoaded', Router.init);
