// === AVI S9-B + S10-D : Alertes flotte B2C → Agency Dashboard ===
// S9-B READ ONLY | S10-D auto-refresh + badges + filtres UI

const AVI_S9B_VERSION = '1.0';
const AVI_S10D_VERSION = '1.0';

/** @type {number|null} */
var __aviAlertsRefreshTimer = null;

function aviGetAlertsDaysFromDom() {
    var sel = document.querySelector('#avi-agency-alerts-days');
    if (!sel) {
        return 7;
    }
    var v = parseInt(String(sel.value), 10);
    return isNaN(v) ? 7 : v;
}

function aviGetAlertsFilterFromDom() {
    var ab = document.querySelector('#avi-agency-alerts-panel .avi-filter-btn.active');
    if (!ab) {
        return 'all';
    }
    return ab.getAttribute('data-avi-filter') || 'all';
}

function aviSyncFilterButtonsActive(filter) {
    document.querySelectorAll('#avi-agency-alerts-panel .avi-filter-btn').forEach(function (btn) {
        var f = btn.getAttribute('data-avi-filter') || '';
        btn.classList.toggle('active', f === filter);
    });
}

/**
 * S10-D : Mise à jour badges compteurs (priorité aux totaux serveur meta.alert_counts).
 *
 * @param {Array} alerts Liste affichée (peut être filtrée).
 * @param {object} meta Métadonnées réponse AJAX.
 */
function aviUpdateFilterBadges(alerts, meta) {
    var counts = (meta && meta.alert_counts) ? meta.alert_counts : null;
    var critCount;
    var warnCount;
    var allCount;

    if (counts && typeof counts === 'object') {
        critCount = parseInt(String(counts.critical), 10) || 0;
        warnCount = parseInt(String(counts.warning), 10) || 0;
        allCount = parseInt(String(counts.all), 10) || 0;
    } else {
        if (!alerts || !alerts.length) {
            critCount = 0;
            warnCount = 0;
            allCount = 0;
        } else {
            critCount = alerts.filter(function (a) {
                return a.priority === 'critical';
            }).length;
            warnCount = alerts.filter(function (a) {
                return a.priority === 'warning';
            }).length;
            allCount = alerts.length;
        }
    }

    document.querySelectorAll('[data-avi-filter]').forEach(function (btn) {
        var filter = btn.getAttribute('data-avi-filter');
        var count = filter === 'critical' ? critCount
            : filter === 'warning' ? warnCount
                : allCount;

        var badge = btn.querySelector('.avi-filter-badge');
        if (!badge) {
            badge = document.createElement('span');
            badge.className = 'avi-filter-badge';
            btn.appendChild(badge);
        }
        badge.textContent = count > 0 ? '(' + count + ')' : '';
        badge.style.display = count > 0 ? 'inline' : 'none';

        if (filter === 'critical' && critCount > 0) {
            btn.classList.add('avi-filter-has-critical');
        } else {
            btn.classList.remove('avi-filter-has-critical');
        }
    });
}

function aviLoadAgencyAlerts(options) {
    options = options || {};
    var container = document.getElementById('avi-agency-alerts-container');
    if (!container) {
        return;
    }

    var days = options.days !== undefined && options.days !== null
        ? parseInt(String(options.days), 10)
        : aviGetAlertsDaysFromDom();
    if (isNaN(days)) {
        days = 7;
    }

    var filter = options.filter !== undefined && options.filter !== null
        ? String(options.filter)
        : aviGetAlertsFilterFromDom();
    var limit = options.limit || 50;

    aviSyncFilterButtonsActive(filter);

    container.innerHTML = '<div style="padding:12px;opacity:.6">⏳ Chargement...</div>';

    var formData = new FormData();
    formData.append('action', 'avision_get_agency_alerts');
    formData.append('nonce', (window.aviAgencyData || {}).nonce || '');
    formData.append('days', String(days));
    formData.append('filter', filter);
    formData.append('limit', String(limit));

    fetch((window.aviAgencyData || {}).ajaxurl || '/wp-admin/admin-ajax.php', {
        method: 'POST',
        body: formData
    })
        .then(function (r) {
            return r.json();
        })
        .then(function (data) {
            if (!data.success) {
                container.innerHTML = '<div style="color:red">⚠️ Erreur (' +
                    (((data.data || {}) || {}).code || 'unknown') + ')</div>';
                return;
            }
            var d = data.data || {};
            var alerts = d.alerts || [];
            var meta = d.meta || {};
            container.innerHTML = aviAlertsRender(alerts, d.fleet_kpis, meta);
            aviUpdateFilterBadges(alerts, meta);
        })
        .catch(function () {
            container.innerHTML = '<div style="color:red">⚠️ Erreur réseau</div>';
        });
}

function aviAlertsRender(alerts, fleet_kpis, meta) {
    if (!alerts || alerts.length === 0) {
        return '<div style="padding:16px;color:green">' +
            '✅ Aucune alerte sur les ' + (meta.days || 7) + ' derniers jours.' +
            '</div>';
    }

    var priorityLabel = {
        critical: '🔴 Critique',
        warning: '🟠 Attention',
        info: '📋 Info'
    };

    var rows = alerts.map(function (a) {
        return '<div class="avi-alert-row avi-alert-' + a.priority + '"' +
            ' style="display:flex;gap:8px;align-items:center;' +
            'padding:8px 12px;border-bottom:1px solid #f0f0f0">' +
            '<span>' + (a.shield_icon || '📋') + '</span>' +
            '<span style="font-weight:600;min-width:140px">' +
            aviEsc(a.business_name) + '</span>' +
            '<span style="color:#666;min-width:140px">' +
            aviEsc(a.signal_label) + '</span>' +
            '<span style="min-width:110px">' +
            (priorityLabel[a.priority] || a.priority) + '</span>' +
            '<span style="flex:1;font-size:.85em;color:#444">' +
            aviEsc(a.message) + '</span>' +
            '<span style="color:#999;font-size:.8em;white-space:nowrap">' +
            aviFormatDate(a.created_at) + '</span>' +
            '</div>';
    }).join('');

    return '<div class="avi-alerts-header" ' +
        'style="display:flex;justify-content:space-between;' +
        'padding:8px 12px;background:#f8f8f8;font-size:.85em;color:#666">' +
        '<strong>' + (meta.total || alerts.length) + ' alerte(s)</strong>' +
        '<span>Mis à jour : ' + aviFormatDate(meta.generated_at) + '</span>' +
        '</div>' +
        '<div class="avi-alerts-list">' + rows + '</div>';
}

function aviEsc(s) {
    if (!s) {
        return '';
    }
    return String(s)
        .replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function aviFormatDate(dt) {
    if (!dt) {
        return '—';
    }
    try {
        return new Date(String(dt).replace(' ', 'T') + 'Z')
            .toLocaleString(({ en: 'en-GB', fr: 'fr-FR', es: 'es-ES' }[(window.aviAgencyData?.lang || 'en')] || 'en-GB'), {
                day: '2-digit', month: '2-digit',
                hour: '2-digit', minute: '2-digit'
            });
    } catch (e) {
        return String(dt);
    }
}

/**
 * S10-D : Auto-refresh alertes (intervalle depuis aviAgencyData.alertRefreshMs).
 *
 * @param {object} options Options par défaut pour aviLoadAgencyAlerts (ex. { filter: 'all' }).
 */
function aviStartAlertsAutoRefresh(options) {
    var intervalMs = (window.aviAgencyData && window.aviAgencyData.alertRefreshMs)
        ? parseInt(String(window.aviAgencyData.alertRefreshMs), 10)
        : 300000;
    if (isNaN(intervalMs) || intervalMs < 60000) {
        intervalMs = 300000;
    }

    if (__aviAlertsRefreshTimer) {
        clearInterval(__aviAlertsRefreshTimer);
    }
    __aviAlertsRefreshTimer = setInterval(function () {
        if (document.getElementById('avi-agency-alerts-container')) {
            aviLoadAgencyAlerts({
                days: aviGetAlertsDaysFromDom(),
                filter: (options && options.filter) ? options.filter : aviGetAlertsFilterFromDom()
            });
        }
    }, intervalMs);
}

document.addEventListener('visibilitychange', function () {
    if (document.hidden) {
        if (__aviAlertsRefreshTimer) {
            clearInterval(__aviAlertsRefreshTimer);
            __aviAlertsRefreshTimer = null;
        }
    } else if (document.getElementById('avi-agency-alerts-container')) {
        aviLoadAgencyAlerts({
            days: aviGetAlertsDaysFromDom(),
            filter: aviGetAlertsFilterFromDom()
        });
        aviStartAlertsAutoRefresh({});
    }
});

document.addEventListener('DOMContentLoaded', function () {
    var daysSel = document.getElementById('avi-agency-alerts-days');
    if (daysSel) {
        daysSel.addEventListener('change', function () {
            aviLoadAgencyAlerts({
                days: aviGetAlertsDaysFromDom(),
                filter: aviGetAlertsFilterFromDom()
            });
        });
    }

    if (document.getElementById('avi-agency-alerts-container')) {
        aviLoadAgencyAlerts({ days: 7, filter: 'all' });
        aviStartAlertsAutoRefresh({});
    }
});
// === FIN AVI S9-B / S10-D ===
