/**
 * assets/js/app.js
 * CES Portal — Custom application JavaScript
 */

(function () {
    'use strict';

    // ── Sidebar toggle (mobile) ───────────────────────────────────────────────

    var headerBtn = document.getElementById('headerMenuBtn');
    var sidebar   = document.querySelector('.sidebar-wrapper');

    if (headerBtn && sidebar) {
        headerBtn.addEventListener('click', function (e) {
            e.preventDefault();
            sidebar.classList.toggle('open');
        });

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (e) {
            if (window.innerWidth < 992) {
                if (!sidebar.contains(e.target) && e.target !== headerBtn && !headerBtn.contains(e.target)) {
                    sidebar.classList.remove('open');
                }
            }
        });
    }

    // ── Confirm dialogs ───────────────────────────────────────────────────────
    // Forms with data-confirm attribute will prompt before submitting

    document.addEventListener('submit', function (e) {
        var form = e.target;
        var msg  = form.getAttribute('data-confirm');
        if (msg && !window.confirm(msg)) {
            e.preventDefault();
        }
    });

    // ── Auto-dismiss flash alerts ─────────────────────────────────────────────

    var alerts = document.querySelectorAll('.alert.alert-success');
    alerts.forEach(function (alert) {
        setTimeout(function () {
            if (typeof $ !== 'undefined') {
                $(alert).fadeOut(400, function () { $(this).remove(); });
            } else {
                alert.style.display = 'none';
            }
        }, 4000);
    });

    // ── Initialize Feather Icons ──────────────────────────────────────────────

    if (typeof feather !== 'undefined') {
        feather.replace();
    }

}());
