<?php $__env->startSection('header', 'Sebaran Geografis Penerima Manfaat'); ?>

<?php $__env->startSection('styles'); ?>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<style>
    #map { height: 600px; width: 100%; border-radius: 0.75rem; z-index: 1; }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
            <h3 class="text-lg font-semibold text-gray-800">Peta Sebaran Real-time</h3>
            <p class="text-sm text-gray-500">Menampilkan lokasi <span id="visibleCount"><?php echo e($beneficiaries->count()); ?></span> penerima manfaat di Kabupaten Sumba Tengah</p>
        </div>
        <div class="flex items-center space-x-2">
            <select id="filterDistrict" class="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-primary focus:border-primary">
                <option value="">Semua Kecamatan</option>
                <option>Mamboro</option>
                <option>Katiku Tana</option>
                <option>Katiku Tana Selatan</option>
                <option>Umbu Ratu Nggay</option>
                <option>Umbu Ratu Nggay Barat</option>
            </select>
            <select id="filterVillage" class="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-primary focus:border-primary">
                <option value="">Semua Desa</option>
                <?php $__currentLoopData = $villages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $village): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option><?php echo e($village); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
            <select id="filterComponent" class="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-primary focus:border-primary">
                <option value="">Semua Komponen</option>
                <option>Hortikultura</option>
                <option>Ternak</option>
                <option>Unggas</option>
                <option>Ikan</option>
            </select>
        </div>
    </div>

    <div id="map"></div>

    <div class="mt-6">
        <h4 class="text-sm font-semibold text-gray-700 mb-3">Legenda Warna Desa</h4>
        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3 max-h-40 overflow-y-auto p-2 bg-gray-50 rounded-lg">
            <?php $__currentLoopData = $villageColors; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $village => $color): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="flex items-center space-x-2">
                    <div class="w-3 h-3 rounded-full shadow-sm" style="background-color: <?php echo e($color); ?>"></div>
                    <span class="text-[10px] text-gray-600 truncate" title="<?php echo e($village); ?>"><?php echo e($village); ?></span>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Center of Sumba Tengah (Approximate)
        var map = L.map('map').setView([-9.45, 119.6], 11);

        // Base Layers
        var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        });

        var satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EBP, and the GIS User Community'
        });

        // Add default layer
        osm.addTo(map);

        // Layer Control
        var baseMaps = {
            "Peta Standar": osm,
            "Satelit": satellite
        };
        L.control.layers(baseMaps).addTo(map);

        // Layer group for markers
        var markersLayer = L.layerGroup().addTo(map);

        // Real data from database
        var locations = <?php echo json_encode($beneficiaries, 15, 512) ?>;
        var districtVillages = <?php echo json_encode($districtVillages, 15, 512) ?>;
        var allVillages = <?php echo json_encode($villages, 15, 512) ?>;

        // Filter elements
        var filterDistrict = document.getElementById('filterDistrict');
        var filterVillage = document.getElementById('filterVillage');
        var filterComponent = document.getElementById('filterComponent');
        var visibleCount = document.getElementById('visibleCount');

        function updateVillageOptions() {
            var selectedDistrict = filterDistrict.value;
            var villages = selectedDistrict ? (districtVillages[selectedDistrict] || []) : allVillages;
            
            var currentVillage = filterVillage.value;
            filterVillage.innerHTML = '<option value="">Semua Desa</option>';
            
            villages.sort().forEach(function(v) {
                var option = document.createElement('option');
                option.value = v;
                option.text = v;
                if (v === currentVillage) option.selected = true;
                filterVillage.appendChild(option);
            });
        }

        function updateMarkers() {
            markersLayer.clearLayers();
            
            var district = filterDistrict.value;
            var village = filterVillage.value;
            var component = filterComponent.value;

            var filtered = locations.filter(function(loc) {
                var matchDistrict = !district || loc.district === district;
                var matchVillage = !village || loc.village === village;
                var matchComponent = !component || loc.type === component || (component === 'Ikan' && loc.type === 'Perikanan');
                return matchDistrict && matchVillage && matchComponent;
            });

            visibleCount.innerText = filtered.length;

            filtered.forEach(function(loc) {
                var marker = L.circleMarker([loc.lat, loc.lng], {
                    radius: 8,
                    fillColor: loc.color,
                    color: "#fff",
                    weight: 2,
                    opacity: 1,
                    fillOpacity: 0.8
                });

                marker.bindPopup(`
                    <div class="p-1">
                        <h4 class="font-bold text-gray-800">${loc.name}</h4>
                        <p class="text-xs text-gray-600">${loc.type}</p>
                        <p class="text-[10px] text-gray-400 mt-1">${loc.village}, Kec. ${loc.district}</p>
                        <a href="/beneficiaries/${loc.id}" class="text-[10px] text-primary mt-2 block font-semibold uppercase tracking-wider">Lihat Detail</a>
                    </div>
                `);

                markersLayer.addLayer(marker);
            });

            if (filtered.length > 0) {
                var group = new L.featureGroup(markersLayer.getLayers());
                map.fitBounds(group.getBounds().pad(0.1));
            }
        }

        filterDistrict.addEventListener('change', function() {
            updateVillageOptions();
            updateMarkers();
        });
        filterVillage.addEventListener('change', updateMarkers);
        filterComponent.addEventListener('change', updateMarkers);

        // Initial markers
        updateVillageOptions();
        updateMarkers();
    });
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/sumba001/public_html/pom500.sumbatengahkab.go.id/resources/views/map.blade.php ENDPATH**/ ?>