{{--
    Geo Density Map Component — Leaflet.js
    Requires: npm install leaflet  (then import in resources/js/app.js)
    Props:
      - cities: Collection of {city, count, latitude?, longitude?} objects
      - title: Card heading
--}}
@props([
    'cities' => collect(),
    'title'  => 'Geographic Distribution',
])

@php
    $mapId = 'geoMap_' . uniqid();
@endphp

<div class="bg-white/80 backdrop-blur-sm rounded-xl p-6 shadow-lg border border-gray-100">
    <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-gray-800">
            <i class="fas fa-map-marked-alt text-rose-500 mr-2"></i>{{ $title }}
        </h3>
        @if($cities->isNotEmpty())
            <span class="text-xs text-gray-400 bg-gray-100 px-2 py-1 rounded-full">
                {{ $cities->count() }} {{ Str::plural('city', $cities->count()) }}
            </span>
        @endif
    </div>

    @if($cities->isNotEmpty())
        <div id="{{ $mapId }}"
             class="h-64 rounded-lg z-0 border border-gray-200"
             data-cities="{{ $cities->toJson() }}">
        </div>
        <p class="text-xs text-gray-400 mt-2">
            <i class="fas fa-info-circle mr-1"></i>
            Showing {{ $cities->count() }} {{ Str::plural('city', $cities->count()) }} with registered institutions.
            @if($cities->whereNull('latitude')->isNotEmpty())
                Coordinates not yet set for some locations — edit institutions to add GPS data.
            @endif
        </p>
    @else
        <div class="flex flex-col items-center justify-center h-40 text-gray-400">
            <i class="fas fa-map text-4xl mb-3 text-gray-300"></i>
            <p class="text-sm">No institution locations yet.</p>
            <p class="text-xs mt-1">Register institutions to see geographic distribution.</p>
        </div>
    @endif
</div>

@push('styles')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
      integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
@endpush

@push('scripts')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV/XN/WLs=" crossorigin=""></script>
<script>
(function () {
    const mapEl = document.getElementById('{{ $mapId }}');
    if (!mapEl) return;

    // Default center: South Sudan
    const map = L.map('{{ $mapId }}').setView([4.85, 31.6], 6);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
        maxZoom: 18,
    }).addTo(map);

    let cities = [];
    try {
        cities = JSON.parse(mapEl.dataset.cities || '[]');
    } catch (e) {
        console.warn('Geo map: could not parse cities data', e);
    }

    const bounds = [];

    cities.forEach(function (city) {
        if (city.latitude && city.longitude) {
            const lat = parseFloat(city.latitude);
            const lng = parseFloat(city.longitude);

            if (!isNaN(lat) && !isNaN(lng)) {
                const marker = L.circleMarker([lat, lng], {
                    radius: Math.min(6 + city.count * 2, 20),
                    fillColor: '#f43f5e',
                    color: '#be123c',
                    weight: 1.5,
                    opacity: 1,
                    fillOpacity: 0.7,
                }).addTo(map);

                marker.bindPopup(
                    `<strong>${city.city}</strong><br>${city.count} institution${city.count !== 1 ? 's' : ''}`
                );

                bounds.push([lat, lng]);
            }
        }
    });

    if (bounds.length > 0) {
        map.fitBounds(bounds, { padding: [30, 30], maxZoom: 10 });
    }
})();
</script>
@endpush
