/**
 * Cincinnati Fire Department Portal — Active911 Toast Notifications
 * Polls api/incidents.php every 15 seconds.
 * Shows iOS-style notifications for new incidents.
 */
(function() {
    'use strict';

    const P = window.CFD_PORTAL || {};
    const container = document.getElementById('toastContainer');
    if (!container) return;

    const MAX_TOASTS = 4;
    const AUTO_DISMISS_MS = 8000;
    let consecutiveFailures = 0;
    let firstPoll = true;

    async function pollIncidents() {
        try {
            const data = await window.portalAPI('incidents.php?action=new');
            if (!data) {
                consecutiveFailures++;
                if (consecutiveFailures >= 3) showOfflineBadge();
                return;
            }

            consecutiveFailures = 0;
            hideOfflineBadge();

            // First poll after login: silently mark all as displayed, don't show toasts
            if (firstPoll) {
                firstPoll = false;
                return;
            }

            if (data.incidents && data.incidents.length > 0) {
                // Group by incident_id so one toast per call, all units merged
                const grouped = {};
                data.incidents.forEach(inc => {
                    const key = inc.incident_id || inc.id;
                    if (!grouped[key]) {
                        grouped[key] = { ...inc, _allUnits: new Set() };
                    }
                    // Merge units from this row
                    (inc.units_assigned || '').split(',').filter(u => u.trim()).forEach(u => grouped[key]._allUnits.add(u.trim()));
                    // Keep latest data
                    if ((inc.received_at || '') > (grouped[key].received_at || '')) {
                        grouped[key].incident_type = inc.incident_type || grouped[key].incident_type;
                        grouped[key].address = inc.address || grouped[key].address;
                        grouped[key].priority = inc.priority || grouped[key].priority;
                        grouped[key].received_at = inc.received_at;
                    }
                });
                Object.values(grouped).forEach(inc => {
                    inc.units_assigned = [...inc._allUnits].join(',');
                    // Show toast only if not muted
                    if (!window.toastsMuted) showToast(inc);
                    // Structure fire alert ALWAYS fires (safety critical)
                    if ((inc.incident_type || '').toUpperCase().includes('STRUCT')) {
                        window.dispatchEvent(new CustomEvent('structureFire', { detail: inc }));
                    }
                });
            }
        } catch (err) {
            consecutiveFailures++;
            if (consecutiveFailures >= 3) showOfflineBadge();
        }
    }

    function showToast(incident) {
        const incidentId = incident.incident_id || incident.id;

        // If toast for this incident already visible, update units and skip
        const existingForId = container.querySelector(`.toast[data-incident-id="${incidentId}"]:not(.dismissing)`);
        if (existingForId) {
            const unitsEl = existingForId.querySelector('.toast-units');
            const units = (incident.units_assigned || '').split(',').filter(u => u.trim());
            if (unitsEl && units.length) {
                unitsEl.innerHTML = units.map(u => `<span class="toast-unit">${escapeHtml(u.trim())}</span>`).join('');
            }
            return;
        }

        // Limit max visible toasts
        const existing = container.querySelectorAll('.toast:not(.dismissing)');
        if (existing.length >= MAX_TOASTS) {
            dismissToast(existing[0]);
        }

        const priority = incident.priority || '3';
        const units = (incident.units_assigned || '').split(',').filter(u => u.trim());
        const time = incident.received_at ? window.timeAgo(incident.received_at) : 'now';

        const toast = document.createElement('div');
        toast.className = `toast toast--priority-${priority}`;
        toast.setAttribute('data-incident-id', incidentId);
        toast.innerHTML = `
            <div class="toast-header">
                <div class="toast-header-left">
                    <img src="assets/img/cfd-logo.png" class="toast-app-icon" alt="CFD">
                    <span class="toast-app-name">Cincinnati Fire</span>
                </div>
                <span class="toast-time">${time}</span>
            </div>
            <div class="toast-divider"></div>
            <div class="toast-type">${escapeHtml(incident.incident_type || 'Incident')}</div>
            <div class="toast-address">${escapeHtml(incident.address || 'Unknown location')}</div>
            ${units.length > 0 ? `
                <div class="toast-units">
                    ${units.map(u => `<span class="toast-unit">${escapeHtml(u.trim())}</span>`).join('')}
                </div>
            ` : ''}
            <div class="toast-footer">
                <a href="dashboard.php?page=incidents" class="toast-view-all">View All Incidents</a>
            </div>
        `;

        // Click to dismiss
        toast.addEventListener('click', () => dismissToast(toast));

        container.appendChild(toast);

        // Auto-dismiss
        setTimeout(() => dismissToast(toast), AUTO_DISMISS_MS);
    }

    function dismissToast(toast) {
        if (!toast || toast.classList.contains('dismissing')) return;
        toast.classList.add('dismissing');
        toast.addEventListener('animationend', () => toast.remove());
    }

    function showOfflineBadge() {
        if (document.getElementById('incidentOfflineBadge')) return;
        const badge = document.createElement('span');
        badge.id = 'incidentOfflineBadge';
        badge.className = 'incident-offline-badge';
        badge.innerHTML = '&#x26A0; Incident feed offline';
        const headerRight = document.querySelector('.header-right');
        if (headerRight) headerRight.prepend(badge);
    }

    function hideOfflineBadge() {
        const badge = document.getElementById('incidentOfflineBadge');
        if (badge) badge.remove();
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str || '';
        return div.innerHTML;
    }

    // Start polling
    pollIncidents();
    setInterval(pollIncidents, P.incidentRefresh || 15000);
})();
