document.addEventListener('DOMContentLoaded', function () {
    var modal = document.getElementById('category-modal');
    if (!modal) { return; }

    var actionInput = document.getElementById('category-action');
    var idInput = document.getElementById('category-id');
    var vnInput = document.getElementById('category-name-vn');
    var engInput = document.getElementById('category-name-eng');
    var submitBtn = document.getElementById('category-submit');
    var titleEl = document.getElementById('category-modal-title');
    var lastFocused = null;

    function openModal(){
        lastFocused = document.activeElement;
        modal.classList.add('show');
        modal.setAttribute('aria-hidden','false');
        if (vnInput) { try { vnInput.focus(); } catch(_) {} }
    }
    function closeModal(){
        var active = document.activeElement;
        if (active && modal.contains(active)) { try { active.blur(); } catch(_) {} }
        // Hide modal immediately to prevent white box flash
        modal.style.display = 'none';
        modal.style.visibility = 'hidden';
        modal.style.opacity = '0';
        modal.classList.remove('show');
        modal.setAttribute('aria-hidden','true');
        // Force reflow to ensure styles are applied
        void modal.offsetHeight;
        if (lastFocused && document.contains(lastFocused)) { try { lastFocused.focus(); } catch(_) {} }
        lastFocused = null;
    }

    function setCreate(){
        if (actionInput) actionInput.value = 'create';
        if (idInput) idInput.value = '0';
        if (vnInput) vnInput.value = '';
        if (engInput) engInput.value = '';
        if (submitBtn) submitBtn.textContent = (submitBtn.getAttribute('data-label-save') || submitBtn.textContent || 'Lưu');
        if (titleEl) titleEl.textContent = titleEl.getAttribute('data-title-create') || titleEl.textContent;
    }

    document.addEventListener('click', function(e){
        var addBtn = e.target.closest('[data-category-open="create"]');
        if(addBtn){ setCreate(); openModal(); return; }

        var editBtn = e.target.closest('[data-category-edit]');
        if(editBtn){
            var id = editBtn.getAttribute('data-category-id');
            var vn = editBtn.getAttribute('data-category-name-vn');
            var eng = editBtn.getAttribute('data-category-name-eng');
            if (actionInput) actionInput.value = 'update';
            if (idInput) idInput.value = String(id || 0);
            if (vnInput) vnInput.value = vn || '';
            if (engInput) engInput.value = eng || '';
            if (submitBtn) submitBtn.textContent = (submitBtn.getAttribute('data-label-update') || submitBtn.textContent || 'Cập nhật');
            if (titleEl) titleEl.textContent = titleEl.getAttribute('data-title-update') || titleEl.textContent;
            openModal();
            return;
        }

        if(e.target.closest('[data-modal-close]')){ closeModal(); }
    });

    document.addEventListener('keydown', function(e){ if(e.key === 'Escape'){ closeModal(); }});

    var form = document.getElementById('category-form');
    if (!form) return;

    form.addEventListener('submit', function(e){
        e.preventDefault();
        var submitBtnEl = document.getElementById('category-submit');
        if (submitBtnEl) { submitBtnEl.disabled = true; }

        // Ensure license is present
        try {
            var licInput = document.getElementById('category-license');
            if (licInput && licInput.value) { /* ok */ } else if (licInput) { licInput.value = licInput.value || ''; }
        } catch(_) {}

        var data = new FormData(form);
        if (!data.has('license')) {
            var licEl = document.getElementById('category-license');
            data.append('license', (licEl && licEl.value) ? licEl.value : '');
        }
        var postUrl = form.getAttribute('action') || form.action;
        fetch(postUrl, { method: 'POST', headers: { 'X-Requested-With': 'fetch', 'Accept': 'application/json' }, body: data })
            .then(function(r){ return r.text(); })
            .then(function(text){
                var json = null;
                try { json = text ? JSON.parse(text) : null; } catch(_) {}
                if (!json) {
                    if (window.showToast) { 
                        const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                        window.showToast('error', '<div class="error-header">' + errorTitle + '</div>Network error'); 
                    }
                    if (submitBtnEl) { submitBtnEl.disabled = false; }
                    return;
                }
                if (json && json.ok) {
                    closeModal();
                    // Mark body as reloading and hide all elements immediately
                    document.body.classList.add('reloading');
                    var elementsToHide = document.querySelectorAll('.modal-backdrop, .modal-overlay, .user-actions-dropdown, .page-loader');
                    elementsToHide.forEach(function(el) {
                        el.style.display = 'none';
                        el.style.visibility = 'hidden';
                        el.style.opacity = '0';
                        el.classList.remove('show');
                    });
                    // Force reflow to ensure styles are applied
                    void document.body.offsetHeight;
                    // Add critical CSS to prevent flash
                    var style = document.createElement('style');
                    style.id = 'reload-prevent-flash';
                    style.textContent = '* { transition: none !important; animation: none !important; } .page-loader, .modal-backdrop, .modal-overlay { display: none !important; visibility: hidden !important; opacity: 0 !important; }';
                    document.head.appendChild(style);
                    // Use requestAnimationFrame to ensure DOM is updated before reload
                    var msg = encodeURIComponent(json.message || '');
                    requestAnimationFrame(function() {
                        requestAnimationFrame(function() {
                            location.href = 'index.php?category=1&success=' + msg;
                        });
                    });
                } else {
                    var err = (json && json.message) ? String(json.message) : 'Error';
                    err = err.replace(/\n/g, '<br>');
                    
                    // Add error header like incoming documents
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + err;
                    
                    if (window.showToast) { window.showToast('error', errorWithHeader); }
                    if (submitBtnEl) { submitBtnEl.disabled = false; }
                }
            })
            .catch(function(){ 
                if (window.showToast) { 
                    const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    window.showToast('error', '<div class="error-header">' + errorTitle + '</div>Network error'); 
                } 
                if (submitBtnEl) { submitBtnEl.disabled = false; } 
            });
    });
});








