/**
 * Admin Leads Page JS — NoonElite Audit Engine
 *
 * Handles: bulk CRM sync progress UI
 * Localized data available via noonAuditLeads object.
 */
(function() {
    'use strict';

    document.addEventListener('DOMContentLoaded', function() {
        var btn = document.getElementById('noon-audit-sync-missing');
        if (!btn) return;

        var container = document.getElementById('noon-audit-sync-progress-container');
        var bar = document.getElementById('noon-audit-sync-progress-bar');
        var status = document.getElementById('noon-audit-sync-status');

        btn.addEventListener('click', async function(e) {
            e.preventDefault();
            if (!confirm(noonAuditLeads.i18n.confirmSync)) return;

            btn.disabled = true;
            container.style.display = 'block';
            status.innerText = noonAuditLeads.i18n.fetching;

            try {
                var fd1 = new FormData();
                fd1.append('action', 'noon_audit_get_missing_leads');
                fd1.append('_wpnonce', noonAuditLeads.bulkSyncNonce);

                var res1 = await fetch(noonAuditLeads.ajaxUrl, { method: 'POST', body: fd1 }).then(function(r) { return r.json(); });

                if (!res1.success) {
                    status.innerText = 'Server Error: ' + (res1.data || 'Permission denied or session expired.');
                    bar.style.backgroundColor = '#ef4444';
                    btn.disabled = false;
                    return;
                }

                if (!res1.data.leads || res1.data.leads.length === 0) {
                    status.innerText = noonAuditLeads.i18n.noMissing;
                    bar.style.width = '100%';
                    bar.style.backgroundColor = '#10b981';
                    btn.disabled = false;
                    return;
                }

                var leadIds = res1.data.leads;
                var total = leadIds.length;
                var batchSize = 5;
                var current = 0;

                status.innerText = noonAuditLeads.i18n.syncing + ' 0 ' + noonAuditLeads.i18n.of + ' ' + total + noonAuditLeads.i18n.leads;

                for (var i = 0; i < total; i += batchSize) {
                    var batch = leadIds.slice(i, i + batchSize);

                    var fd2 = new FormData();
                    fd2.append('action', 'noon_audit_process_sync_batch');
                    fd2.append('batch', JSON.stringify(batch));
                    fd2.append('_wpnonce', noonAuditLeads.bulkSyncNonce);

                    var res2 = await fetch(noonAuditLeads.ajaxUrl, { method: 'POST', body: fd2 }).then(function(r) { return r.json(); });

                    if (!res2.success) {
                        console.error('Batch failed:', res2);
                    }

                    current += batch.length;
                    var pct = Math.round((current / total) * 100);
                    bar.style.width = pct + '%';
                    status.innerText = noonAuditLeads.i18n.syncing + ' ' + current + noonAuditLeads.i18n.of + ' ' + total + noonAuditLeads.i18n.leads;
                }

                status.innerText = noonAuditLeads.i18n.finished + ' ' + total + noonAuditLeads.i18n.leadsRefresh;
                bar.style.backgroundColor = '#10b981';
                btn.disabled = false;

            } catch (err) {
                status.innerText = noonAuditLeads.i18n.networkError + err.message;
                bar.style.backgroundColor = '#ef4444';
                btn.disabled = false;
            }
        });
    });
})();
