<!DOCTYPE html>
<html lang="en">
@include('index.head')
<body>
@include('index.navigation')
<style>
    .ngbvd-district-page{background:#f4f7fb;min-height:calc(100vh - 86px);padding:24px 0 34px;}
    .ngbvd-district-shell{max-width:1380px;margin:0 auto;padding:0 18px;display:grid;grid-template-columns:minmax(0,1fr) 390px;gap:18px;align-items:stretch;}
    .ngbvd-map-card,.ngbvd-map-detail{background:#fff;border:1px solid #e1e7f0;border-radius:22px;box-shadow:0 16px 38px rgba(15,31,61,.08);overflow:hidden;}
    #map{height:690px;min-height:540px;}
    .ngbvd-map-detail{padding:20px;position:sticky;top:96px;max-height:690px;overflow:auto;}
    .ngbvd-map-detail .kicker{font-size:12px;text-transform:uppercase;letter-spacing:.12em;font-weight:900;color:#ffb000;margin-bottom:8px;display:block;}
    .ngbvd-map-detail h2{font-size:24px;font-weight:900;color:#07142b;margin:0 0 4px;}
    .ngbvd-map-count{font-size:38px;font-weight:900;color:#07142b;line-height:1;margin:14px 0 4px;}
    .ngbvd-map-muted{color:#667085;margin-bottom:14px;}
    .ngbvd-district-table{width:100%;border-collapse:collapse;margin-top:14px;font-size:14px;}
    .ngbvd-district-table th{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:#667085;text-align:left;border-bottom:1px solid #e6ebf2;padding:10px 6px;}
    .ngbvd-district-table td{border-bottom:1px solid #eef2f7;padding:10px 6px;color:#152238;font-weight:700;}
    .ngbvd-district-help{background:#fff8df;border:1px solid #ffe6a3;border-radius:16px;padding:14px;color:#7a5400;font-size:14px;line-height:1.5;}
    .ngbvd-mini-bar{height:9px;border-radius:999px;background:#eef2f7;overflow:hidden;min-width:90px}.ngbvd-mini-bar span{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,#34aeea,#5547e7)}
    .rounded-badge .badge{width:44px;height:44px;border-radius:999px;display:flex;align-items:center;justify-content:center;border:3px solid #fff;box-shadow:0 10px 24px rgba(15,31,61,.2);font-size:13px;color:#07142b;cursor:pointer;}
    .rounded-badge.low .badge{background:#c7f9d4}.rounded-badge.medium .badge{background:#ffec8a}.rounded-badge.high .badge{background:#ffc4c4}
    @media(max-width: 1100px){.ngbvd-district-shell{grid-template-columns:1fr}.ngbvd-map-detail{position:relative;top:auto;max-height:none}#map{height:560px}}
</style>
<main class="ngbvd-district-page">
    <section class="ngbvd-district-shell">
        <div class="ngbvd-map-card"><div id="map"></div></div>
        <aside class="ngbvd-map-detail" id="districtDetailPanel">
            <span class="kicker">District Drill-down</span>
            <h2>Click a district number</h2>
            <p class="ngbvd-map-muted">Select any number marker on the map to view total incidents, top incident categories and gender breakdown.</p>
            <div class="ngbvd-district-help">Large red markers represent higher incident counts. The right panel updates without leaving the map.</div>
        </aside>
    </section>
</main>
@include('index.footer')
<script>
    var map = L.map('map').setView([1.3733, 32.2903], 7);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; OpenStreetMap contributors' }).addTo(map);

    function esc(value){ return String(value == null ? '' : value).replace(/[&<>"']/g, function(s){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s];}); }
    function valueOf(row, keys, fallback) { for (var i = 0; i < keys.length; i++) { if (row[keys[i]] !== undefined && row[keys[i]] !== null && row[keys[i]] !== '') { return row[keys[i]]; } } return fallback || ''; }

    function rowsTable(title, rows){
        if(!rows || !rows.length){ return '<p class="ngbvd-map-muted">No '+title.toLowerCase()+' breakdown available.</p>'; }
        var max = Math.max.apply(null, rows.map(function(r){ return Number(r.total || 0); })) || 1;
        var html = '<h5 style="font-weight:900;margin-top:18px;">'+title+'</h5><table class="ngbvd-district-table"><tbody>';
        rows.forEach(function(r){
            var pct = Math.max(3, Math.round((Number(r.total || 0) / max) * 100));
            html += '<tr><td>'+esc(r.name)+'</td><td style="width:120px"><div class="ngbvd-mini-bar"><span style="width:'+pct+'%"></span></div></td><td style="text-align:right">'+Number(r.total || 0).toLocaleString()+'</td></tr>';
        });
        return html + '</tbody></table>';
    }

    function renderDistrictDetail(row) {
        var id = valueOf(row, ['district_id','id'], '');
        var panel = document.getElementById('districtDetailPanel');
        panel.innerHTML = '<span class="kicker">Loading District Drill-down</span><h2>'+esc(valueOf(row, ['district','name'], 'Selected District'))+'</h2><p class="ngbvd-map-muted">Fetching incident categories...</p>';
        $.getJSON("{{ route('/index/mapdata') }}", { district_id: id })
            .done(function(data){
                var d = data.district || row;
                var total = Number(data.total || row.incidents || 0);
                panel.innerHTML = '<span class="kicker">District Drill-down</span>'+
                    '<h2>'+esc(d.name || row.district || 'Selected District')+'</h2>'+
                    '<div class="ngbvd-map-count">'+total.toLocaleString()+'</div>'+
                    '<p class="ngbvd-map-muted">reported incident records</p>'+
                    '<table class="ngbvd-district-table"><tbody>'+
                    '<tr><th>District</th><td>'+esc(d.name || row.district || '')+'</td></tr>'+
                    '<tr><th>Region</th><td>'+esc(d.region || row.region || 'Not specified')+'</td></tr>'+
                    '<tr><th>Total Incidents</th><td>'+total.toLocaleString()+'</td></tr>'+
                    '</tbody></table>'+
                    rowsTable('Top Incident Categories', data.categories || [])+
                    rowsTable('Gender Breakdown', data.gender || []);
            })
            .fail(function(){ panel.innerHTML = '<span class="kicker">District Drill-down</span><h2>Unable to load details</h2><div class="ngbvd-district-help">Please refresh the page and try again.</div>'; });
    }

    $.ajax({
        url: "{{ route('/index/mapdata') }}",
        dataType: 'json',
        success: function (data) {
            data.forEach(function (participantData) {
                if (participantData.latitudes && participantData.longitudes){
                    var count = Number(participantData.incidents || 0);
                    var iconClass = 'rounded-badge ' + (count < 10 ? 'low' : (count < 50 ? 'medium' : 'high'));
                    var marker = L.marker([participantData.latitudes, participantData.longitudes], {
                        icon: L.divIcon({ className: iconClass, html: '<div class="badge"><strong>' + count.toLocaleString() + '</strong></div>', iconSize: [44, 44] })
                    });
                    marker.on('click', function () { renderDistrictDetail(participantData); });
                    marker.addTo(map);
                }
            });
        },
        error: function (error) { /* security: browser console output removed */; }
    });
</script>
</body>
</html>
