/**
 * main.js — Application JavaScript
 */

'use strict';

// ── Auto-dismiss alerts after 6 seconds ──────────────────
document.querySelectorAll('.alert').forEach(function (el) {
    setTimeout(function () {
        el.style.transition = 'opacity .4s';
        el.style.opacity    = '0';
        setTimeout(function () { el.remove(); }, 420);
    }, 6000);
});

// ── Dropdown keyboard accessibility ──────────────────────
document.querySelectorAll('.dropdown').forEach(function (dropdown) {
    var btn  = dropdown.querySelector('.btn-tool');
    var menu = dropdown.querySelector('.dropdown-menu');
    if (!btn || !menu) return;

    btn.addEventListener('click', function (e) {
        e.stopPropagation();
        var open = dropdown.classList.toggle('open');
        menu.style.display = open ? 'block' : 'none';
    });

    // Close on outside click
    document.addEventListener('click', function () {
        dropdown.classList.remove('open');
        menu.style.display = 'none';
    });
});

// ── Confirm password match validation ────────────────────
(function () {
    var newPw  = document.getElementById('new_password');
    var confPw = document.getElementById('confirm_password');
    if (!newPw || !confPw) return;

    function check() {
        if (confPw.value && newPw.value !== confPw.value) {
            confPw.setCustomValidity('Passwords do not match');
        } else {
            confPw.setCustomValidity('');
        }
    }
    newPw.addEventListener('input',  check);
    confPw.addEventListener('input', check);
})();

// ── Menus déroulants des rails de rapports (Oracle et PostgreSQL) ────────
// Le bouton appelle ociToggle/pgToggle(id, event) et stoppe la propagation
// pour que le listener de fermeture (phase BULLE) ne referme pas aussitôt.
// Ne jamais passer en phase capture : le menu se fermerait avant l'ouverture.
var DB_NAV_FAMILIES = ['oracle', 'pg'];

function dbNavCloseAll(family) {
    document.querySelectorAll('.' + family + '-dropdown.open').forEach(function (d) {
        d.classList.remove('open');
    });
}
function dbNavToggle(id, event, family) {
    if (event) event.stopPropagation();
    var el = document.getElementById(id);
    if (!el) return;
    var isOpen = el.classList.contains('open');
    dbNavCloseAll(family);
    if (!isOpen) el.classList.add('open');
}
window.ociToggle = function (id, event) { dbNavToggle(id, event, 'oracle'); };
window.pgToggle  = function (id, event) { dbNavToggle(id, event, 'pg'); };

// Fermeture sur clic extérieur (phase bulle — après stopPropagation du bouton)
document.addEventListener('click', function (e) {
    if (!e.target.closest) return;
    DB_NAV_FAMILIES.forEach(function (fam) {
        if (!e.target.closest('.' + fam + '-dropdown')) dbNavCloseAll(fam);
    });
});

// ── Oracle reports sidebar : collapse persistant + hauteur header ──
(function () {
    var header = document.querySelector('.site-header');
    function syncHeaderHeight() {
        if (header) {
            document.documentElement.style.setProperty(
                '--ora-header-h', header.offsetHeight + 'px'
            );
        }
    }
    syncHeaderHeight();
    window.addEventListener('resize', syncHeaderHeight);

    // Un rail par module (Oracle, PostgreSQL) : repli persistant via le burger
    // placé à côté du logo applicatif.
    function initReportSidebar(toggleId, bodyClass, storageKey) {
        var toggle = document.getElementById(toggleId);
        try {
            if (localStorage.getItem(storageKey) === '1') {
                document.body.classList.add(bodyClass);
            }
        } catch (e) { /* private mode */ }
        if (!toggle) return;
        toggle.addEventListener('click', function () {
            var collapsed = document.body.classList.toggle(bodyClass);
            try { localStorage.setItem(storageKey, collapsed ? '1' : '0'); } catch (e) {}
        });
    }
    initReportSidebar('oracle-sidebar-toggle', 'oracle-sidebar-collapsed', 'oracle_sidebar_collapsed');
    initReportSidebar('pg-sidebar-toggle',     'pg-sidebar-collapsed',     'pg_sidebar_collapsed');
})();

// ── Theme live preview ────────────────────────────────────
(function () {
    var themeLinks = document.querySelectorAll('[href*="?theme="]');
    themeLinks.forEach(function (link) {
        link.addEventListener('mouseenter', function () {
            var match = link.href.match(/[?&]theme=([^&]+)/);
            if (match) {
                document.documentElement.setAttribute('data-theme', match[1]);
                var css = document.getElementById('theme-css');
                if (css) css.href = '/assets/css/themes/' + match[1] + '.css';
            }
        });
    });
})();
