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(_) {} }
        modal.classList.remove('show');
        modal.setAttribute('aria-hidden','true');
        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();
                    var msg = encodeURIComponent(json.message || '');
                    // Reload immediately with success message in URL
                    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; } 
            });
    });
});








