<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireAdmin();

$page_title = 'Location Insights';

// Calculate top and hotspot info
$top_location_name = '';
$top_location_count = 0;
$top_hotspot_name = '';
$top_hotspot_lost = 0;
if (!empty($combined)) {
    $top_data = array_values($combined)[0];
    $top_location_name = array_key_first($combined);
    $top_location_count = $top_data['total'];
    $top_hotspot_name = !empty($ll) ? $ll[0] : '';
    $top_hotspot_lost = !empty($ld) ? $ld[0] : 0;
}

// All locations with both lost and found counts
$lost_locs  = $conn->query("SELECT location, COUNT(*) c FROM lost_items  WHERE location!='' GROUP BY location ORDER BY c DESC");
$found_locs = $conn->query("SELECT location, COUNT(*) c FROM found_items WHERE location!='' GROUP BY location ORDER BY c DESC");

$ll=[]; $ld=[];
while($r=$lost_locs->fetch_assoc())  { $ll[]=$r['location']; $ld[]=$r['c']; }
$fl=[]; $fd=[];
while($r=$found_locs->fetch_assoc()) { $fl[]=$r['location']; $fd[]=$r['c']; }

// Combined: merge all unique locations
$all_locs = array_unique(array_merge($ll, $fl));
$combined = [];
foreach($all_locs as $loc) {
    $li = array_search($loc, $ll);
    $fi = array_search($loc, $fl);
    $combined[$loc] = [
        'lost'  => $li !== false ? $ld[$li] : 0,
        'found' => $fi !== false ? $fd[$fi] : 0,
    ];
    $combined[$loc]['total'] = $combined[$loc]['lost'] + $combined[$loc]['found'];
}
uasort($combined, fn($a,$b) => $b['total'] - $a['total']);

// Summary stats
$total_lost_reports  = array_sum($ld);
$total_found_reports = array_sum($fd);
$unique_locations    = count($all_locs);
$top_lost_loc  = !empty($ll) ? $ll[0] : 'N/A';
$top_found_loc = !empty($fl) ? $fl[0] : 'N/A';

// Top 8 for charts
$chart_locs  = array_slice($ll, 0, 8);
$chart_ld    = array_slice($ld, 0, 8);
$chart_flocs = array_slice($fl, 0, 8);
$chart_fd    = array_slice($fd, 0, 8);

// Combined top 8
$comb_top   = array_slice($combined, 0, 8, true);
$comb_labels = array_keys($comb_top);
$comb_lost   = array_column(array_values($comb_top), 'lost');
$comb_found  = array_column(array_values($comb_top), 'found');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
/* ═════════════════════════════════════════════════════════ */
/* 🎨 LOCATIONS PAGE - ENHANCED STYLES */
/* ═════════════════════════════════════════════════════════ */

/* Page content */
.page-content { padding: 24px 28px; background: var(--bg-primary); }

/* Stat row */
.loc-stat-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 18px;
    margin-bottom: 32px;
    animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.loc-stat {
    background: var(--white);
    border-radius: 14px;
    padding: 24px 20px;
    border: 1px solid var(--border);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    cursor: default;
}

.loc-stat:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    border-color: currentColor;
}

.loc-stat::before {
    content: '';
    position: absolute;
    top: 0; left: 0;
    width: 4px; height: 100%;
    border-radius: 14px 0 0 14px;
    opacity: 0.8;
}

.loc-stat::after {
    content: '';
    position: absolute;
    bottom: -30px; right: -30px;
    width: 100px; height: 100px;
    border-radius: 50%;
    opacity: 0.04;
    transition: all 0.3s ease;
}

.loc-stat:hover::after { bottom: -20px; right: -20px; opacity: 0.08; }

.loc-stat.blue::before   { background: #3b82f6; }
.loc-stat.blue::after    { background: #3b82f6; }
.loc-stat.red::before    { background: #ef4444; }
.loc-stat.red::after     { background: #ef4444; }
.loc-stat.green::before  { background: #10b981; }
.loc-stat.green::after   { background: #10b981; }
.loc-stat.yellow::before { background: #f59e0b; }
.loc-stat.yellow::after  { background: #f59e0b; }

.loc-stat-icon {
    width: 56px; height: 56px;
    border-radius: 14px;
    display: flex; align-items: center; justify-content: center;
    font-size: 28px; flex-shrink: 0;
}

.loc-stat-icon.red    { background: #fee2e2; }
.loc-stat-icon.green  { background: #d1fae5; }
.loc-stat-icon.blue   { background: #dbeafe; }
.loc-stat-icon.yellow { background: #fef3c7; }

.loc-stat-val  {
    font-size: 36px;
    font-weight: 900;
    color: var(--text);
    line-height: 1;
    letter-spacing: -1px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-variant-numeric: tabular-nums;
}

.loc-stat-lbl  {
    font-size: 11px;
    color: var(--text-muted);
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.8px;
}

.loc-stat-sub  {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 3px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 140px;
}

/* Location Insights Cards */
.loc-insights-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 28px;
    animation: fadeInUp 0.7s ease-out 0.1s both;
}

.loc-insight-card {
    background: linear-gradient(135deg, var(--white), var(--bg-secondary));
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 18px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
}

.loc-insight-card:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.06);
    transform: translateY(-3px);
}

.loc-insight-badge {
    display: inline-block;
    background: var(--primary-light);
    color: var(--primary);
    font-size: 10px;
    font-weight: 800;
    padding: 4px 10px;
    border-radius: 20px;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.loc-insight-value {
    font-size: 24px;
    font-weight: 900;
    color: var(--text);
    margin: 8px 0;
}

.loc-insight-desc {
    font-size: 11px;
    color: var(--text-muted);
    line-height: 1.4;
}

/* Chart card */
.loc-chart-card {
    background: var(--white);
    border-radius: 14px;
    border: 1px solid var(--border);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    margin-bottom: 24px;
    transition: all 0.3s ease;
    animation: fadeInUp 0.6s ease-out forwards;
}

.loc-chart-card:nth-child(1) { animation-delay: 0.15s; }
.loc-chart-card:nth-child(2) { animation-delay: 0.2s; }
.loc-chart-card:nth-child(3) { animation-delay: 0.25s; }
.loc-chart-card:nth-child(4) { animation-delay: 0.3s; }

.loc-chart-card:hover {
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    transform: translateY(-3px);
}

.loc-chart-header {
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    background: linear-gradient(135deg, var(--white) 0%, var(--bg-secondary) 100%);
}

.loc-chart-header h3 {
    font-size: 14px;
    font-weight: 800;
    color: var(--text);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.loc-chart-header .sub {
    font-size: 12px;
    color: var(--text-muted);
    margin-top: 4px;
}

.loc-chart-body { padding: 24px; }
.chart-h-lg { height: 340px; position: relative; }
.chart-h-md { height: 280px; position: relative; }

/* Two column */
.loc-2col {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
    animation: fadeInUp 0.6s ease-out 0.2s both;
}

/* Hotspot list */
.hotspot-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.hotspot-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 14px;
    background: var(--bg);
    border-radius: 10px;
    border: 1px solid var(--border);
    transition: all 0.2s ease;
}

.hotspot-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateX(4px);
    background: var(--bg-secondary);
}

.hotspot-rank {
    width: 32px; height: 32px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 12px; font-weight: 800;
    flex-shrink: 0; color: #fff;
}

.rank-1 { background: linear-gradient(135deg, #f59e0b, #fbbf24); box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3); }
.rank-2 { background: linear-gradient(135deg, #9ca3af, #d1d5db); box-shadow: 0 2px 8px rgba(156, 163, 175, 0.2); }
.rank-3 { background: linear-gradient(135deg, #b45309, #d97706); box-shadow: 0 2px 8px rgba(180, 83, 9, 0.3); }
.rank-n { background: linear-gradient(135deg, var(--primary), #84cc16); }

.hotspot-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.hotspot-name {
    font-size: 13px;
    font-weight: 700;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.hotspot-bar-wrap {
    flex: 1;
    background: var(--bg-secondary);
    border-radius: 20px;
    height: 10px;
    overflow: hidden;
    position: relative;
}

.hotspot-bar {
    height: 10px;
    border-radius: 20px;
    transition: width 1s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
}

.hotspot-bar::after {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background: linear-gradient(90deg, rgba(255,255,255,0), rgba(255,255,255,0.3));
    border-radius: 20px;
}

.hotspot-count {
    font-size: 12px;
    font-weight: 900;
    color: var(--text-muted);
    min-width: 36px;
    text-align: right;
}

/* Combined table */
.table-wrapper {
    overflow-x: auto;
}

.comb-table {
    width: 100%;
    border-collapse: collapse;
}

.comb-table th {
    background: linear-gradient(135deg, var(--bg-secondary), var(--white));
    padding: 14px 14px;
    font-size: 11px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-muted);
    border-bottom: 2px solid var(--border);
    text-align: left;
}

.comb-table td {
    padding: 14px 14px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    vertical-align: middle;
    color: var(--text);
}

.comb-table tr:last-child td { border-bottom: none; }

.comb-table tbody tr:hover td {
    background: var(--bg-secondary);
    transition: background 0.2s ease;
}

.rank-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px; height: 32px;
    border-radius: 50%;
    font-size: 11px;
    font-weight: 800;
    color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Dark mode */
body.dark-mode .loc-chart-header { background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); }
body.dark-mode .loc-insight-card { background: linear-gradient(135deg, #0f172a, #1e293b); }
body.dark-mode .hotspot-item:hover { background: #1e293b; }
body.dark-mode .comb-table th { background: linear-gradient(135deg, #1e293b, #0f172a); }
body.dark-mode .comb-table tbody tr:hover td { background: #263348; }

/* Responsive Design */
@media(max-width: 1400px) {
    .loc-stat-row { grid-template-columns: repeat(2, 1fr); }
    .loc-insights-grid { grid-template-columns: repeat(2, 1fr); }
}

@media(max-width: 1000px) {
    .loc-stat-row { grid-template-columns: repeat(2, 1fr); }
    .loc-2col { grid-template-columns: 1fr; }
    .chart-h-lg { height: 300px; }
    .chart-h-md { height: 250px; }
}

@media(max-width: 768px) {
    .loc-stat-row { grid-template-columns: 1fr; gap: 12px; }
    .loc-insights-grid { grid-template-columns: 1fr; }
    .loc-2col { grid-template-columns: 1fr; gap: 16px; }
    .chart-h-lg { height: 280px; }
    .chart-h-md { height: 240px; }
    .loc-chart-body { padding: 16px; }
    .page-content { padding: 16px; }
}

@media(max-width: 480px) {
    .loc-stat-row { grid-template-columns: 1fr; }
    .loc-stat-icon { width: 48px; height: 48px; font-size: 24px; }
    .loc-stat-val { font-size: 28px; }
    .chart-h-lg { height: 240px; }
}
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">

            <!-- ── STAT CARDS WITH ANIMATED COUNTERS ── -->
            <div class="loc-stat-row">
                <div class="loc-stat blue">
                    <div class="loc-stat-icon blue">📍</div>
                    <div>
                        <div class="loc-stat-val counter" data-target="<?= $unique_locations ?>">0</div>
                        <div class="loc-stat-lbl">Unique Locations</div>
                        <div class="loc-stat-sub">Tracked areas</div>
                    </div>
                </div>
                <div class="loc-stat red">
                    <div class="loc-stat-icon red">🔍</div>
                    <div>
                        <div class="loc-stat-val counter" data-target="<?= $total_lost_reports ?>">0</div>
                        <div class="loc-stat-lbl">Lost Reports</div>
                        <div class="loc-stat-sub" title="<?= htmlspecialchars($top_lost_loc) ?>">Top: <?= htmlspecialchars($top_lost_loc) ?></div>
                    </div>
                </div>
                <div class="loc-stat green">
                    <div class="loc-stat-icon green">📦</div>
                    <div>
                        <div class="loc-stat-val counter" data-target="<?= $total_found_reports ?>">0</div>
                        <div class="loc-stat-lbl">Found Reports</div>
                        <div class="loc-stat-sub" title="<?= htmlspecialchars($top_found_loc) ?>">Top: <?= htmlspecialchars($top_found_loc) ?></div>
                    </div>
                </div>
                <div class="loc-stat yellow">
                    <div class="loc-stat-icon yellow">🏆</div>
                    <div>
                        <div class="loc-stat-val counter" data-target="<?= !empty($combined) ? array_values($combined)[0]['total'] : 0 ?>">0</div>
                        <div class="loc-stat-lbl">Highest Activity</div>
                        <div class="loc-stat-sub" title="<?= htmlspecialchars(array_key_first($combined) ?? '') ?>"><?= htmlspecialchars(array_key_first($combined) ?? 'N/A') ?></div>
                    </div>
                </div>
            </div>

            <!-- ── LOCATION INSIGHTS ── -->
            <div class="loc-insights-grid">
                <div class="loc-insight-card">
                    <span class="loc-insight-badge" style="background: #3b82f633; color: #3b82f6;">📊 Coverage</span>
                    <div class="loc-insight-value"><?= $unique_locations ?> areas</div>
                    <div class="loc-insight-desc">Your lost and found reports span across this many unique locations</div>
                </div>

                <div class="loc-insight-card">
                    <span class="loc-insight-badge" style="background: #ef444433; color: #ef4444;">🔴 Priority Zone</span>
                    <div class="loc-insight-value"><?= htmlspecialchars(substr($top_lost_loc, 0, 20)) ?></div>
                    <div class="loc-insight-desc">Highest lost items concentration - focus recovery efforts here</div>
                </div>

                <div class="loc-insight-card">
                    <span class="loc-insight-badge" style="background: #10b98133; color: #10b981;">📍 Finder Hotspot</span>
                    <div class="loc-insight-value"><?= $total_found_reports > 0 ? round(($total_found_reports / $total_lost_reports) * 100, 1) : 0 ?>%</div>
                    <div class="loc-insight-desc">Ratio of found to lost reports - where items are being discovered</div>
                </div>
            </div>

            <!-- ── FULL WIDTH: Combined Comparison Chart ── -->
            <div class="loc-chart-card">
                <div class="loc-chart-header">
                    <div>
                        <h3>📊 Lost vs Found — Location Comparison</h3>
                        <div class="sub">Top 8 most active locations comparing lost and found reports side by side</div>
                    </div>
                </div>
                <div class="loc-chart-body">
                    <div class="chart-h-lg"><canvas id="combinedChart"></canvas></div>
                </div>
            </div>

            <!-- ── TWO COLUMNS: Individual Charts ── -->
            <div class="loc-2col">
                <div class="loc-chart-card">
                    <div class="loc-chart-header">
                        <div>
                            <h3>🔍 Lost Item Hotspots</h3>
                            <div class="sub">Where items are most frequently lost</div>
                        </div>
                        <span style="background:#fee2e2;color:#991b1b;font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px"><?= count($ll) ?> locations</span>
                    </div>
                    <div class="loc-chart-body">
                        <div class="chart-h-md" style="margin-bottom:20px"><canvas id="lostChart"></canvas></div>
                        <div class="hotspot-list">
                        <?php
                        $max_l = max(array_merge($ld,[1]));
                        $lost_slice = array_slice($ll, 0, 6);
                        foreach($lost_slice as $i => $loc):
                            $cnt = $ld[$i];
                            $rankClass = $i===0?'rank-1':($i===1?'rank-2':($i===2?'rank-3':'rank-n'));
                        ?>
                        <div class="hotspot-item">
                            <div class="hotspot-rank <?= $rankClass ?>"><?= $i+1 ?></div>
                            <div class="hotspot-info">
                                <div class="hotspot-name" title="<?= htmlspecialchars($loc) ?>"><?= htmlspecialchars($loc) ?></div>
                            </div>
                            <div class="hotspot-bar-wrap">
                                <div class="hotspot-bar" style="width:<?= round(($cnt/$max_l)*100) ?>%;background:linear-gradient(90deg,#ef4444,#f87171)"></div>
                            </div>
                            <span class="hotspot-count"><?= $cnt ?></span>
                        </div>
                        <?php endforeach; ?>
                        <?php if(empty($ll)): ?>
                        <p style="color:var(--text-muted);font-size:13px;text-align:center;padding:20px 0">No data yet.</p>
                        <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="loc-chart-card">
                    <div class="loc-chart-header">
                        <div>
                            <h3>📦 Found Item Hotspots</h3>
                            <div class="sub">Where items are most frequently found</div>
                        </div>
                        <span style="background:#d1fae5;color:#065f46;font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px"><?= count($fl) ?> locations</span>
                    </div>
                    <div class="loc-chart-body">
                        <div class="chart-h-md" style="margin-bottom:20px"><canvas id="foundChart"></canvas></div>
                        <div class="hotspot-list">
                        <?php
                        $max_f = max(array_merge($fd,[1]));
                        $found_slice = array_slice($fl, 0, 6);
                        foreach($found_slice as $i => $loc):
                            $cnt = $fd[$i];
                            $rankClass = $i===0?'rank-1':($i===1?'rank-2':($i===2?'rank-3':'rank-n'));
                        ?>
                        <div class="hotspot-item">
                            <div class="hotspot-rank <?= $rankClass ?>"><?= $i+1 ?></div>
                            <div class="hotspot-info">
                                <div class="hotspot-name" title="<?= htmlspecialchars($loc) ?>"><?= htmlspecialchars($loc) ?></div>
                            </div>
                            <div class="hotspot-bar-wrap">
                                <div class="hotspot-bar" style="width:<?= round(($cnt/$max_f)*100) ?>%;background:linear-gradient(90deg,#10b981,#34d399)"></div>
                            </div>
                            <span class="hotspot-count"><?= $cnt ?></span>
                        </div>
                        <?php endforeach; ?>
                        <?php if(empty($fl)): ?>
                        <p style="color:var(--text-muted);font-size:13px;text-align:center;padding:20px 0">No data yet.</p>
                        <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── FULL WIDTH: Combined Ranked Table ── -->
            <div class="loc-chart-card">
                <div class="loc-chart-header">
                    <div>
                        <h3>🏆 All Locations — Full Breakdown</h3>
                        <div class="sub">Complete ranking of all tracked locations by total activity</div>
                    </div>
                    <span style="background:var(--primary-light);color:var(--primary);font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px"><?= $unique_locations ?> total</span>
                </div>
                <div class="table-wrapper">
                    <table class="comb-table">
                        <thead>
                            <tr>
                                <th style="width:48px">Rank</th>
                                <th>Location</th>
                                <th>Lost</th>
                                <th>Found</th>
                                <th>Total</th>
                                <th style="min-width:160px">Activity</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                        $max_total = !empty($combined) ? array_values($combined)[0]['total'] : 1;
                        $rank = 1;
                        foreach($combined as $loc => $data):
                            $rankBg = $rank===1?'#f59e0b':($rank===2?'#9ca3af':($rank===3?'#b45309':'var(--primary)'));
                            $pct = round(($data['total']/$max_total)*100);
                        ?>
                        <tr>
                            <td>
                                <span class="rank-badge" style="background:<?= $rankBg ?>"><?= $rank ?></span>
                            </td>
                            <td><strong><?= htmlspecialchars($loc) ?></strong></td>
                            <td>
                                <span style="background:#fee2e2;color:#991b1b;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:700"><?= $data['lost'] ?></span>
                            </td>
                            <td>
                                <span style="background:#d1fae5;color:#065f46;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:700"><?= $data['found'] ?></span>
                            </td>
                            <td><strong><?= $data['total'] ?></strong></td>
                            <td>
                                <div style="display:flex;align-items:center;gap:8px">
                                    <div style="flex:1;background:#e5e7eb;border-radius:20px;height:8px;overflow:hidden">
                                        <div style="width:<?= $pct ?>%;height:8px;border-radius:20px;background:linear-gradient(90deg,var(--primary),#a8d040)"></div>
                                    </div>
                                    <span style="font-size:11px;color:var(--text-muted);min-width:32px"><?= $pct ?>%</span>
                                </div>
                            </td>
                        </tr>
                        <?php $rank++; endforeach; ?>
                        <?php if(empty($combined)): ?>
                        <tr><td colspan="6" style="text-align:center;padding:32px;color:var(--text-muted)">No location data available yet.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
<script>
// ═════════════════════════════════════════════════════════════════════
// 🎯 ANIMATED COUNTER - Numbers count up when page loads
// ═════════════════════════════════════════════════════════════════════
function animateCounters() {
    const counters = document.querySelectorAll('.counter');
    const isVisible = (el) => {
        const rect = el.getBoundingClientRect();
        return rect.top <= window.innerHeight && rect.bottom >= 0;
    };

    const animate = (counter) => {
        const target = parseInt(counter.getAttribute('data-target'));
        const increment = target / 40;
        let current = 0;

        const timer = setInterval(() => {
            current += increment;
            if (current >= target) {
                counter.textContent = target.toLocaleString();
                clearInterval(timer);
            } else {
                counter.textContent = Math.floor(current).toLocaleString();
            }
        }, 15);
    };

    counters.forEach(counter => {
        if (isVisible(counter) && !counter.classList.contains('animated')) {
            counter.classList.add('animated');
            animate(counter);
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    setTimeout(animateCounters, 300);
});

// ═════════════════════════════════════════════════════════════════════
// 📊 CHART CONFIGURATION
// ═════════════════════════════════════════════════════════════════════
const isDark    = () => document.body.classList.contains('dark-mode');
const tickColor = () => isDark() ? '#94a3b8' : '#64748b';
const gridColor = () => isDark() ? 'rgba(255,255,255,.08)' : 'rgba(0,0,0,.05)';
const borderClr = () => isDark() ? '#1e293b' : '#ffffff';

const tooltip = {
    backgroundColor: isDark() ? '#0f172a' : '#1e293b',
    titleColor: '#f1f5f9',
    bodyColor: '#cbd5e1',
    borderColor: 'rgba(255,255,255,.12)',
    borderWidth: 2,
    padding: 12,
    cornerRadius: 12,
    displayColors: true,
    boxPadding: 6,
    titleFont: { size: 12, weight: '600' },
    bodyFont: { size: 11 }
};

function baseScales() {
    return {
        x: {
            grid: { display: false },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' } },
            border: { display: false }
        },
        y: {
            beginAtZero: true,
            grid: { color: gridColor(), drawBorder: false },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' }, precision: 0 },
            border: { display: false }
        }
    };
}

function hBarScales() {
    return {
        x: {
            beginAtZero: true,
            grid: { color: gridColor() },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' }, precision: 0 },
            border: { display: false }
        },
        y: {
            grid: { display: false },
            ticks: { color: tickColor(), font: { size: 11, weight: '500' } },
            border: { display: false }
        }
    };
}

// Combined grouped bar
const combinedChart = new Chart(document.getElementById('combinedChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($comb_labels) ?>,
        datasets: [
            {
                label: 'Lost',
                data: <?= json_encode($comb_lost) ?>,
                backgroundColor: 'rgba(239,68,68,.85)',
                borderRadius: 8,
                borderSkipped: false
            },
            {
                label: 'Found',
                data: <?= json_encode($comb_found) ?>,
                backgroundColor: 'rgba(16,185,129,.85)',
                borderRadius: 8,
                borderSkipped: false
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    font: { size: 12, weight: '600' },
                    boxWidth: 14,
                    padding: 16,
                    color: tickColor(),
                    usePointStyle: true,
                    pointStyle: 'rectRounded'
                }
            },
            tooltip: { ...tooltip }
        },
        scales: baseScales()
    }
});

// Lost horizontal bar
const lostChart = new Chart(document.getElementById('lostChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($chart_locs) ?>,
        datasets: [{
            label: 'Lost Reports',
            data: <?= json_encode($chart_ld) ?>,
            backgroundColor: [
                '#ef4444', '#f97316', '#f59e0b', '#eab308',
                '#84cc16', '#22c55e', '#16a34a', '#15803d'
            ],
            borderRadius: 8,
            borderSkipped: false
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        plugins: {
            legend: { display: false },
            tooltip: { ...tooltip }
        },
        scales: hBarScales()
    }
});

// Found horizontal bar
const foundChart = new Chart(document.getElementById('foundChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($chart_flocs) ?>,
        datasets: [{
            label: 'Found Reports',
            data: <?= json_encode($chart_fd) ?>,
            backgroundColor: [
                '#10b981', '#059669', '#047857', '#065f46',
                '#3b82f6', '#2563eb', '#1d4ed8', '#1e40af'
            ],
            borderRadius: 8,
            borderSkipped: false
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        plugins: {
            legend: { display: false },
            tooltip: { ...tooltip }
        },
        scales: hBarScales()
    }
});

// Live update on dark mode toggle
const allCharts = [combinedChart, lostChart, foundChart];
const origToggle = window.toggleDarkMode;
window.toggleDarkMode = function () {
    origToggle();
    allCharts.forEach(chart => {
        if (chart.options.plugins?.legend?.labels) chart.options.plugins.legend.labels.color = tickColor();
        ['x','y'].forEach(axis => {
            if (chart.options.scales?.[axis]) {
                if (chart.options.scales[axis].ticks) chart.options.scales[axis].ticks.color = tickColor();
                if (chart.options.scales[axis].grid?.color !== undefined) chart.options.scales[axis].grid.color = gridColor();
            }
        });
        chart.update();
    });
};
</script>
</body>
</html>
