@extends('layouts.app')
@section('title', 'Peta Potensi Desa Suka Baru')
@section('meta_description', 'Peta Potensi Desa Suka Baru Kecamatan Marga Sakti Sebelat Kabupaten Bengkulu Utara')

@push('scripts')
<script>
window.addEventListener('load', function () {
    if (typeof L === 'undefined') { console.error('Leaflet belum dimuat'); return; }

    const points = @json($points);
    const center = [-3.1680, 101.7070];

    const map = L.map('peta-map', {
        center: center,
        zoom: 15,
        zoomControl: false,
        scrollWheelZoom: true,
    });

    L.control.zoom({ position: 'bottomright' }).addTo(map);

    const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    });

    const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        maxZoom: 19,
        attribution: '© Esri, Maxar'
    });

    satelliteLayer.addTo(map);

    const basemaps = { '🛰️ Satelit': satelliteLayer, '🗺️ Peta': osmLayer };
    L.control.layers(basemaps, {}, { position: 'topright', collapsed: false }).addTo(map);

    const iconConfig = {
        kantor_desa:    { emoji: '🏛️', color: '#1E3A8A', bg: '#dbeafe' },
        dusun:          { emoji: '🏘️', color: '#2563EB', bg: '#eff6ff' },
        fasilitas_umum: { emoji: '🏢', color: '#059669', bg: '#ecfdf5' },
        objek_wisata:   { emoji: '🌿', color: '#0891b2', bg: '#ecfeff' },
        batas_desa:     { emoji: '🚩', color: '#475569', bg: '#f1f5f9' },
    };

    function getEmoji(point) {
        const nama = point.nama.toLowerCase();
        if (nama.includes('masjid') || nama.includes('mushola'))  return '🕌';
        if (nama.includes('posyandu') || nama.includes('kesehatan')) return '🏥';
        if (nama.includes('paud') || nama.includes('pendidikan') || nama.includes('sekolah')) return '📚';
        if (nama.includes('lapangan voli') || nama.includes('sepak bola')) return '⚽';
        if (nama.includes('warung') || nama.includes('toko'))     return '🏪';
        if (nama.includes('bengkel'))  return '🔧';
        if (nama.includes('pertamina') || nama.includes('spbu'))  return '⛽';
        if (nama.includes('koperasi')) return '🤝';
        if (nama.includes('gajah') || nama.includes('plg'))       return '🐘';
        if (nama.includes('gapura'))   return '🚪';
        if (nama.includes('sungai'))   return '🌊';
        if (nama.includes('balai desa') || nama.includes('kantor kepala')) return '🏛️';
        if (nama.includes('bpd'))      return '🏢';
        if (nama.includes('bkkbn'))    return '👨‍👩‍👧';
        if (nama.includes('camat'))    return '🏢';
        if (nama.includes('dusun'))    return '🏘️';
        if (nama.includes('batas'))    return '🚩';
        const cfg = iconConfig[point.jenis] || iconConfig['fasilitas_umum'];
        return cfg.emoji;
    }

    function createMarkerIcon(point) {
        const cfg = iconConfig[point.jenis] || iconConfig['fasilitas_umum'];
        const emoji = getEmoji(point);
        return L.divIcon({
            className: '',
            html: `<div style="
                width:36px;height:36px;border-radius:50%;
                background:${cfg.bg};border:2.5px solid ${cfg.color};
                box-shadow:0 3px 10px rgba(0,0,0,0.3);
                display:flex;align-items:center;justify-content:center;
                font-size:16px;transition:transform 0.15s;cursor:pointer;
            ">${emoji}</div>`,
            iconSize: [36, 36],
            iconAnchor: [18, 36],
            popupAnchor: [0, -38],
        });
    }

    const markerMap = {};
    if (points && points.length > 0) {
        const bounds = [];
        points.forEach(function (p) {
            if (!p.latitude || !p.longitude) return;
            const cfg = iconConfig[p.jenis] || iconConfig['fasilitas_umum'];
            const emoji = getEmoji(p);
            const marker = L.marker([p.latitude, p.longitude], { icon: createMarkerIcon(p) });
            marker.bindPopup(
                `<div style="font-family:sans-serif;min-width:200px;padding:4px 0;">
                    <div style="font-size:22px;text-align:center;margin-bottom:6px;">${emoji}</div>
                    <p style="font-weight:800;font-size:13px;color:#111827;margin:0 0 5px 0;text-align:center;">${p.nama}</p>
                    <div style="text-align:center;margin-bottom:8px;">
                        <span style="font-size:10px;background:${cfg.bg};color:${cfg.color};padding:2px 10px;border-radius:999px;font-weight:700;border:1px solid ${cfg.color}30;">${p.jenis_label}</span>
                    </div>
                    ${p.deskripsi ? `<p style="font-size:11px;color:#6b7280;margin:0;line-height:1.5;border-top:1px solid #f3f4f6;padding-top:8px;">${p.deskripsi}</p>` : ''}
                </div>`,
                { maxWidth: 250, className: 'custom-popup' }
            );
            marker.addTo(map);
            markerMap[p.id] = marker;
            bounds.push([p.latitude, p.longitude]);
        });
        if (bounds.length > 1) {
            map.fitBounds(bounds, { padding: [60, 60] });
        }
    }

    document.querySelectorAll('[data-point-id]').forEach(function (el) {
        el.addEventListener('click', function (e) {
            if (e.target.tagName === 'A' || e.target.closest('a')) return;
            const id = parseInt(this.dataset.pointId);
            const lat = parseFloat(this.dataset.lat);
            const lng = parseFloat(this.dataset.lng);
            map.setView([lat, lng], 17, { animate: true });
            if (markerMap[id]) {
                markerMap[id].openPopup();
            }
            document.getElementById('peta-map').scrollIntoView({ behavior: 'smooth', block: 'center' });
        });
    });

    setTimeout(function () { map.invalidateSize(); }, 300);
});
</script>
<style>
.custom-popup .leaflet-popup-content-wrapper {
    border-radius: 14px !important;
    box-shadow: 0 8px 30px rgba(0,0,0,0.18) !important;
}
.custom-popup .leaflet-popup-tip { background: white !important; }
.leaflet-control-layers { border-radius: 12px !important; font-size: 12px !important; }
</style>
@endpush

@section('content')

{{-- HERO --}}
<div style="background: linear-gradient(135deg, #1E3A8A 0%, #1e40af 50%, #0f172a 100%);" class="py-10 text-white">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <nav class="text-blue-200 text-sm mb-3">
            <a href="{{ route('home') }}" class="hover:text-white">Beranda</a>
            <span class="mx-2">/</span>
            <span class="text-white font-medium">Peta Potensi Desa</span>
        </nav>
        <h1 class="text-3xl sm:text-4xl font-extrabold text-white tracking-tight">Peta & Titik Potensi Desa Suka Baru</h1>
        <p class="text-blue-200 text-sm mt-1.5 font-light">
            Kecamatan Marga Sakti Sebelat, Kabupaten Bengkulu Utara &bull; Skala 1:15.000 &bull; GCS WGS 1984
        </p>
    </div>
</div>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

    {{-- LEGEND --}}
    <div class="bg-white border border-gray-200 rounded-2xl p-4 mb-6 shadow-sm">
        <p class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">Keterangan Peta & Kategori Titik</p>
        <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-y-2 gap-x-4 text-xs">
            @foreach([
                ['label' => 'Balai Desa / Pemerintahan', 'color' => '#1E3A8A'],
                ['label' => 'Masjid / Tempat Ibadah', 'color' => '#059669'],
                ['label' => 'Posyandu / Kesehatan', 'color' => '#dc2626'],
                ['label' => 'PAUD / Pendidikan', 'color' => '#ea580c'],
                ['label' => 'Lapangan Olahraga', 'color' => '#7c3aed'],
                ['label' => 'Warung / Toko Warga', 'color' => '#ca8a04'],
                ['label' => 'Pertamina / BBM', 'color' => '#dc2626'],
                ['label' => 'Bengkel Motor & Mobil', 'color' => '#475569'],
                ['label' => 'Koperasi Desa', 'color' => '#0891b2'],
                ['label' => 'PLG Seblat (Wisata)', 'color' => '#065f46'],
                ['label' => 'Sungai Seblat', 'color' => '#0284c7'],
            ] as $leg)
            <div class="flex items-center gap-2">
                <span style="color:{{ $leg['color'] }}" class="font-semibold leading-tight">{{ $leg['label'] }}</span>
            </div>
            @endforeach
        </div>
    </div>

    {{-- FOTO PETA STATIC --}}
    <div class="shadow-xl border border-gray-200 rounded-3xl overflow-hidden mb-10 bg-slate-900 text-center relative group">
        <img src="{{ asset('images/peta.jpg') }}" alt="Peta Desa Suka Baru" class="max-w-full h-auto mx-auto rounded-2xl" />
        <div class="bg-black/60 backdrop-blur-md text-white p-3 text-xs font-medium">
            🗺️ Peta Potensi Desa Suka Baru, Kecamatan Marga Sakti Sebelat, Kabupaten Bengkulu Utara
        </div>
    </div>

    {{-- DAFTAR TITIK LOKASI DENGAN FOTO TERINTEGRASI --}}
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-black text-gray-900 flex items-center gap-2">
            <span style="width:4px;height:24px;background:#1E3A8A;border-radius:2px;display:inline-block;"></span>
            Daftar Titik Lokasi & Foto Potensi
            <span class="bg-blue-100 text-blue-800 text-xs font-black px-3 py-1 rounded-full ml-2">
                {{ $points->count() }} Titik Terintegrasi
            </span>
        </h2>
    </div>

    @if($points->count() > 0)
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
        @foreach($points as $point)
        @php
            $jenisColor = [
                'kantor_desa'    => ['color' => '#1E3A8A', 'bg' => '#eff6ff'],
                'dusun'          => ['color' => '#2563EB', 'bg' => '#eff6ff'],
                'fasilitas_umum' => ['color' => '#059669', 'bg' => '#ecfdf5'],
                'objek_wisata'   => ['color' => '#0891b2', 'bg' => '#ecfeff'],
                'batas_desa'     => ['color' => '#475569', 'bg' => '#f1f5f9'],
            ];
            $cfg = $jenisColor[$point->jenis] ?? ['color' => '#1E3A8A', 'bg' => '#eff6ff'];
            $potId = $point->matching_potential_id;
        @endphp
        <div class="bg-white border border-gray-200 rounded-3xl p-4 flex flex-col justify-between hover:shadow-xl hover:-translate-y-1 transition-all duration-300 group"
             data-point-id="{{ $point->id }}"
             data-lat="{{ $point->latitude }}"
             data-lng="{{ $point->longitude }}">

            <div class="flex items-start gap-3.5">
                {{-- Foto Tempat / Titik --}}
                <div class="w-16 h-16 rounded-2xl overflow-hidden bg-slate-100 flex-shrink-0 border border-gray-200 shadow-sm relative group-hover:scale-105 transition-transform duration-300">
                    @if($point->foto_url)
                        <img src="{{ $point->foto_url }}" alt="{{ $point->nama }}" class="w-full h-full object-cover">
                    @else
                        <div class="w-full h-full flex items-center justify-center text-xl bg-blue-50 text-blue-600 font-bold">
                            📍
                        </div>
                    @endif
                </div>

                {{-- Deskripsi Titik --}}
                <div class="flex-1 min-w-0">
                    <h3 class="font-bold text-gray-900 text-sm leading-snug group-hover:text-blue-600 transition-colors line-clamp-1">
                        {{ $point->nama }}
                    </h3>
                    <span style="background: {{ $cfg['bg'] }}; color: {{ $cfg['color'] }};" class="text-[10px] font-extrabold px-2.5 py-0.5 rounded-full uppercase tracking-wider inline-block mt-1">
                        {{ $point->jenis_label }}
                    </span>
                    @if($point->deskripsi)
                    <p class="text-xs text-gray-500 mt-1.5 leading-relaxed line-clamp-2">
                        {{ $point->deskripsi }}
                    </p>
                    @endif
                </div>
            </div>

            {{-- Action Link ke Artikel Detail Potensi --}}
            <div class="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between text-xs">
                <span class="text-gray-400 font-medium text-[11px] flex items-center gap-1">
                    📍 Lokasi Terdata
                </span>
                @if($potId)
                <a href="{{ route('potensi.show', $potId) }}"
                   class="font-bold text-blue-600 hover:text-blue-800 bg-blue-50 hover:bg-blue-100 px-3 py-1.5 rounded-full transition-colors flex items-center gap-1">
                    Artikel Detail ➔
                </a>
                @else
                <a href="{{ route('potensi') }}"
                   class="font-bold text-gray-600 hover:text-gray-800 bg-gray-100 hover:bg-gray-200 px-3 py-1.5 rounded-full transition-colors flex items-center gap-1">
                    Potensi Desa ➔
                </a>
                @endif
            </div>

        </div>
        @endforeach
    </div>
    @endif

    {{-- INFO SUMBER --}}
    <div class="mt-10 bg-slate-50 border border-slate-200 rounded-3xl p-6 flex flex-col sm:flex-row items-start gap-4">
        <span class="text-3xl p-3 bg-white border border-slate-200 rounded-2xl shadow-sm">🗺️</span>
        <div>
            <h4 class="text-xs font-extrabold uppercase tracking-wider text-slate-800">Sumber Data Peta & Foto Lokasi</h4>
            <p class="text-xs text-slate-600 mt-1 leading-relaxed">
                Data titik lokasi dan foto potensi bersumber dari <strong>Peta Potensi Desa Suka Baru Seblat</strong>, Kecamatan Marga Sakti Sebelat, Kabupaten Bengkulu Utara.
                Skala 1:15.000 — Koordinat GCS WGS 1984 — Datum WGS 1984.
                Dibuat oleh <strong>PPK Ormawa HIMA Sylva PCSI Universitas Bengkulu</strong>.
            </p>
        </div>
    </div>

</div>
@endsection
