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

    var actionInput = document.getElementById('company-action');
    var idInput = document.getElementById('company-id');
    var vnInput = document.getElementById('company-name-vn');
    var engInput = document.getElementById('company-name-eng');
    var submitBtn = document.getElementById('company-submit');
    var titleEl = document.getElementById('company-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') || 'Lưu');
        if (titleEl) titleEl.textContent = titleEl.getAttribute('data-title-create') || titleEl.textContent;
    }

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

        var editBtn = e.target.closest('[data-company-edit]');
        if(editBtn){
            var id = editBtn.getAttribute('data-company-id');
            var vn = editBtn.getAttribute('data-company-name-vn');
            var eng = editBtn.getAttribute('data-company-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') || '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('company-form');
    if (!form) return;

    form.addEventListener('submit', function(e){
        // Let server handle validation; always submit payload

        e.preventDefault();
        var submitBtnEl = document.getElementById('company-submit');
        if (submitBtnEl) { submitBtnEl.disabled = true; }

        try {
            var licInput = document.getElementById('company-license');
            // license value is rendered from PHP (database.php)
            if (licInput && licInput.value) { /* ok */ } else if (licInput) { licInput.value = licInput.value || ''; }
        } catch(_) {}
        // Build FormData after ensuring license is present
        var data = new FormData(form);
        if (!data.has('license')) {
            var licEl = document.getElementById('company-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(_) { /* non-JSON */ }
                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?company=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; } 
            });
    });
});


