// StudyTrack - Main JavaScript

// ===== SIDEBAR TOGGLE =====
// Runs after DOM is ready (script loaded at bottom of body)
(function() {
    function initSidebar() {
        var sidebar        = document.getElementById('sidebar');
        var sidebarOverlay = document.getElementById('sidebarOverlay');
        var sidebarClose   = document.getElementById('sidebarClose');

        // Support both button IDs used across pages
        var toggleBtn = document.getElementById('sidebarToggle');

        if (!sidebar) return; // no sidebar on this page

        function openSidebar() {
            sidebar.classList.add('open');
            if (sidebarOverlay) {
                sidebarOverlay.classList.add('active');
                sidebarOverlay.style.display = 'block';
            }
            document.body.style.overflow = 'hidden';
        }

        function closeSidebar() {
            sidebar.classList.remove('open');
            if (sidebarOverlay) {
                sidebarOverlay.classList.remove('active');
                sidebarOverlay.style.display = 'none';
            }
            document.body.style.overflow = '';
        }

        if (toggleBtn)      toggleBtn.addEventListener('click', openSidebar);
        if (sidebarClose)   sidebarClose.addEventListener('click', closeSidebar);
        if (sidebarOverlay) sidebarOverlay.addEventListener('click', closeSidebar);

        // Close when nav link clicked on mobile
        sidebar.querySelectorAll('a.nav-item').forEach(function(link) {
            link.addEventListener('click', function() {
                if (window.innerWidth <= 768) closeSidebar();
            });
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSidebar);
    } else {
        initSidebar(); // already ready
    }
})();

// ===== COUNTDOWN TIMER =====
function updateCountdowns() {
    document.querySelectorAll('[data-date]').forEach(function(el) {
        var target = new Date(el.dataset.date + 'T00:00:00');
        var now    = new Date();
        var diff   = target - now;

        if (diff <= 0) {
            el.innerHTML = '<span style="color:var(--danger)">Exam day!</span>';
            return;
        }

        var days  = Math.floor(diff / 86400000);
        var hours = Math.floor((diff % 86400000) / 3600000);
        var mins  = Math.floor((diff % 3600000) / 60000);
        var secs  = Math.floor((diff % 60000) / 1000);

        function pad(n) { return String(n).padStart(2, '0'); }
        el.innerHTML =
            '<span class="countdown-unit"><span class="countdown-number">' + pad(days)  + '</span><span class="countdown-label">Days</span></span>' +
            '<span class="countdown-unit"><span class="countdown-number">' + pad(hours) + '</span><span class="countdown-label">Hours</span></span>' +
            '<span class="countdown-unit"><span class="countdown-number">' + pad(mins)  + '</span><span class="countdown-label">Mins</span></span>' +
            '<span class="countdown-unit"><span class="countdown-number">' + pad(secs)  + '</span><span class="countdown-label">Secs</span></span>';
    });
}
if (document.querySelector('[data-date]')) {
    updateCountdowns();
    setInterval(updateCountdowns, 1000);
}

// ===== MODAL =====
function openModal(id) {
    var m = document.getElementById(id);
    if (m) { m.classList.add('active'); document.body.style.overflow = 'hidden'; }
}
function closeModal(id) {
    var m = document.getElementById(id);
    if (m) { m.classList.remove('active'); document.body.style.overflow = ''; }
}
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) closeModal(e.target.id);
});

// ===== TOAST =====
function showToast(message, type) {
    type = type || 'success';
    var toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(function() { toast.classList.add('show'); }, 10);
    setTimeout(function() {
        toast.classList.remove('show');
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

// ===== AJAX HELPER =====
async function doAjax(url, formData) {
    var res = await fetch(url, {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    var text = await res.text();
    try {
        return JSON.parse(text);
    } catch(e) {
        console.error('Non-JSON response:', text.substring(0, 300));
        throw new Error('Server error. Check PHP error logs.');
    }
}
