<?php
/**
 * Active Incidents Dashboard — Hi-tech with ECharts + Satellite Map
 */
$db = getDB();
$incidents = $db->query("SELECT * FROM incidents_cache WHERE received_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY received_at DESC")->fetchAll();
$incidents7d = $db->query("SELECT * FROM incidents_cache WHERE received_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) ORDER BY received_at DESC")->fetchAll();
$total24 = count($incidents);
$latest = $incidents[0]['received_at'] ?? null;

// Stats
$p1 = $p2 = $p3 = 0;
$activeCount = 0;
$byType = [];
$byHourToday = array_fill(0, 24, 0);
$byHourYesterday = array_fill(0, 24, 0);
$heatmap = []; // [dayOfWeek][hour] = count

date_default_timezone_set('America/New_York');
$todayStart = strtotime('today');
$yesterdayStart = strtotime('yesterday');

foreach ($incidents7d as $inc) {
    $p = $inc['priority'] ?? '3';
    $t = $inc['incident_type'] ?? 'Unknown';
    $dt = strtotime($inc['received_at']);
    $hour = (int)date('G', $dt);
    $dow = (int)date('w', $dt); // 0=Sun

    $byType[$t] = ($byType[$t] ?? 0) + 1;

    if ($dt >= $todayStart) {
        if ($p == '1') $p1++;
        elseif ($p == '2') $p2++;
        else $p3++;
        if (($inc['status'] ?? '') === 'active') $activeCount++;
        $byHourToday[$hour]++;
    } elseif ($dt >= $yesterdayStart && $dt < $todayStart) {
        $byHourYesterday[$hour]++;
    }

    $key = "{$dow}-{$hour}";
    $heatmap[$key] = ($heatmap[$key] ?? 0) + 1;
}

arsort($byType);
$topTypes = array_slice($byType, 0, 8, true);

// Busiest Medic (M) and Engine (E) units in 24h
$unitCounts = [];
foreach ($incidents as $inc) {
    foreach (explode(',', $inc['units_assigned'] ?? '') as $u) {
        $u = trim($u);
        if ($u) $unitCounts[$u] = ($unitCounts[$u] ?? 0) + 1;
    }
}
arsort($unitCounts);
$topUnitsForChart = array_slice($unitCounts, 0, 10, true);
$busiestMedic = $busiestMedicRuns = $busiestEngine = $busiestEngineRuns = null;
foreach ($unitCounts as $unit => $cnt) {
    if (!$busiestMedic && str_starts_with($unit, 'M')) { $busiestMedic = $unit; $busiestMedicRuns = $cnt; }
    if (!$busiestEngine && str_starts_with($unit, 'E')) { $busiestEngine = $unit; $busiestEngineRuns = $cnt; }
    if ($busiestMedic && $busiestEngine) break;
}

// Build heatmap data array for ECharts: [hour, day, value]
$heatmapData = [];
for ($d = 0; $d < 7; $d++) {
    for ($h = 0; $h < 24; $h++) {
        $heatmapData[] = [$h, $d, $heatmap["{$d}-{$h}"] ?? 0];
    }
}
?>

<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>

<?php
    date_default_timezone_set('America/New_York');
    $oldest = $incidents7d ? end($incidents7d)['received_at'] : null;
    $newest = $incidents ? $incidents[0]['received_at'] : null;
    $dataStart = $oldest ? date('M j, g:i A', strtotime($oldest)) : '--';
    $dataEnd = $newest ? date('M j, g:i A', strtotime($newest)) : '--';
    $currentShift = getCurrentShiftBounds();
    $shift = $currentShift['shift'];
?>
<div class="page-header">
    <h1>Active Incidents</h1>
    <div style="display:flex; align-items:center; gap:12px;">
        <span class="badge <?= $total24 > 0 ? 'badge-green' : 'badge-gray' ?>" id="incidentLiveStatus">
            <?= $total24 > 0 ? 'Live' : 'Waiting' ?>
        </span>
        <span style="font-size:13px; color:var(--ios-secondary);"><?= $total24 ?> incidents (24h)</span>
        <button class="btn btn-sm btn-secondary" onclick="location.reload()">Refresh</button>
    </div>
</div>

<div style="display:flex; align-items:center; justify-content:space-between; padding:10px 16px; margin-bottom:16px; background:var(--ios-bg); border-radius:var(--ios-radius); border:1px solid var(--ios-border);">
    <div style="display:flex; align-items:center; gap:16px;">
        <div style="display:flex; align-items:center; gap:6px;">
            <span style="width:7px; height:7px; border-radius:50%; background:#00A6A0; box-shadow:0 0 6px #00A6A080;"></span>
            <span style="font-size:12px; font-weight:600; color:var(--primary);">Source: Active911 Webhook</span>
        </div>
        <span style="color:var(--ios-border);">|</span>
        <span style="font-size:12px; color:var(--ios-secondary);">
            Stat cards & hourly chart: <strong>last 24 hours</strong> &middot;
            Call types & heatmap: <strong>last 7 days</strong>
        </span>
    </div>
    <div style="display:flex; align-items:center; gap:12px;">
        <span style="font-size:11px; color:var(--ios-tertiary);">
            <?= $dataStart ?> — <?= $dataEnd ?>
        </span>
        <span style="color:var(--ios-border);">|</span>
        <span style="font-size:11px; padding:2px 10px; border-radius:12px; background:<?= $shift['color'] ?>20; color:<?= $shift['color'] ?>; font-weight:700;">
            On Duty: <?= $shift['unit'] ?>
        </span>
    </div>
</div>

<!-- Stat Cards -->
<div class="grid grid-4" style="margin-bottom:20px;">
    <div class="stat-card" style="border-top-color:var(--accent);">
        <span class="stat-value"><?= $total24 ?></span>
        <span class="stat-label">Incidents (24h)</span>
    </div>
    <div class="stat-card" style="border-top-color:#DC2626;">
        <span class="stat-value" style="color:#DC2626;"><?= $busiestEngine ?? '--' ?></span>
        <span class="stat-label">Busiest Engine (<?= $busiestEngineRuns ?? 0 ?> runs)</span>
    </div>
    <div class="stat-card" style="border-top-color:var(--cfd-teal);">
        <span class="stat-value" style="color:var(--cfd-teal);"><?= $busiestMedic ?? '--' ?></span>
        <span class="stat-label">Busiest Medic (<?= $busiestMedicRuns ?? 0 ?> runs)</span>
    </div>
    <div class="stat-card" style="border-top-color:var(--highlight);">
        <span class="stat-value" style="font-size:16px;">
            <?= $latest ? date('g:i A', strtotime($latest)) : 'No data' ?>
        </span>
        <span class="stat-label">Last Received</span>
    </div>
</div>

<!-- Satellite Map -->
<div class="card" style="margin-bottom:20px; padding:0; overflow:hidden; border:none; position:relative;">
    <div id="incidentsMap" style="height:400px; background:var(--primary);"></div>
    <div style="position:absolute; bottom:12px; left:12px; z-index:5; display:flex; gap:6px;">
        <button class="map-layer-btn active" id="btnDistricts" onclick="toggleLayer('districts', this)" title="Fire Districts">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
            Districts
        </button>
        <button class="map-layer-btn active" id="btnStations" onclick="toggleLayer('stations', this)" title="Fire Stations">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
            Stations
        </button>
    </div>
</div>
<style>
.map-layer-btn {
    display: inline-flex; align-items: center; gap: 5px;
    padding: 6px 12px; font-size: 11px; font-weight: 600;
    background: rgba(11,34,64,0.85); color: rgba(255,255,255,0.6);
    border: 1px solid rgba(255,255,255,0.15); border-radius: 8px;
    cursor: pointer; backdrop-filter: blur(8px); transition: all 0.2s;
}
.map-layer-btn:hover { background: rgba(11,34,64,0.95); color: #fff; }
.map-layer-btn.active { background: var(--accent); color: #fff; border-color: var(--accent); }
</style>

<!-- Charts Row -->
<div class="grid grid-2" style="margin-bottom:20px;">
    <!-- Incidents by Hour -->
    <div class="card">
        <div class="card-header"><h2 class="card-title">Today vs Yesterday by Hour</h2></div>
        <div id="chartByHour" style="height:280px;"></div>
    </div>
    <!-- Unit Activity Radar -->
    <div class="card">
        <div class="card-header"><h2 class="card-title">Busiest Units (24h)</h2></div>
        <div id="chartUnitRadar" style="height:280px;"></div>
    </div>
</div>

<div class="grid grid-2" style="margin-bottom:20px;">
    <!-- Incidents by Type -->
    <div class="card">
        <div class="card-header"><h2 class="card-title">Top Call Types (7 Days)</h2></div>
        <div id="chartByType" style="height:300px;"></div>
    </div>
    <!-- Heatmap -->
    <div class="card">
        <div class="card-header"><h2 class="card-title">Activity Heatmap (7 Days)</h2></div>
        <div id="chartHeatmap" style="height:300px;"></div>
    </div>
</div>

<!-- Incidents Table -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Incident Log</h2>
        <div class="segmented-control">
            <button class="seg-btn active" onclick="filterIncidents('all', this)">All</button>
            <button class="seg-btn" onclick="filterIncidents('1', this)">P1</button>
            <button class="seg-btn" onclick="filterIncidents('2', this)">P2</button>
            <button class="seg-btn" onclick="filterIncidents('3', this)">P3</button>
        </div>
    </div>
    <?php if (empty($incidents)): ?>
        <div class="empty-state" style="padding:48px;">
            <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="var(--ios-green)" stroke-width="1.5"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            <h3>No Active Incidents</h3>
            <p>All clear — waiting for Active911 alerts.</p>
        </div>
    <?php else: ?>
        <div class="table-wrapper">
            <table id="incidentsTable">
                <thead><tr><th>Priority</th><th>Type</th><th>Address</th><th>Units</th><th>Status</th><th>Time</th></tr></thead>
                <tbody>
                <?php foreach ($incidents as $inc):
                    $incJson = htmlspecialchars(json_encode([
                        'type' => $inc['incident_type'] ?? 'Unknown',
                        'address' => $inc['address'] ?? '',
                        'city' => $inc['city'] ?? '',
                        'id' => $inc['incident_id'] ?? '',
                        'priority' => $inc['priority'] ?? '3',
                        'status' => $inc['status'] ?? 'unknown',
                        'units' => $inc['units_assigned'] ?? '',
                        'time' => $inc['received_at'] ?? '',
                        'lat' => $inc['latitude'] ?? '',
                        'lng' => $inc['longitude'] ?? '',
                    ]), ENT_QUOTES);
                ?>
                    <tr class="incident-row incident-clickable" data-incident="<?= $incJson ?>" data-priority="<?= htmlspecialchars($inc['priority'] ?? '3') ?>" onclick="openIncidentDetail(this)" style="cursor:pointer;">
                        <td><?php $p = $inc['priority'] ?? '3'; ?><span class="badge <?= $p == '1' ? 'badge-red' : ($p == '2' ? 'badge-orange' : 'badge-gray') ?>">P<?= htmlspecialchars($p) ?></span></td>
                        <td><strong><?= htmlspecialchars($inc['incident_type'] ?? 'Unknown') ?></strong></td>
                        <td><?= htmlspecialchars($inc['address'] ?? '') ?></td>
                        <td><?php foreach (array_filter(explode(',', $inc['units_assigned'] ?? '')) as $u): ?><span class="unit-badge"><?= htmlspecialchars(trim($u)) ?></span><?php endforeach; ?></td>
                        <td><?php $s = $inc['status'] ?? 'unknown'; ?><span class="badge <?= $s === 'active' ? 'badge-red' : 'badge-gray' ?>"><?= ucfirst($s) ?></span></td>
                        <td style="white-space:nowrap; font-size:13px; color:var(--ios-secondary);"><?= date('g:i A', strtotime($inc['received_at'])) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const navy = '#0B2240';
    const blue = '#1B6CB0';
    const teal = '#00A6A0';
    const green = '#8CC63F';
    const blueLight = '#5BA4D9';

    // ─── Satellite Map ──────────────────────────────────
    const mapEl = document.getElementById('incidentsMap');
    if (mapEl && window.CFD_PORTAL.mapsKey) {
        const script = document.createElement('script');
        script.src = `https://maps.googleapis.com/maps/api/js?key=${window.CFD_PORTAL.mapsKey}&callback=initIncMap`;
        script.async = true;
        document.head.appendChild(script);
    }

    window.initIncMap = function() {
        const map = new google.maps.Map(mapEl, {
            center: { lat: 39.1031, lng: -84.5120 },
            zoom: 12,
            mapTypeId: 'hybrid',
            styles: [
                { featureType: 'poi', stylers: [{ visibility: 'off' }] },
                { featureType: 'transit', stylers: [{ visibility: 'off' }] }
            ],
            mapTypeControl: true,
            mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, position: google.maps.ControlPosition.TOP_RIGHT }
        });

        // Load KMZ layers — CFD Districts & Stations
        const baseUrl = window.location.origin;
        window._kmlLayers = {};

        window._kmlLayers.districts = new google.maps.KmlLayer({
            url: baseUrl + '/assets/data/CFD_Districts.kmz',
            map: map,
            preserveViewport: true,
            suppressInfoWindows: false
        });

        window._kmlLayers.stations = new google.maps.KmlLayer({
            url: baseUrl + '/assets/data/CFD_Stations.kmz',
            map: map,
            preserveViewport: true,
            suppressInfoWindows: false
        });

        window.toggleLayer = function(name, btn) {
            const layer = window._kmlLayers[name];
            if (!layer) return;
            if (btn.classList.contains('active')) {
                layer.setMap(null);
                btn.classList.remove('active');
            } else {
                layer.setMap(map);
                btn.classList.add('active');
            }
        };

        // Incident markers on top of layers
        document.querySelectorAll('.incident-row').forEach(row => {
            const lat = parseFloat(row.dataset.lat);
            const lng = parseFloat(row.dataset.lng);
            if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) return;
            const p = row.dataset.priority;
            const color = p === '1' ? '#FF3B30' : (p === '2' ? '#FF9500' : '#8CC63F');
            const typeText = row.querySelector('td:nth-child(2) strong')?.textContent || '';
            const addrText = row.querySelector('td:nth-child(3)')?.textContent || '';

            const marker = new google.maps.Marker({
                position: { lat, lng },
                map: map,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 12,
                    fillColor: color,
                    fillOpacity: 0.85,
                    strokeWeight: 3,
                    strokeColor: '#fff'
                },
                title: typeText
            });

            const infoWindow = new google.maps.InfoWindow({
                content: `<div style="font-family:-apple-system,system-ui,sans-serif;padding:4px;">
                    <strong style="font-size:14px;color:${navy};">${typeText}</strong><br>
                    <span style="font-size:12px;color:#666;">${addrText}</span>
                </div>`
            });
            marker.addListener('click', () => infoWindow.open(map, marker));
        });
    };

    // ─── ECharts: Today vs Yesterday by Hour ──────────────
    const todayData = <?= json_encode(array_values($byHourToday)) ?>;
    const yesterdayData = <?= json_encode(array_values($byHourYesterday)) ?>;
    const currentHour = new Date().getHours();
    const hourLabels = Array.from({length:24}, (_,i) => i === 0 ? '12a' : i < 12 ? i+'a' : i === 12 ? '12p' : (i-12)+'p');
    const hourChart = echarts.init(document.getElementById('chartByHour'));
    hourChart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['Today', 'Yesterday'], right: 16, top: 0, textStyle: { color: '#5A6A7E', fontSize: 11 } },
        grid: { left: 40, right: 16, top: 28, bottom: 30 },
        xAxis: {
            type: 'category',
            data: hourLabels,
            axisLine: { lineStyle: { color: '#D8DEE6' } },
            axisLabel: { color: '#5A6A7E', fontSize: 10 }
        },
        yAxis: {
            type: 'value',
            axisLine: { show: false },
            splitLine: { lineStyle: { color: '#F0F2F5' } },
            axisLabel: { color: '#5A6A7E', fontSize: 10 }
        },
        series: [{
            name: 'Today',
            type: 'bar',
            data: todayData.map((v, i) => ({
                value: v,
                itemStyle: {
                    color: i === currentHour
                        ? new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'#DC2626'},{offset:1,color:'#FF6B6B'}])
                        : i < currentHour
                            ? new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:blue},{offset:1,color:teal}])
                            : '#E8ECF0',
                    borderRadius: [4, 4, 0, 0]
                }
            })),
            barWidth: '40%',
            animationDuration: 1500,
            animationEasing: 'elasticOut',
        }, {
            name: 'Yesterday',
            type: 'line',
            data: yesterdayData,
            smooth: 0.3,
            symbol: 'circle',
            symbolSize: 4,
            lineStyle: { color: '#9CA3AF', width: 2, type: 'dashed' },
            itemStyle: { color: '#9CA3AF' },
            areaStyle: { color: new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'rgba(156,163,175,0.1)'},{offset:1,color:'transparent'}]) },
            animationDuration: 2000,
        }]
    });

    // ─── ECharts: Unit Activity Radar ──────────────────
    const unitNames = <?= json_encode(array_keys($topUnitsForChart)) ?>;
    const unitVals = <?= json_encode(array_values($topUnitsForChart)) ?>;
    const maxUnit = Math.max(...unitVals, 1);
    const radarChart = echarts.init(document.getElementById('chartUnitRadar'));
    radarChart.setOption({
        tooltip: { trigger: 'item' },
        radar: {
            indicator: unitNames.map(n => ({ name: n, max: maxUnit * 1.2 })),
            shape: 'polygon',
            splitNumber: 4,
            axisName: { color: '#0B2240', fontSize: 11, fontWeight: 600 },
            splitLine: { lineStyle: { color: '#E8ECF0' } },
            splitArea: { areaStyle: { color: ['rgba(27,108,176,0.02)', 'rgba(27,108,176,0.04)'] } },
            axisLine: { lineStyle: { color: '#D8DEE6' } },
        },
        series: [{
            type: 'radar',
            data: [{
                value: unitVals,
                name: 'Runs (24h)',
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { color: blue, width: 2 },
                areaStyle: { color: new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'rgba(27,108,176,0.35)'},{offset:1,color:'rgba(0,166,160,0.1)'}]) },
                itemStyle: { color: blue, borderColor: '#fff', borderWidth: 2 },
                label: { show: true, formatter: '{c}', color: '#0B2240', fontSize: 10, fontWeight: 700 },
            }],
            animationDuration: 2000,
            animationEasing: 'elasticOut',
        }]
    });

    // ─── ECharts: Top Call Types (animated bars) ─────────
    const typeLabels = <?= json_encode(array_keys($topTypes)) ?>;
    const typeValues = <?= json_encode(array_values($topTypes)) ?>;
    const typeColors = typeLabels.map(t => {
        const tl = t.toLowerCase();
        if (tl.includes('struct')) return '#DC2626';
        if (tl.includes('falarm') || tl.includes('calarm')) return '#FCD34D';
        if (tl.includes('acci')) return '#FF9800';
        if (tl.includes('sick') || tl.includes('breath') || tl.includes('faint') || tl.includes('fall')) return '#5BA4D9';
        if (tl.includes('arrest')) return '#DC2626';
        return '#00A6A0';
    });
    const typeChart = echarts.init(document.getElementById('chartByType'));
    typeChart.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: { left: 16, right: 40, top: 8, bottom: 8, containLabel: true },
        xAxis: { type: 'value', axisLine: { show: false }, splitLine: { lineStyle: { color: '#F0F2F5' } }, axisLabel: { color: '#5A6A7E', fontSize: 10 } },
        yAxis: { type: 'category', data: typeLabels.reverse(), axisLine: { lineStyle: { color: '#D8DEE6' } }, axisLabel: { color: '#0B2240', fontSize: 11, width: 140, overflow: 'truncate' } },
        series: [{
            type: 'bar',
            data: typeValues.reverse().map((v, i) => ({
                value: v,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0,0,1,0,[
                        {offset:0, color: typeColors[typeColors.length-1-i] + '60'},
                        {offset:1, color: typeColors[typeColors.length-1-i]}
                    ]),
                    borderRadius: [0, 6, 6, 0]
                }
            })),
            barWidth: '55%',
            label: { show: true, position: 'right', color: '#5A6A7E', fontSize: 11, fontWeight: 600 },
            animationDuration: 1500,
            animationDelay: function(idx) { return idx * 100; },
            animationEasing: 'elasticOut',
        }]
    });

    // ─── ECharts: Activity Heatmap ──────────────────────
    const heatmapData = <?= json_encode($heatmapData) ?>;
    const hmChart = echarts.init(document.getElementById('chartHeatmap'));
    hmChart.setOption({
        tooltip: {
            position: 'top',
            formatter: function(p) {
                const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
                const h = p.data[0];
                const time = h === 0 ? '12a' : h < 12 ? h+'a' : h === 12 ? '12p' : (h-12)+'p';
                return `${days[p.data[1]]} ${time}: <strong>${p.data[2]}</strong> incidents`;
            }
        },
        grid: { left: 48, right: 16, top: 8, bottom: 36 },
        xAxis: {
            type: 'category',
            data: Array.from({length:24}, (_,i) => i === 0 ? '12a' : i < 12 ? i+'a' : i === 12 ? '12p' : (i-12)+'p'),
            splitArea: { show: true },
            axisLabel: { color: '#5A6A7E', fontSize: 9 }
        },
        yAxis: {
            type: 'category',
            data: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
            splitArea: { show: true },
            axisLabel: { color: '#5A6A7E', fontSize: 10 }
        },
        visualMap: {
            min: 0,
            max: Math.max(...heatmapData.map(d => d[2]), 1),
            calculable: false,
            orient: 'horizontal',
            left: 'center',
            bottom: 0,
            inRange: {
                color: ['#E8EDF3', blueLight, blue, navy]
            },
            textStyle: { color: '#5A6A7E', fontSize: 10 },
            itemWidth: 12,
            itemHeight: 80
        },
        series: [{
            type: 'heatmap',
            data: heatmapData,
            label: { show: false },
            emphasis: {
                itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.3)' }
            },
            itemStyle: { borderRadius: 3 }
        }]
    });

    // Responsive resize
    window.addEventListener('resize', () => {
        hourChart.resize();
        prioChart.resize();
        typeChart.resize();
        hmChart.resize();
    });

    // Filter table
    window.filterIncidents = function(priority, btn) {
        btn.parentElement.querySelectorAll('.seg-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.incident-row').forEach(row => {
            row.style.display = (priority === 'all' || row.dataset.priority === priority) ? '' : 'none';
        });
    };

    // Auto-refresh stats every 30s
    setInterval(async () => {
        const data = await window.portalAPI('incidents.php?action=stats');
        if (data) {
            const el = document.getElementById('incidentLiveStatus');
            if (el) { el.textContent = data.total_24h > 0 ? 'Live' : 'Waiting'; el.className = 'badge ' + (data.total_24h > 0 ? 'badge-green' : 'badge-gray'); }
        }
    }, 30000);
});

// ─── Incident Detail Modal ────────────────────────────
let streetViewPano = null;

window.openIncidentDetail = function(row) {
    const mapsKey = window.CFD_PORTAL?.mapsKey || '<?= GOOGLE_MAPS_API_KEY ?>';
    const inc = JSON.parse(row.dataset.incident);

    document.getElementById('incDetailType').textContent = inc.type;
    document.getElementById('incDetailAddress').textContent = inc.address + (inc.city ? ', ' + inc.city : '');
    document.getElementById('incDetailId').textContent = 'ID: ' + inc.id;
    document.getElementById('incDetailStatus').textContent = inc.status;

    const prioEl = document.getElementById('incDetailPriority');
    prioEl.textContent = 'Priority ' + inc.priority;
    prioEl.className = 'badge ' + (inc.priority == '1' ? 'badge-red' : (inc.priority == '2' ? 'badge-orange' : 'badge-gray'));

    const unitsEl = document.getElementById('incDetailUnits');
    const units = (inc.units || '').split(',').filter(u => u.trim());
    unitsEl.innerHTML = units.length > 0
        ? units.map(u => `<span class="unit-badge">${u.trim()}</span>`).join('')
        : '<span style="color:var(--ios-tertiary); font-size:13px;">No units assigned</span>';

    const timeEl = document.getElementById('incDetailTime');
    if (inc.time) {
        const d = new Date(inc.time.replace(' ', 'T'));
        timeEl.textContent = d.toLocaleTimeString('en-US', {hour:'numeric', minute:'2-digit'}) + ' — ' +
            d.toLocaleDateString('en-US', {weekday:'short', month:'short', day:'numeric'});
    } else {
        timeEl.textContent = 'Unknown';
    }

    const addr = encodeURIComponent(inc.address + ', Cincinnati, OH');
    document.getElementById('incDetailMapsLink').href = 'https://www.google.com/maps/search/?api=1&query=' + addr;

    const svEl = document.getElementById('incDetailStreetView');
    const loadingEl = document.getElementById('incDetailStreetViewLoading');
    loadingEl.style.display = 'flex';
    loadingEl.textContent = 'Loading Street View...';

    openModal('incidentDetailModal');

    if (inc.lat && inc.lng && inc.lat != 0) {
        loadStreetView(parseFloat(inc.lat), parseFloat(inc.lng), svEl, loadingEl, mapsKey);
    } else {
        geocodeAndLoadStreetView(inc.address + ', Cincinnati, OH', svEl, loadingEl, mapsKey);
    }
};

function loadStreetView(lat, lng, container, loadingEl, mapsKey) {
    if (!mapsKey || !window.google || !google.maps) {
        loadingEl.textContent = 'Maps not available';
        return;
    }
    loadingEl.style.display = 'none';
    const svService = new google.maps.StreetViewService();
    svService.getPanorama({ location: { lat, lng }, radius: 100 }, function(data, status) {
        if (status === google.maps.StreetViewStatus.OK) {
            if (streetViewPano) {
                streetViewPano.setPosition(data.location.latLng);
            } else {
                streetViewPano = new google.maps.StreetViewPanorama(container, {
                    position: data.location.latLng,
                    pov: { heading: 0, pitch: 0 },
                    zoom: 1,
                    addressControl: false,
                    showRoadLabels: true,
                });
            }
        } else {
            loadingEl.style.display = 'flex';
            loadingEl.innerHTML = `<div style="text-align:center;">
                <div style="margin-bottom:8px;">Street View not available</div>
                <img src="https://maps.googleapis.com/maps/api/staticmap?center=${lat},${lng}&zoom=17&size=600x300&maptype=hybrid&markers=color:red|${lat},${lng}&key=${mapsKey}" style="width:100%;max-width:500px;border-radius:8px;">
            </div>`;
        }
    });
}

function geocodeAndLoadStreetView(address, container, loadingEl, mapsKey) {
    if (!mapsKey || !window.google || !google.maps) {
        loadingEl.textContent = 'Maps not available';
        return;
    }
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address }, function(results, status) {
        if (status === 'OK' && results[0]) {
            const loc = results[0].geometry.location;
            loadStreetView(loc.lat(), loc.lng(), container, loadingEl, mapsKey);
        } else {
            loadingEl.textContent = 'Location not found';
        }
    });
}
</script>

<!-- Incident Detail Modal -->
<div class="modal-overlay" id="incidentDetailModal">
    <div class="modal" style="max-width:720px; padding:0; overflow:hidden;">
        <div id="incDetailHeader" style="background:linear-gradient(135deg,#0B2240,#1B6CB0); padding:20px 24px; color:#fff;">
            <div style="display:flex; justify-content:space-between; align-items:flex-start;">
                <div>
                    <div style="display:flex; align-items:center; gap:8px; margin-bottom:6px;">
                        <span id="incDetailPriority" class="badge" style="font-size:12px;"></span>
                        <span id="incDetailStatus" style="font-size:11px; opacity:0.7; text-transform:uppercase; letter-spacing:0.5px;"></span>
                    </div>
                    <h2 id="incDetailType" style="font-size:20px; font-weight:800; margin-bottom:4px;"></h2>
                    <p id="incDetailAddress" style="font-size:14px; color:rgba(255,255,255,0.7);"></p>
                </div>
                <button onclick="closeModal('incidentDetailModal')" style="background:rgba(255,255,255,0.1); border:none; color:#fff; width:32px; height:32px; border-radius:50%; font-size:18px; cursor:pointer;">&times;</button>
            </div>
        </div>
        <div style="display:grid; grid-template-columns:1fr 1fr; border-bottom:1px solid var(--ios-border);">
            <div style="padding:14px 24px; border-right:1px solid var(--ios-border);">
                <div style="font-size:10px; text-transform:uppercase; letter-spacing:0.8px; color:var(--ios-tertiary); font-weight:600; margin-bottom:4px;">Units Assigned</div>
                <div id="incDetailUnits" style="display:flex; flex-wrap:wrap; gap:4px;"></div>
            </div>
            <div style="padding:14px 24px;">
                <div style="font-size:10px; text-transform:uppercase; letter-spacing:0.8px; color:var(--ios-tertiary); font-weight:600; margin-bottom:4px;">Time Received</div>
                <div id="incDetailTime" style="font-size:15px; font-weight:700; color:var(--primary);"></div>
                <div id="incDetailId" style="font-size:11px; color:var(--ios-tertiary); margin-top:2px;"></div>
            </div>
        </div>
        <div id="incDetailStreetView" style="height:300px; background:var(--primary); position:relative;">
            <div id="incDetailStreetViewLoading" style="position:absolute; inset:0; display:flex; align-items:center; justify-content:center; color:rgba(255,255,255,0.4); font-size:13px;">
                Loading Street View...
            </div>
        </div>
        <div style="padding:12px 24px; background:var(--ios-bg); display:flex; gap:8px; justify-content:flex-end;">
            <a id="incDetailMapsLink" href="#" target="_blank" class="btn btn-sm btn-secondary" style="text-decoration:none;">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-2px;"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
                Open in Google Maps
            </a>
            <button onclick="closeModal('incidentDetailModal')" class="btn btn-sm btn-primary">Close</button>
        </div>
    </div>
</div>

<style>
.incident-clickable { transition: background 0.15s; }
.incident-clickable:hover { background: var(--ios-bg) !important; }
</style>
