<?php
/**
 * ESO EMS Command Center Dashboard — Apache ECharts WebGL Edition
 * Dense, data-rich view for Fire Chief + command staff
 */
$db = getDB();

// Get latest daily summary
$today = $db->query("SELECT * FROM eso_ems_daily ORDER BY report_date DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// Get 7-day trend
$trend = $db->query("SELECT * FROM eso_ems_daily ORDER BY report_date DESC LIMIT 7")->fetchAll(PDO::FETCH_ASSOC);
$trend = array_reverse($trend);

// High-acuity incidents for latest date
$latestDate = $today['report_date'] ?? date('Y-m-d', strtotime('-1 day'));
$stmt = $db->prepare("
    SELECT * FROM eso_ems_incidents
    WHERE report_date = ?
      AND (is_cardiac_arrest = 1 OR is_stemi = 1 OR is_stroke = 1 OR is_overdose = 1 OR is_pediatric = 1)
    ORDER BY dispatched_at DESC
");
$stmt->execute([$latestDate]);
$highAcuity = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Recent cardiac arrests (last 30 days)
$arrests = $db->query("SELECT * FROM eso_cardiac_arrests ORDER BY dispatched_at DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);

// Decode JSON fields
$topImpressions = json_decode($today['top_impressions'] ?? '{}', true) ?: [];
$topNatures = json_decode($today['top_cad_natures'] ?? '{}', true) ?: [];
$hospitals = json_decode($today['hospital_transports'] ?? '{}', true) ?: [];
$hourlyVol = json_decode($today['hourly_volume'] ?? '{}', true) ?: [];
$unitCounts = json_decode($today['unit_counts'] ?? '{}', true) ?: [];

$medicTurnout = json_decode($today['medic_turnout_json'] ?? '{}', true) ?: [];
// Sort by unit name
ksort($medicTurnout);

$reportDate = $today ? date('l, F j, Y', strtotime($today['report_date'])) : 'No data';
$responseGoal = 360;

// Prepare data for JS
$trendDates = array_map(fn($d) => date('D M j', strtotime($d['report_date'])), $trend);
$trendInc = array_map(fn($d) => (int)$d['unique_incidents'], $trend);
$trendTransports = array_map(fn($d) => (int)$d['total_transports'], $trend);
$trendAvgResp = array_map(fn($d) => round(($d['avg_response_time_sec'] ?? 0) / 60, 1), $trend);
$trendPctGoal = array_map(fn($d) => round($d['pct_under_goal'] ?? 0, 1), $trend);

$impNames = array_keys(array_slice($topImpressions, 0, 8));
$impValues = array_values(array_slice($topImpressions, 0, 8));
$natNames = array_keys(array_slice($topNatures, 0, 8));
$natValues = array_values(array_slice($topNatures, 0, 8));
$hospData = [];
foreach (array_slice($hospitals, 0, 8) as $name => $ct) {
    $hospData[] = ['name' => $name, 'value' => $ct];
}

$hourlyData = [];
for ($h = 0; $h < 24; $h++) {
    $hourlyData[] = [0, $h, (int)($hourlyVol[(string)$h] ?? 0)];
}
?>

<!-- ECharts CDN -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-liquidfill@3/dist/echarts-liquidfill.min.js"></script>

<style>
.ems-cc { padding: 0; }
.ems-cc .cc-header {
    background: linear-gradient(135deg, #0B2240 0%, #163158 100%);
    color: #fff;
    padding: 16px 24px;
    border-radius: var(--ios-radius);
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.ems-cc .cc-header h1 { font-size: 20px; font-weight: 800; letter-spacing: -0.3px; }
.ems-cc .cc-header .cc-date { font-size: 13px; color: #8EAEC4; }
.ems-cc .cc-header .cc-badge {
    background: #8CC63F; color: #0B2240; font-size: 10px; font-weight: 700;
    padding: 3px 10px; border-radius: 12px; text-transform: uppercase; letter-spacing: 0.5px;
}
.cc-stats {
    display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
    gap: 10px; margin-bottom: 16px;
}
.cc-stat {
    background: var(--ios-card); border-radius: var(--ios-radius-sm);
    padding: 14px 16px; box-shadow: var(--ios-shadow); text-align: center;
    position: relative; overflow: hidden;
}
.cc-stat::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; }
.cc-stat.stat-incidents::before { background: var(--cfd-blue); }
.cc-stat.stat-transports::before { background: var(--cfd-green); }
.cc-stat.stat-arrests::before { background: #E74C3C; }
.cc-stat.stat-stemi::before { background: #E67E22; }
.cc-stat.stat-stroke::before { background: #8E44AD; }
.cc-stat.stat-od::before { background: #00BCD4; }
.cc-stat.stat-peds::before { background: #E91E63; }
.cc-stat.stat-response::before { background: var(--cfd-navy); }
.cc-stat-value { font-size: 28px; font-weight: 800; color: var(--ios-text); line-height: 1; }
.cc-stat-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.8px; color: var(--ios-tertiary); font-weight: 600; margin-top: 4px; }

.cc-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px; }
.cc-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; margin-bottom: 16px; }
.cc-panel { background: var(--ios-card); border-radius: var(--ios-radius-sm); padding: 16px; box-shadow: var(--ios-shadow); }
.cc-panel-title {
    font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px;
    color: var(--ios-tertiary); margin-bottom: 8px; padding-bottom: 6px; border-bottom: 1px solid var(--ios-border);
}
.cc-chart { width: 100%; }
.cc-back { font-size: 13px; color: var(--ios-blue); text-decoration: none; display: inline-flex; align-items: center; gap: 4px; margin-bottom: 12px; }
.cc-back:hover { text-decoration: underline; }

/* Collapsible */
.cc-collapsed { display: none; }
.cc-chevron { transform: rotate(-90deg); transition: transform 0.2s ease; }
.cc-chevron-open { transform: rotate(0deg); }

/* High acuity cards */
.cc-acuity-card { border-left: 4px solid; padding: 10px 14px; margin-bottom: 8px; border-radius: 0 var(--ios-radius-sm) var(--ios-radius-sm) 0; font-size: 12px; }
.cc-acuity-card.arrest { border-color: #E74C3C; background: #FDE8E8; }
.cc-acuity-card.stemi { border-color: #E67E22; background: #FFF3E0; }
.cc-acuity-card.stroke { border-color: #8E44AD; background: #F3E5F5; }
.cc-acuity-card.overdose { border-color: #00BCD4; background: #E0F7FA; }
.cc-acuity-card.pediatric { border-color: #E91E63; background: #FCE4EC; }
.cc-acuity-inc { font-weight: 700; color: var(--ios-text); }
.cc-acuity-meta { font-size: 11px; color: var(--ios-secondary); margin-top: 2px; }
.cc-acuity-badge { display: inline-block; font-size: 9px; font-weight: 700; padding: 1px 6px; border-radius: 8px; color: #fff; text-transform: uppercase; }

@media (max-width: 768px) {
    .cc-stats { grid-template-columns: repeat(2, 1fr); }
    .cc-grid, .cc-grid-3 { grid-template-columns: 1fr; }
}
</style>

<div class="ems-cc">
    <a href="dashboard.php?page=eso" class="cc-back">&larr; ESO Overview</a>

    <div class="cc-header">
        <div>
            <h1>EMS Command Center</h1>
            <div class="cc-date"><?= $reportDate ?></div>
        </div>
        <span class="cc-badge">Live Data</span>
    </div>

    <!-- Stat Strip with animated count-up -->
    <div class="cc-stats">
        <div class="cc-stat stat-incidents">
            <div class="cc-stat-value" data-countup="<?= $today['unique_incidents'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Incidents</div>
        </div>
        <div class="cc-stat stat-transports">
            <div class="cc-stat-value" data-countup="<?= $today['total_transports'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Transports</div>
        </div>
        <div class="cc-stat stat-arrests">
            <div class="cc-stat-value" data-countup="<?= $today['cardiac_arrests'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Arrests</div>
        </div>
        <div class="cc-stat stat-stemi">
            <div class="cc-stat-value" data-countup="<?= $today['stemis'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">STEMI</div>
        </div>
        <div class="cc-stat stat-stroke">
            <div class="cc-stat-value" data-countup="<?= $today['strokes'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Stroke</div>
        </div>
        <div class="cc-stat stat-od">
            <div class="cc-stat-value" data-countup="<?= $today['overdoses'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Overdose</div>
        </div>
        <div class="cc-stat stat-peds">
            <div class="cc-stat-value" data-countup="<?= $today['pediatric_calls'] ?? 0 ?>">0</div>
            <div class="cc-stat-label">Pediatric</div>
        </div>
        <div class="cc-stat stat-response">
            <?php $avgMin = round(($today['avg_response_time_sec'] ?? 0) / 60, 1); ?>
            <div class="cc-stat-value" style="color: <?= $avgMin <= 6 ? '#8CC63F' : ($avgMin <= 8 ? '#FF9500' : '#E74C3C') ?>" data-countup="<?= $avgMin ?>" data-decimal="1">0</div>
            <div class="cc-stat-label">Avg Resp (min)</div>
        </div>
    </div>

    <!-- Row 1: Trend + Gauge + Liquid Fill -->
    <div class="cc-grid-3">
        <div class="cc-panel">
            <div class="cc-panel-title">7-Day Incident Trend</div>
            <div id="chart-trend" class="cc-chart" style="height:220px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">Response Time</div>
            <div id="chart-gauge" class="cc-chart" style="height:220px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">Goal Compliance</div>
            <div id="chart-liquid" class="cc-chart" style="height:220px;"></div>
        </div>
    </div>

    <!-- Row 2: Heatmap full width -->
    <div class="cc-panel" style="margin-bottom:16px;">
        <div class="cc-panel-title">Call Volume by Hour</div>
        <div id="chart-heatmap" class="cc-chart" style="height:120px;"></div>
    </div>

    <!-- Row 2.5: Medic Turnout Time Gauges -->
    <?php if (!empty($medicTurnout)): ?>
    <div class="cc-panel" style="margin-bottom:16px;">
        <div class="cc-panel-title">Medic Unit Turnout Times <span style="font-weight:400;color:var(--ios-secondary);font-size:10px;text-transform:none;letter-spacing:0;">(Dispatched → En Route)</span></div>
        <div style="display:flex;gap:2px;justify-content:center;overflow-x:auto;">
            <?php $gaugeCount = count($medicTurnout); $gaugeWidth = max(60, min(90, (int)(100 / $gaugeCount * 10))); ?>
            <?php foreach ($medicTurnout as $unit => $data): ?>
                <div id="gauge-<?= htmlspecialchars($unit) ?>" style="min-width:<?= $gaugeWidth ?>px;height:100px;flex:1;"></div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Row 3: Impressions + CAD Natures + Hospital Treemap -->
    <div class="cc-grid-3">
        <div class="cc-panel">
            <div class="cc-panel-title">Top Primary Impressions</div>
            <div id="chart-impressions" class="cc-chart" style="height:280px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">Top CAD Natures</div>
            <div id="chart-natures" class="cc-chart" style="height:280px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">Hospital Transports</div>
            <div id="chart-hospitals" class="cc-chart" style="height:280px;"></div>
        </div>
    </div>

    <!-- Row 4: Response Time Trend + Transport Trend -->
    <div class="cc-grid">
        <div class="cc-panel">
            <div class="cc-panel-title">7-Day Response Time &amp; Goal Trend</div>
            <div id="chart-resp-trend" class="cc-chart" style="height:200px;"></div>
        </div>
        <div class="cc-panel">
            <div class="cc-panel-title">7-Day Transport Volume</div>
            <div id="chart-transport-trend" class="cc-chart" style="height:200px;"></div>
        </div>
    </div>

    <!-- Row 5: High-Acuity Calls (collapsed) -->
    <?php if (!empty($highAcuity)): ?>
    <div class="cc-panel" style="margin-bottom:16px;">
        <div class="cc-panel-title" style="cursor:pointer;display:flex;justify-content:space-between;align-items:center;user-select:none;" onclick="document.getElementById('acuityBody').classList.toggle('cc-collapsed');this.querySelector('.cc-chevron').classList.toggle('cc-chevron-open');">
            <span>High-Acuity Calls &mdash; <?= date('M j', strtotime($latestDate)) ?> <span style="font-weight:400;color:var(--ios-secondary);font-size:10px;text-transform:none;letter-spacing:0;">(<?= count($highAcuity) ?> calls)</span></span>
            <span class="cc-chevron" style="display:inline-block;font-size:14px;color:var(--ios-tertiary);">&#9660;</span>
        </div>
        <div id="acuityBody" class="cc-collapsed">
        <?php foreach ($highAcuity as $inc):
            $type = 'standard'; $badge = '';
            if ($inc['is_cardiac_arrest']) { $type = 'arrest'; $badge = 'Cardiac Arrest'; }
            elseif ($inc['is_stemi']) { $type = 'stemi'; $badge = 'STEMI'; }
            elseif ($inc['is_stroke']) { $type = 'stroke'; $badge = 'Stroke'; }
            elseif ($inc['is_overdose']) { $type = 'overdose'; $badge = 'Overdose'; }
            elseif ($inc['is_pediatric']) { $type = 'pediatric'; $badge = 'Pediatric'; }
            $bgColors = ['arrest'=>'#E74C3C','stemi'=>'#E67E22','stroke'=>'#8E44AD','overdose'=>'#00BCD4','pediatric'=>'#E91E63'];
        ?>
            <div class="cc-acuity-card <?= $type ?>">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <span class="cc-acuity-inc"><?= htmlspecialchars($inc['incident_number']) ?></span>
                    <span class="cc-acuity-badge" style="background:<?= $bgColors[$type] ?? '#888' ?>"><?= $badge ?></span>
                </div>
                <div class="cc-acuity-meta">
                    <?= htmlspecialchars($inc['unit'] ?? '') ?>
                    &bull; <?= $inc['dispatched_at'] ? date('g:i A', strtotime($inc['dispatched_at'])) : '' ?>
                    &bull; <?= htmlspecialchars($inc['primary_impression'] ?? '') ?>
                    <?php if ($inc['destination']): ?>&bull; &rarr; <?= htmlspecialchars($inc['destination']) ?><?php endif; ?>
                    <?php if ($inc['patient_age']): ?>&bull; <?= $inc['patient_age'] ?>yo<?php endif; ?>
                </div>
                <?php if ($inc['narrative']): ?>
                    <div style="margin-top:6px;font-size:11px;color:var(--ios-secondary);line-height:1.4;">
                        <?= htmlspecialchars(mb_substr($inc['narrative'], 0, 200)) ?><?= mb_strlen($inc['narrative']) > 200 ? '...' : '' ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <div style="text-align:center;padding:12px;font-size:10px;color:var(--ios-tertiary);">
        Data Source: ESO ePCR / Snowflake &bull; Updated daily at 5:30 AM &bull; Powered by Apache ECharts &bull; Cincinnati Fire Department
    </div>
</div>

<script>
// ── Data from PHP ────────────────────────────────────────────
const trendDates = <?= json_encode($trendDates) ?>;
const trendInc = <?= json_encode($trendInc) ?>;
const trendTransports = <?= json_encode($trendTransports) ?>;
const trendAvgResp = <?= json_encode($trendAvgResp) ?>;
const trendPctGoal = <?= json_encode($trendPctGoal) ?>;
const impNames = <?= json_encode(array_reverse($impNames)) ?>;
const impValues = <?= json_encode(array_reverse($impValues)) ?>;
const natNames = <?= json_encode(array_reverse($natNames)) ?>;
const natValues = <?= json_encode(array_reverse($natValues)) ?>;
const hospData = <?= json_encode($hospData) ?>;
const hourlyData = <?= json_encode($hourlyData) ?>;
const avgResp = <?= round(($today['avg_response_time_sec'] ?? 0) / 60, 1) ?>;
const medianResp = <?= round(($today['median_response_time_sec'] ?? 0) / 60, 1) ?>;
const pctUnderGoal = <?= round($today['pct_under_goal'] ?? 0, 1) ?>;

// ── Animated count-up ────────────────────────────────────────
document.querySelectorAll('[data-countup]').forEach(el => {
    const target = parseFloat(el.dataset.countup);
    const decimal = parseInt(el.dataset.decimal || '0');
    const duration = 1200;
    const start = performance.now();
    const tick = (now) => {
        const progress = Math.min((now - start) / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 3); // ease-out cubic
        el.textContent = (target * eased).toFixed(decimal);
        if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
});

// ── Chart helper ─────────────────────────────────────────────
function initChart(id) {
    const dom = document.getElementById(id);
    if (!dom) return null;
    const chart = echarts.init(dom, null, { renderer: 'canvas' });
    window.addEventListener('resize', () => chart.resize());
    return chart;
}

// ── 1. 7-Day Incident Trend (area chart) ─────────────────────
const trendChart = initChart('chart-trend');
if (trendChart) trendChart.setOption({
    tooltip: { trigger: 'axis', backgroundColor: '#0B2240', borderColor: '#1B6CB0', textStyle: { color: '#fff', fontSize: 12 } },
    grid: { top: 10, right: 10, bottom: 24, left: 40 },
    xAxis: { type: 'category', data: trendDates, axisLine: { lineStyle: { color: '#D8DEE6' } }, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    yAxis: { type: 'value', splitLine: { lineStyle: { color: '#E8EDF3' } }, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    series: [{
        data: trendInc, type: 'line', smooth: true, symbol: 'circle', symbolSize: 8,
        lineStyle: { width: 3, color: '#1B6CB0' },
        itemStyle: { color: '#1B6CB0', borderWidth: 2, borderColor: '#fff' },
        areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(27,108,176,0.4)' },
            { offset: 1, color: 'rgba(27,108,176,0.02)' }
        ])},
        animationDuration: 1500, animationEasing: 'cubicOut'
    }]
});

// ── 2. Response Time Gauge ───────────────────────────────────
const gaugeChart = initChart('chart-gauge');
if (gaugeChart) gaugeChart.setOption({
    series: [{
        type: 'gauge',
        startAngle: 200, endAngle: -20,
        min: 0, max: 12,
        splitNumber: 6,
        center: ['50%', '60%'],
        radius: '90%',
        axisLine: {
            lineStyle: {
                width: 20,
                color: [[0.33, '#8CC63F'], [0.5, '#FFCC00'], [0.67, '#FF9500'], [1, '#E74C3C']]
            }
        },
        pointer: { length: '60%', width: 6, itemStyle: { color: '#0B2240' } },
        axisTick: { distance: -20, length: 6, lineStyle: { color: '#fff', width: 2 } },
        splitLine: { distance: -24, length: 14, lineStyle: { color: '#fff', width: 3 } },
        axisLabel: { color: '#8E99A8', distance: 30, fontSize: 10, formatter: v => v + 'm' },
        detail: {
            valueAnimation: true, fontSize: 28, fontWeight: 800, offsetCenter: [0, '20%'],
            formatter: v => v.toFixed(1) + ' min',
            color: avgResp <= 6 ? '#8CC63F' : (avgResp <= 8 ? '#FF9500' : '#E74C3C')
        },
        title: { offsetCenter: [0, '45%'], fontSize: 11, color: '#8E99A8' },
        data: [{ value: avgResp, name: 'Median: ' + medianResp + ' min' }],
        animationDuration: 2000, animationEasing: 'elasticOut'
    }]
});

// ── 3. Goal Compliance Liquid Fill ───────────────────────────
const liquidChart = initChart('chart-liquid');
const liquidColor = pctUnderGoal >= 80 ? '#8CC63F' : (pctUnderGoal >= 60 ? '#FF9500' : '#E74C3C');
if (liquidChart) liquidChart.setOption({
    series: [{
        type: 'liquidFill',
        data: [pctUnderGoal / 100, (pctUnderGoal / 100) - 0.05, (pctUnderGoal / 100) - 0.1],
        radius: '80%',
        color: [liquidColor, echarts.color.lift(liquidColor, 0.2), echarts.color.lift(liquidColor, 0.4)],
        backgroundStyle: { color: 'rgba(0,0,0,0.05)' },
        outline: { borderDistance: 4, itemStyle: { borderWidth: 3, borderColor: liquidColor } },
        label: {
            formatter: function() { return pctUnderGoal + '%\nunder 6 min'; },
            fontSize: 22, fontWeight: 800, color: liquidColor,
            insideColor: '#fff'
        },
        animationDuration: 2000
    }]
});

// ── 4. Hourly Volume (bar chart with color intensity) ────────
const heatmapChart = initChart('chart-heatmap');
const hourLabels = Array.from({length: 24}, (_, i) => {
    if (i === 0) return '12a';
    if (i === 12) return '12p';
    return (i % 12) + (i < 12 ? 'a' : 'p');
});
const hourValues = Array.from({length: 24}, (_, i) => hourlyData.find(d => d[1] === i)?.[2] || 0);
const maxHourVal = Math.max(...hourValues, 1);
if (heatmapChart) heatmapChart.setOption({
    tooltip: {
        trigger: 'axis',
        formatter: function(params) {
            const h = params[0].dataIndex;
            const ampm = h < 12 ? 'AM' : 'PM';
            const hour12 = h === 0 ? 12 : (h > 12 ? h - 12 : h);
            return '<strong>' + hour12 + ':00 ' + ampm + '</strong><br>' + params[0].value + ' incidents';
        },
        backgroundColor: '#0B2240', borderColor: '#1B6CB0', textStyle: { color: '#fff' }
    },
    grid: { top: 8, right: 8, bottom: 20, left: 30 },
    xAxis: { type: 'category', data: hourLabels, axisLabel: { color: '#8E99A8', fontSize: 9 }, axisLine: { lineStyle: { color: '#E8EDF3' } } },
    yAxis: { type: 'value', axisLabel: { color: '#8E99A8', fontSize: 9 }, splitLine: { lineStyle: { color: '#F0F2F5' } } },
    series: [{
        type: 'bar', data: hourValues.map((v, i) => ({
            value: v,
            itemStyle: {
                borderRadius: [4, 4, 0, 0],
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                    { offset: 0, color: 'rgba(27,108,176,0.3)' },
                    { offset: 1, color: 'rgba(27,108,176,' + (0.3 + 0.7 * (v / maxHourVal)) + ')' }
                ])
            }
        })),
        barWidth: '70%',
        emphasis: { itemStyle: { shadowBlur: 8, shadowColor: 'rgba(27,108,176,0.4)' } },
        animationDelay: idx => idx * 40
    }]
});

// ── 5. Top Impressions (horizontal bar) ──────────────────────
const impChart = initChart('chart-impressions');
if (impChart) impChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, backgroundColor: '#0B2240', textStyle: { color: '#fff' } },
    grid: { top: 4, right: 40, bottom: 4, left: 10, containLabel: true },
    xAxis: { type: 'value', show: false },
    yAxis: { type: 'category', data: impNames, axisLabel: { color: '#5A6A7E', fontSize: 10, width: 140, overflow: 'truncate' }, axisLine: { show: false }, axisTick: { show: false } },
    series: [{
        type: 'bar', data: impValues, barWidth: 16, itemStyle: {
            borderRadius: [0, 8, 8, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: '#1B6CB0' }, { offset: 1, color: '#5BA4D9' }])
        },
        label: { show: true, position: 'right', color: '#0B2240', fontWeight: 700, fontSize: 11 },
        animationDelay: idx => idx * 80
    }]
});

// ── 6. Top CAD Natures (horizontal bar) ──────────────────────
const natChart = initChart('chart-natures');
if (natChart) natChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, backgroundColor: '#0B2240', textStyle: { color: '#fff' } },
    grid: { top: 4, right: 40, bottom: 4, left: 10, containLabel: true },
    xAxis: { type: 'value', show: false },
    yAxis: { type: 'category', data: natNames, axisLabel: { color: '#5A6A7E', fontSize: 10, width: 140, overflow: 'truncate' }, axisLine: { show: false }, axisTick: { show: false } },
    series: [{
        type: 'bar', data: natValues, barWidth: 16, itemStyle: {
            borderRadius: [0, 8, 8, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: '#6BA030' }, { offset: 1, color: '#8CC63F' }])
        },
        label: { show: true, position: 'right', color: '#0B2240', fontWeight: 700, fontSize: 11 },
        animationDelay: idx => idx * 80
    }]
});

// ── 7. Hospital Transport Treemap ────────────────────────────
const hospChart = initChart('chart-hospitals');
if (hospChart) hospChart.setOption({
    tooltip: { formatter: p => '<strong>' + p.name + '</strong><br>' + p.value + ' transports', backgroundColor: '#0B2240', textStyle: { color: '#fff' } },
    series: [{
        type: 'treemap', data: hospData, roam: false,
        breadcrumb: { show: false },
        itemStyle: { borderRadius: 6, borderWidth: 3, borderColor: '#fff', gapWidth: 2 },
        levels: [{ colorSaturation: [0.4, 0.8], itemStyle: { borderColor: '#fff', borderWidth: 3, gapWidth: 3 } }],
        label: { show: true, formatter: '{b}\n{c}', fontSize: 11, fontWeight: 600, color: '#fff', lineHeight: 16 },
        upperLabel: { show: false },
        color: ['#1B6CB0', '#E67E22', '#8CC63F', '#E74C3C', '#8E44AD', '#00BCD4', '#FFCC00', '#E91E63'],
        animationDuration: 1500
    }]
});

// ── 8. Response Time + Goal Trend (dual axis) ────────────────
const respTrendChart = initChart('chart-resp-trend');
if (respTrendChart) respTrendChart.setOption({
    tooltip: { trigger: 'axis', backgroundColor: '#0B2240', textStyle: { color: '#fff' } },
    legend: { data: ['Avg Response', '% Under Goal'], textStyle: { color: '#8E99A8', fontSize: 10 }, top: 0 },
    grid: { top: 30, right: 50, bottom: 24, left: 50 },
    xAxis: { type: 'category', data: trendDates, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    yAxis: [
        { type: 'value', name: 'Minutes', nameTextStyle: { color: '#8E99A8', fontSize: 9 }, axisLabel: { color: '#8E99A8', fontSize: 10, formatter: '{value}m' }, splitLine: { lineStyle: { color: '#E8EDF3' } } },
        { type: 'value', name: '% Goal', nameTextStyle: { color: '#8E99A8', fontSize: 9 }, axisLabel: { color: '#8E99A8', fontSize: 10, formatter: '{value}%' }, splitLine: { show: false }, min: 0, max: 100 }
    ],
    series: [
        { name: 'Avg Response', type: 'line', data: trendAvgResp, smooth: true, symbol: 'circle', symbolSize: 6, lineStyle: { width: 3, color: '#E67E22' }, itemStyle: { color: '#E67E22' }, animationDuration: 1500 },
        { name: '% Under Goal', type: 'line', yAxisIndex: 1, data: trendPctGoal, smooth: true, symbol: 'diamond', symbolSize: 6, lineStyle: { width: 2, color: '#8CC63F', type: 'dashed' }, itemStyle: { color: '#8CC63F' },
            areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: 'rgba(140,198,63,0.2)' }, { offset: 1, color: 'rgba(140,198,63,0)' }]) },
            animationDuration: 1500
        }
    ]
});

// ── 9. Transport Trend (bar) ─────────────────────────────────
const transTrendChart = initChart('chart-transport-trend');
if (transTrendChart) transTrendChart.setOption({
    tooltip: { trigger: 'axis', backgroundColor: '#0B2240', textStyle: { color: '#fff' } },
    grid: { top: 10, right: 10, bottom: 24, left: 40 },
    xAxis: { type: 'category', data: trendDates, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    yAxis: { type: 'value', splitLine: { lineStyle: { color: '#E8EDF3' } }, axisLabel: { color: '#8E99A8', fontSize: 10 } },
    series: [{
        type: 'bar', data: trendTransports, barWidth: '50%',
        itemStyle: {
            borderRadius: [6, 6, 0, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#8CC63F' }, { offset: 1, color: '#6BA030' }])
        },
        emphasis: { itemStyle: { color: '#A5D75E' } },
        animationDelay: idx => idx * 150
    }]
});

// ── 10. Medic Turnout Liquid Fill Gauges ─────────────────────
const turnoutData = <?= json_encode($medicTurnout) ?>;
Object.entries(turnoutData).forEach(([unit, data], idx) => {
    const dom = document.getElementById('gauge-' + unit);
    if (!dom) return;
    const chart = echarts.init(dom);
    window.addEventListener('resize', () => chart.resize());

    const avgSec = data.avg;
    const fillLevel = Math.min(avgSec / 180, 1);

    const color = avgSec <= 60 ? '#8CC63F' : (avgSec <= 90 ? '#FF9500' : '#E74C3C');
    const colorLight = avgSec <= 60 ? '#A5D75E' : (avgSec <= 90 ? '#FFB84D' : '#FF6B6B');
    const colorDark = avgSec <= 60 ? '#6BA030' : (avgSec <= 90 ? '#CC7A00' : '#C0392B');

    chart.setOption({
        series: [{
            type: 'liquidFill',
            data: [fillLevel, fillLevel - 0.04, fillLevel - 0.08],
            radius: '82%',
            color: [color, colorLight, colorDark],
            backgroundStyle: { color: 'rgba(0,0,0,0.03)', borderColor: '#E8EDF3', borderWidth: 1 },
            outline: {
                borderDistance: 2,
                itemStyle: { borderWidth: 2, borderColor: color, shadowBlur: 5, shadowColor: color + '40' }
            },
            label: {
                formatter: function() { return unit + '\n' + (avgSec / 60).toFixed(1) + 'm'; },
                fontSize: 10, fontWeight: 800, color: '#0B2240', insideColor: '#fff', lineHeight: 13
            },
            shape: 'circle',
            waveAnimation: true,
            animationDuration: 2000 + idx * 150,
            animationDurationUpdate: 1000
        }]
    });
});
</script>
