document.addEventListener('DOMContentLoaded', function () {
    // Sidebar toggle (mobile)
    var sidebarToggle = document.getElementById('sidebarToggle');
    var sidebarOverlay = document.getElementById('sidebarOverlay');

    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function () {
            document.body.classList.toggle('sidebar-open');
        });
    }

    if (sidebarOverlay) {
        sidebarOverlay.addEventListener('click', function () {
            document.body.classList.remove('sidebar-open');
        });
    }

    // Active nav highlighting
    var currentPath = window.location.pathname.toLowerCase().replace(/\/$/, '');
    var sidebarLinks = document.querySelectorAll('.sidebar-nav a');

    sidebarLinks.forEach(function (link) {
        var href = link.getAttribute('href');
        if (!href) return;

        var linkPath = href.toLowerCase().replace(/\/$/, '');

        // Exact match or starts-with match (for sub-pages)
        if (currentPath === linkPath || (linkPath !== '' && currentPath.startsWith(linkPath + '/'))) {
            link.classList.add('active');
        }
    });

    // Special case: root path goes to Dashboard
    if (currentPath === '' || currentPath === '/') {
        var dashboardLink = document.querySelector('.sidebar-nav a[href*="Dashboard"]');
        if (dashboardLink) {
            dashboardLink.classList.add('active');
        }
    }

    // Auto-dismiss alerts after 5 seconds
    setTimeout(function () {
        var alerts = document.querySelectorAll('.alert');
        alerts.forEach(function (alert) {
            var bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
            if (bsAlert) {
                bsAlert.close();
            }
        });
    }, 5000);
});
