// Nazareth Church Management System - Main JS

function showToast(type, message, opts) {
    var container = document.getElementById('toast-container');
    if (!container) return;
    opts = opts || {};
    var timeoutMs = typeof opts.timeoutMs === 'number' ? opts.timeoutMs : 5000;
    var toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.setAttribute('role', type === 'error' ? 'alert' : 'status');
    toast.setAttribute('aria-live', type === 'error' ? 'assertive' : 'polite');

    var msg = document.createElement('div');
    msg.className = 'toast-message';
    msg.textContent = message;

    var closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'toast-close';
    closeBtn.setAttribute('aria-label', 'Dismiss');
    closeBtn.innerHTML = '&times;';

    toast.appendChild(msg);
    toast.appendChild(closeBtn);
    container.appendChild(toast);

    var remove = function() {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        setTimeout(function() { toast.remove(); }, 200);
    };

    var timer = null;
    var startTimer = function() {
        if (timeoutMs <= 0) return;
        timer = setTimeout(remove, timeoutMs);
    };
    var clearTimer = function() {
        if (timer) clearTimeout(timer);
        timer = null;
    };

    closeBtn.addEventListener('click', function() {
        clearTimer();
        remove();
    });
    toast.addEventListener('mouseenter', clearTimer);
    toast.addEventListener('mouseleave', startTimer);
    startTimer();
}

document.addEventListener('DOMContentLoaded', function() {
    // Toast from URL params (success/error after redirect)
    var params = new URLSearchParams(window.location.search);
    var msg = params.get('toast') || params.get('success');
    if (msg) {
        showToast('success', decodeURIComponent(msg.replace(/\+/g, ' ')));
        params.delete('toast');
        params.delete('success');
        var qs = params.toString();
        var clean = (qs ? '?' + qs : '') + (window.location.hash || '');
        history.replaceState(null, '', window.location.pathname + clean);
    }
    msg = params.get('toast_error') || params.get('error');
    if (msg) {
        showToast('error', decodeURIComponent(msg.replace(/\+/g, ' ')));
        params.delete('toast_error');
        params.delete('error');
        var qs = params.toString();
        var clean = (qs ? '?' + qs : '') + (window.location.hash || '');
        history.replaceState(null, '', window.location.pathname + clean);
    }

    // Toast from data attribute (form validation errors)
    var el = document.querySelector('[data-toast]');
    if (el) {
        showToast(el.getAttribute('data-toast') || 'error', el.getAttribute('data-toast-msg') || el.textContent);
    }

    // Confirm delete modal
    var modal = document.getElementById('confirm-modal');
    var modalMsg = document.getElementById('modal-title');
    var modalCancel = modal && modal.querySelector('.modal-cancel');
    var modalConfirm = modal && modal.querySelector('.modal-confirm');
    var modalBackdrop = modal && modal.querySelector('.modal-backdrop');
    var lastActiveEl = null;

    function closeModal() {
        if (!modal) return;
        modal.hidden = true;
        document.body.classList.remove('modal-open');
        document.removeEventListener('keydown', onModalKeydown, true);
        if (lastActiveEl && typeof lastActiveEl.focus === 'function') {
            lastActiveEl.focus();
        }
    }

    function showConfirmModal(message, onConfirm, confirmButtonText, opts) {
        if (!modal) return;
        opts = opts || {};
        lastActiveEl = document.activeElement;
        modalMsg.textContent = message;
        modalConfirm.textContent = confirmButtonText || 'Confirm';
        if (modalCancel) {
            modalCancel.hidden = !!opts.hideCancel;
        }
        modal.hidden = false;
        document.body.classList.add('modal-open');
        document.addEventListener('keydown', onModalKeydown, true);
        setTimeout(function() {
            if (modalConfirm) modalConfirm.focus();
        }, 0);
        modalConfirm.onclick = function() {
            closeModal();
            if (onConfirm) onConfirm();
        };
    }

    if (modalCancel) modalCancel.addEventListener('click', closeModal);
    if (modalBackdrop) modalBackdrop.addEventListener('click', closeModal);
    if (modal) {
        // Prevent clicks inside content from closing via backdrop handler
        var content = modal.querySelector('.modal-content');
        if (content) content.addEventListener('click', function(e) { e.stopPropagation(); });
    }

    function onModalKeydown(e) {
        if (!modal || modal.hidden) return;
        if (e.key === 'Escape') {
            e.preventDefault();
            closeModal();
            return;
        }
        if (e.key !== 'Tab') return;
        // Basic focus trap inside modal
        var focusable = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
        if (!focusable.length) return;
        var first = focusable[0];
        var last = focusable[focusable.length - 1];
        if (e.shiftKey && document.activeElement === first) {
            e.preventDefault();
            last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
            e.preventDefault();
            first.focus();
        }
    }

    // System admin (/system): collapsible sidebar on narrow viewports
    if (document.body.classList.contains('theme-system')) {
        var sysToggle = document.getElementById('system-nav-toggle');
        var sysSidebar = document.getElementById('system-sidebar');
        var sysBackdrop = document.getElementById('system-sidebar-backdrop');
        function systemNavSetOpen(open) {
            document.body.classList.toggle('system-nav-open', open);
            if (sysToggle) {
                sysToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
                sysToggle.setAttribute('aria-label', open ? 'Close menu' : 'Open menu');
            }
            if (sysBackdrop) {
                sysBackdrop.hidden = !open;
            }
            document.body.style.overflow = open ? 'hidden' : '';
        }
        if (sysToggle && sysSidebar) {
            sysToggle.addEventListener('click', function() {
                systemNavSetOpen(!document.body.classList.contains('system-nav-open'));
            });
            if (sysBackdrop) {
                sysBackdrop.addEventListener('click', function() {
                    systemNavSetOpen(false);
                });
            }
            sysSidebar.querySelectorAll('nav a').forEach(function(link) {
                link.addEventListener('click', function() {
                    systemNavSetOpen(false);
                });
            });
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && document.body.classList.contains('system-nav-open')) {
                    systemNavSetOpen(false);
                    if (sysToggle) sysToggle.focus();
                }
            });
            window.addEventListener('resize', function() {
                if (window.matchMedia('(min-width: 1025px)').matches) {
                    systemNavSetOpen(false);
                }
            });
        }
    }

    document.querySelectorAll('[data-confirm]').forEach(function(el) {
        el.addEventListener('click', function(e) {
            e.preventDefault();
            var msg = this.getAttribute('data-confirm') || 'Are you sure?';
            var btnText = this.getAttribute('data-confirm-btn');
            var mode = this.getAttribute('data-confirm-mode'); // "info" shows OK-only modal
            var url = this.getAttribute('href');
            var form = (this.tagName === 'BUTTON' || this.tagName === 'INPUT') ? (this.form || (this.closest && this.closest('form'))) : null;
            if (mode === 'info') {
                showConfirmModal(msg, null, btnText || 'OK', { hideCancel: true });
                return;
            }
            showConfirmModal(msg, function() {
                if (form) {
                    form.submit();
                } else if (url) {
                    window.location = url;
                }
            }, btnText, { hideCancel: false });
        });
    });
});
