@extends('layouts.app')


<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<style>
    /* Styling tambahan untuk memuluskan transisi modal peta */
    .modal-active {
        overflow: hidden;
    }
    
    /* OPTIMASI KINERJA MAP: Memaksa hardware acceleration GPU untuk rendering peta Leaflet yang mulus */
    .leaflet-tile-container {
        will-change: transform;
        transform: translateZ(0);
        -webkit-transform: translateZ(0);
    }
    .leaflet-zoom-animated {
        will-change: transform;
    }
</style>



<div class="flex flex-col gap-6">
    <!-- Header Halaman -->
    <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
        <h2 class="text-2xl font-bold text-slate-800">Formulir Pengajuan Usulan Bantuan</h2>
        <p class="text-sm text-slate-500 mt-1 font-medium">Ajukan bantuan sarana produksi pertanian untuk Kelompok Tani resmi. Sistem dilengkapi dengan peta satelit geospasial riil Jawa Tengah.</p>
    </div>

    <!-- Tampilan Notifikasi Error jika ada -->
    @if($errors->any())
        <div class="bg-rose-100 border-l-4 border-rose-600 text-rose-800 p-4 rounded-xl shadow-sm text-sm">
            <span class="font-bold block mb-1">Kesalahan Pengisian:</span>
            <ul class="list-disc pl-5 mt-1 space-y-0.5 font-medium">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route('kabupaten.usulan.store') }}" method="POST" enctype="multipart/form-data" id="formUsulan">
        @csrf
        <!-- Input Tersembunyi untuk Membedakan Tombol Aksi (Draft vs Submit) -->
        <input type="hidden" name="action_type" id="actionType" value="submit">

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <!-- FORM INPUT KIRI -->
            <div class="lg:col-span-2 bg-white rounded-xl border border-slate-200 shadow-sm p-6 flex flex-col gap-5">
                <h4 class="font-bold text-slate-800 border-b border-slate-100 pb-2 flex items-center gap-2">
                    <i data-lucide="file-plus" class="text-emerald-700 w-4 h-4"></i>
                    Informasi Utama Usulan
                </h4>

                <!-- 1. Pilih Program Kegiatan -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Pilih Program / Kegiatan:</label>
                    <select name="kegiatan_id" id="kegiatanSelect" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 cursor-pointer font-medium text-slate-700">
                        @forelse($kegiatan as $k)
                            <option value="{{ $k->id }}">{{ $k->nama_kegiatan }} (TA {{ $k->tahun_anggaran }})</option>
                        @empty
                            <option value="1">Saprodi Padi Unggul (TA 2026)</option>
                        @endforelse
                    </select>
                </div>

                <!-- 2. Pencarian Poktan Autocomplete -->
                <div class="relative">
                    <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Cari Kelompok Tani (Database Resmi):</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-slate-400">
                            <i data-lucide="search" class="w-4 h-4"></i>
                        </span>
                        <input type="text" id="poktanSearch" placeholder="Ketik nama kelompok atau nomor induk poktan..." class="w-full pl-10 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 transition-all font-medium text-slate-700" autocomplete="off">
                    </div>

                    <div id="autocompleteDropdown" class="hidden absolute left-0 right-0 z-50 bg-white border border-slate-200 rounded-lg mt-1 shadow-xl max-h-56 overflow-y-auto divide-y divide-slate-100"></div>
                    
                    <input type="hidden" name="kelompok_tani_id" id="selectedPoktanId">

                    <!-- Panel Info Kelompok Tani Terpilih -->
                    <div id="selectedPoktanPanel" class="hidden mt-3 p-4 bg-emerald-50 border border-emerald-100 rounded-xl text-xs flex justify-between items-center shadow-inner animate-fade-in">
                        <div class="flex items-center gap-3">
                            <div class="bg-emerald-600 text-white p-2 rounded-lg">
                                <i data-lucide="check" class="w-4 h-4"></i>
                            </div>
                            <div>
                                <p class="font-bold text-emerald-900 text-sm" id="selectedPoktanName">Nama Kelompok</p>
                                <p class="text-emerald-700 mt-0.5" id="selectedPoktanDetail">Detail Nomor Induk & Ketua</p>
                            </div>
                        </div>
                        <button type="button" onclick="resetSelectedPoktan()" class="text-emerald-900 hover:text-rose-600 p-2 hover:bg-emerald-100 rounded-lg transition-all">
                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>

                <!-- 3. Luas Lahan Pengajuan -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Luas Lahan Pemanfaatan (Hektar):</label>
                    <input type="number" name="luas_lahan" id="luasLahanInput" placeholder="Contoh: 1.5" step="0.1" min="0.1" required class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm font-semibold text-slate-800 focus:outline-none focus:ring-2 focus:ring-emerald-500 transition-all">
                </div>

                <!-- 4. Unggah Berkas Persyaratan PDF -->
                <div class="border-t border-slate-100 pt-4">
                    <h4 class="font-bold text-slate-800 mb-3 text-sm">Dokumen Persyaratan Tambahan (Wajib PDF jika langsung dikirim)</h4>
                    <div class="p-4 bg-slate-50 border border-slate-200 rounded-lg text-xs flex flex-col gap-2">
                        <div class="flex justify-between items-center">
                            <span class="font-bold text-slate-700">Surat Keterangan Kepala Desa / Lurah</span>
                            <span class="text-slate-400">Berkas PDF (Maksimal 2MB, opsional jika simpan draf)</span>
                        </div>
                        <input type="file" name="dokumen_sk_desa" accept="application/pdf" class="text-xs bg-white p-2 border border-slate-200 rounded-lg focus:outline-none cursor-pointer">
                    </div>
                </div>

                <!-- Tombol Aksi Form Ganda (Draft & Submit) -->
                <div class="border-t border-slate-100 pt-4 flex justify-between gap-3 items-center">
                    <a href="{{ route('shared.usulan.index') }}" class="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-lg text-xs font-bold transition-colors">Batal</a>
                    
                    <div class="flex gap-2">
                        <!-- TOMBOL SAVE DRAFT -->
                        <button type="button" onclick="submitForm('draft')" class="px-4 py-2.5 bg-amber-500 hover:bg-amber-600 text-white rounded-lg text-xs font-bold shadow-sm transition-colors flex items-center gap-1.5">
                            <i data-lucide="file-edit" class="w-4 h-4"></i>
                            Simpan sebagai Draf
                        </button>
                        
                        <!-- TOMBOL KIRIM UTAMA -->
                        <button type="button" onclick="submitForm('submit')" class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow-sm transition-colors flex items-center gap-1.5">
                            <i data-lucide="send" class="w-4.5 h-4.5"></i>
                            Kirim Usulan Resmi
                        </button>
                    </div>
                </div>
            </div>

            <!-- MODUL PREVIEW PETA (KANAN) -->
            <div class="flex flex-col gap-6">
                <!-- Card Pratinjau Peta Mini -->
                <div class="bg-white rounded-xl border border-slate-200 shadow-sm p-5 flex flex-col gap-4">
                    <h4 class="font-bold text-slate-800 flex items-center gap-2 text-sm border-b border-slate-100 pb-2">
                        <i data-lucide="map" class="text-emerald-700 w-4.5 h-4.5"></i>
                        Plot Batas Lahan Kelompok Tani
                    </h4>
                    
                    <!-- Box Pratinjau Kecil (Klik untuk Membuka Peta Besar) -->
                    <div onclick="bukaModalPeta()" class="group relative w-full h-44 bg-slate-900 rounded-xl overflow-hidden shadow-inner cursor-pointer border border-slate-200 flex flex-col items-center justify-center text-center gap-2 hover:border-emerald-500 transition-all font-sans">
                        <!-- Citra Latar Belakang Satelit -->
                        <div class="absolute inset-0 bg-cover bg-center opacity-60 group-hover:scale-105 transition-all duration-500" style="background-image: url('https://images.unsplash.com/photo-1500382017468-9049fed747ef?auto=format&fit=crop&q=80&w=400');"></div>
                        <div class="absolute inset-0 bg-gradient-to-t from-slate-950/80 to-transparent z-10"></div>
                        
                        <!-- Mini Leaflet Map Preview Container -->
                        <div id="miniMapPreview" class="absolute inset-0 z-0 opacity-80 pointer-events-none"></div>

                        <!-- Ikon Melayang -->
                        <div class="z-20 bg-white/90 hover:bg-white text-emerald-800 p-3 rounded-full shadow-lg scale-90 group-hover:scale-100 transition-all duration-300">
                            <i data-lucide="maximize-2" class="w-5 h-5"></i>
                        </div>
                        <span class="z-20 text-xs font-bold text-white tracking-wide">Atur Batas Lahan di Peta Besar</span>
                        <span id="miniMapBadge" class="z-20 text-[10px] bg-emerald-600 text-white font-extrabold px-2.5 py-0.5 rounded-full uppercase tracking-wider shadow">Belum Tergambar</span>
                    </div>

                    <!-- Input Tersembunyi untuk Menampung Format Spasial WKT -->
                    <input type="hidden" name="polygon_coordinates" id="wktCoordinates">

                    <!-- Data Geolokasi Terjemahan WKT (Mini display) -->
                    <div class="text-[10px] bg-slate-50 p-2.5 rounded-lg border border-slate-100 text-slate-500 font-mono leading-relaxed">
                        <span class="font-bold block text-slate-600 mb-1">DATA GEOLOKASI (WKT):</span>
                        <div id="geoJsonText" class="truncate font-bold text-slate-700">[kosong - belum dipetakan]</div>
                    </div>
                </div>

                <!-- Petunjuk Juknis Spasial -->
                <div class="bg-amber-50 border border-amber-200 rounded-xl p-5 text-xs text-amber-800 leading-relaxed font-medium flex gap-3">
                    <i data-lucide="info" class="w-5 h-5 text-amber-700 shrink-0"></i>
                    <div>
                        <h5 class="font-bold mb-1 text-amber-950">Informasi Peta Pop-up:</h5>
                        Dengan menekan tombol peta di atas, sistem akan memunculkan penjelajah geospasial berskala penuh untuk memudahkan penentuan lokasi sawah kelompok tani secara presisi.
                    </div>
                </div>
            </div>

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

<!-- ========================================================================= -->
<!--             PGIM (PRADIPA INTERACTIVE GEOSPATIAL MAP) MODAL RAKSASA       -->
<!-- ========================================================================= -->
<div id="modalPetaRaksasa" class="hidden fixed inset-0 z-50 bg-slate-950/80 flex items-center justify-center p-4">
    <div class="bg-white w-full max-w-6xl rounded-2xl shadow-2xl border border-slate-200 flex flex-col h-[85vh] overflow-hidden">
        
        <!-- Header Modal Peta -->
        <div class="bg-slate-50 border-b border-slate-100 px-6 py-4 flex flex-col sm:flex-row justify-between sm:items-center gap-4">
            <div>
                <h3 class="font-extrabold text-slate-800 text-lg flex items-center gap-2">
                    <i data-lucide="map" class="text-emerald-600 w-5 h-5"></i>
                    Penjelajah Geospasial Batas Lahan Poktan
                </h3>
                <p class="text-xs text-slate-500 font-medium">Klik pada batas-batas sawah Kelompok Tani untuk menggambar Polygon area lahan (Satelit Esri).</p>
            </div>
            
            <!-- Tombol Keluar & Tutup -->
            <button type="button" onclick="tutupModalPeta()" class="text-slate-400 hover:text-slate-600 bg-slate-100 hover:bg-slate-200 p-2 rounded-full transition-all self-end sm:self-auto">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>

        <!-- Toolbar Pencarian Lokasi Cepat di atas Peta -->
        <div class="bg-slate-100/80 px-6 py-3 border-b border-slate-200 flex flex-col sm:flex-row justify-between items-center gap-3">
            <!-- Search Bar Alamat -->
            <div class="flex-1 w-full relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-slate-400">
                    <i data-lucide="search" class="w-4 h-4"></i>
                </span>
                <input type="text" id="mapSearchInput" onkeydown="handleSearchMap(event)" placeholder="Ketik nama desa, kecamatan, atau kota di Jawa Tengah (lalu tekan Enter)..." class="w-full pl-9 pr-24 py-2 bg-white border border-slate-200 rounded-lg text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-emerald-500">
                <button type="button" onclick="searchAddressMap()" class="absolute inset-y-1 right-1 px-3 bg-slate-800 hover:bg-slate-900 text-white rounded-md text-[10px] font-bold transition-all font-sans">Cari Lokasi</button>
            </div>

            <!-- Tombol GPS & Reset -->
            <div class="flex gap-2 w-full sm:w-auto">
                <button type="button" onclick="getUserLocation()" class="flex-1 sm:flex-initial px-3 py-2 bg-emerald-50 hover:bg-emerald-100 text-emerald-800 border border-emerald-200 rounded-lg text-xs font-bold flex items-center justify-center gap-1.5 transition-all font-sans">
                    <i data-lucide="navigation" class="w-3.5 h-3.5 font-sans"></i>
                    Gunakan GPS Saya
                </button>
                <button type="button" onclick="clearLeafletPolygon()" class="flex-1 sm:flex-initial px-3 py-2 bg-rose-50 hover:bg-rose-100 text-rose-700 border border-rose-200 rounded-lg text-xs font-bold flex items-center justify-center gap-1.5 transition-all font-sans">
                    <i data-lucide="rotate-ccw" class="w-3.5 h-3.5"></i>
                    Reset Gambar
                </button>
            </div>
        </div>

        <!-- Wadah Utama Peta Leaflet (Fullscreen di dalam Modal) -->
        <div class="flex-1 relative">
            <div id="leafletMap" class="w-full h-full z-10"></div>
            
            <!-- Lencana Teks Mengambang di atas peta -->
            <div class="absolute z-20 top-4 left-4 bg-slate-950/85 text-white p-3 rounded-xl shadow-lg border border-slate-800 text-[10px] space-y-1 font-sans">
                <span class="font-extrabold text-amber-400 block uppercase tracking-wider">Metode Gambar Batas Sawah:</span>
                <p class="leading-relaxed">1. Klik pada peta untuk menaruh pasak sudut sawah pertama.<br>2. Klik sudut berikutnya secara memutar searah jarum jam.<br>3. Hubungkan minimal 3 sudut sawah hingga area hijau terbentuk.</p>
            </div>
        </div>

        <!-- Footer Modal Peta -->
        <div class="bg-slate-50 border-t border-slate-200 px-6 py-4 flex justify-between items-center">
            <div class="text-[11px] font-semibold text-slate-500 font-mono flex items-center gap-2">
                <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                <span>WGS84 EPSG:4326</span>
            </div>
            
            <button type="button" onclick="simpanDanTutupPeta()" class="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow-md flex items-center gap-1.5 transition-all font-sans">
                <i data-lucide="check" class="w-4 h-4"></i>
                Simpan & Kunci Batas Lahan
            </button>
        </div>

    </div>
</div>



<!-- Masukkan CDN Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script>
    // --- AUTOCOMPLETE LOGIC ---
    const searchInput = document.getElementById('poktanSearch');
    const dropdown = document.getElementById('autocompleteDropdown');
    const selectedPanel = document.getElementById('selectedPoktanPanel');
    const selectedIdInput = document.getElementById('selectedPoktanId');

    searchInput.addEventListener('input', function() {
        const query = this.value.trim().toLowerCase();
        if (query.length < 2) {
            dropdown.classList.add('hidden');
            return;
        }

        fetch(`{{ route('kabupaten.api.poktan_search') }}?term=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(data => {
                renderDropdownResults(data);
            });
    });

    function renderDropdownResults(items) {
        dropdown.innerHTML = '';
        if (items.length === 0) {
            dropdown.innerHTML = '<div class="p-3 text-xs text-rose-600 font-medium bg-white">Kelompok tani tidak ditemukan di database resmi kabupaten ini.</div>';
            dropdown.classList.remove('hidden');
            return;
        }

        items.forEach(p => {
            const item = document.createElement('div');
            item.className = 'p-3 hover:bg-slate-100 cursor-pointer text-xs border-b border-slate-100 transition-colors bg-white flex justify-between items-center font-sans';
            item.innerHTML = `
                <div>
                    <span class="font-bold text-slate-800 text-sm block">${p.nama_kelompok}</span>
                    <span class="text-[10px] text-slate-400 font-sans">No Induk: <span class="font-mono text-emerald-700 font-semibold">${p.nomor_induk}</span></span>
                </div>
                <span class="text-[9px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded-full font-bold font-sans">Kab. ${p.nama_kabupaten || p.kabupaten}</span>
            `;
            item.addEventListener('click', () => {
                selectPoktan(p.id, p.nama_kelompok, p.nomor_induk, (p.nama_ketua || p.ketua));
            });
            dropdown.appendChild(item);
        });
        dropdown.classList.remove('hidden');
    }

    function selectPoktan(id, nama, induk, ketua) {
        selectedIdInput.value = id;
        searchInput.value = '';
        dropdown.classList.add('hidden');
        selectedPanel.classList.remove('hidden');
        document.getElementById('selectedPoktanName').innerText = nama;
        document.getElementById('selectedPoktanDetail').innerText = `Nomor Induk: ${induk} | Ketua: ${ketua}`;
        lucide.createIcons();
    }

    function resetSelectedPoktan() {
        selectedIdInput.value = '';
        selectedPanel.classList.add('hidden');
    }

    // --- LEAFLET PGIM SYSTEM (MODAL MAP & REUSABLE SOURCE) ---
    let map, polygonLayer;
    let currentCoords = [];
    let mapMarkers = [];
    let isMapInitialized = false;

    /**
     * Membuka modal peta raksasa dan memicu pembaruan layout peta Leaflet
     */
    function bukaModalPeta() {
        document.getElementById('modalPetaRaksasa').classList.remove('hidden');
        document.body.classList.add('modal-active');

        // Inisialisasi peta Leaflet hanya 1 kali di awal untuk menghemat memori komputer
        if (!isMapInitialized) {
            initLeafletMap();
            isMapInitialized = true;
        } else {
            // Re-render ulang peta Leaflet saat modal dibuka agar tidak abu-abu (Invalidate Size)
            setTimeout(() => {
                map.invalidateSize();
                if (currentCoords.length > 0) {
                    const bounds = polygonLayer.getBounds();
                    map.fitBounds(bounds, { padding: [50, 50] });
                }
            }, 150);
        }
    }

    function tutupModalPeta() {
        document.getElementById('modalPetaRaksasa').classList.add('hidden');
        document.body.classList.remove('modal-active');
    }

    function initLeafletMap() {
        // Koordinat tengah Jawa Tengah
        const centralJavaLat = -7.0522;
        const centralJavaLon = 110.4325;

        // Inisialisasi Peta Leaflet dengan optimasi performa caching bawaan
        map = L.map('leafletMap', {
            center: [centralJavaLat, centralJavaLon],
            zoom: 12,
            zoomControl: true,
            attributionControl: true,
            fadeAnimation: true,       // Memuluskan transisi ubin peta
            zoomAnimation: true,       // Memuluskan animasi zoom
            inertia: true              // Mengaktifkan efek inersia drag halus
        });

        // Layer Citra Satelit Bumi Riil dari ESRI World Imagery dengan optimasi pengunduhan
        const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            attribution: 'Tiles &copy; Esri &mdash; Citra Satelit Bumi Riil',
            maxZoom: 19,
            updateWhenIdle: true,      // Mengurangi beban unduh saat sedang menggeser peta
            updateWhenZooming: false,  // Mencegah redraw berlebihan saat melakukan zoom
            keepBuffer: 4              // Menambah cache buffer ubin di luar viewport agar peta tidak berkedip
        });

        // Layer Garis Batas / Nama Jalan dari CartoDB Labels dengan caching optimal
        const labelLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{y}/{x}.png', {
            attribution: '&copy; CartoDB',
            updateWhenIdle: true,
            keepBuffer: 4
        });

        satelliteLayer.addTo(map);
        labelLayer.addTo(map);

        // Kumpulan titik Polygon pembungkus hijau premium khas Pradipa
        polygonLayer = L.polygon([], {
            color: '#10b981',
            fillColor: '#10b981',
            fillOpacity: 0.35,
            weight: 3
        }).addTo(map);

        // Listener klik untuk menambahkan titik koordinat
        map.on('click', function(e) {
            const lat = e.latlng.lat;
            const lon = e.latlng.lng;

            currentCoords.push([lat, lon]);
            updateLeafletPolygon();
        });
    }

    function updateLeafletPolygon() {
        // Gambar koordinat pada layer polygon utama
        polygonLayer.setLatLngs(currentCoords);

        // Bersihkan marker lama
        mapMarkers.forEach(m => map.removeLayer(m));
        mapMarkers = [];

        // Gambar penanda merah kecil untuk setiap sudut koordinat
        currentCoords.forEach((coord, index) => {
            const marker = L.circleMarker(coord, {
                radius: 5,
                fillColor: '#e11d48', // Warna Merah Rose
                color: '#fff',
                weight: 1.5,
                fillOpacity: 1
            }).addTo(map);

            marker.bindTooltip(`Sudut ${index + 1}`, { permanent: false, direction: 'top' });
            mapMarkers.push(marker);
        });

        // Tampilkan teks WKT di bawah peta
        if (currentCoords.length >= 3) {
            const wktPoints = currentCoords.map(coord => `${coord[0].toFixed(6)} ${coord[1].toFixed(6)}`);
            const closedPoint = `${currentCoords[0][0].toFixed(6)} ${currentCoords[0][1].toFixed(6)}`;
            const finalWkt = `POLYGON((${wktPoints.join(', ')}, ${closedPoint}))`;
            
            document.getElementById("geoJsonText").innerText = finalWkt;
        } else {
            document.getElementById("geoJsonText").innerText = `polygon: [sedang digambar - butuh ${3 - currentCoords.length} titik lagi]`;
        }
    }

    function clearLeafletPolygon() {
        currentCoords = [];
        polygonLayer.setLatLngs([]);
        
        mapMarkers.forEach(m => map.removeLayer(m));
        mapMarkers = [];

        document.getElementById("geoJsonText").innerText = "polygon: [tidak ada data koordinat]";
    }

    /**
     * Mengunci koordinat polygon yang digambar dari modal raksasa ke dalam input form utama
     */
    function simpanDanTutupPeta() {
        if (currentCoords.length > 0 && currentCoords.length < 3) {
            alert("Harap buat minimal 3 titik sudut sawah untuk menghasilkan batas polygon yang valid!");
            return;
        }

        if (currentCoords.length >= 3) {
            const wktPoints = currentCoords.map(coord => `${coord[0].toFixed(6)} ${coord[1].toFixed(6)}`);
            const closedPoint = `${currentCoords[0][0].toFixed(6)} ${currentCoords[0][1].toFixed(6)}`;
            const finalWkt = `POLYGON((${wktPoints.join(', ')}, ${closedPoint}))`;

            document.getElementById("wktCoordinates").value = finalWkt;
            document.getElementById("geoJsonText").innerHTML = `<span class="text-emerald-700 font-extrabold">${finalWkt}</span>`;
            
            // Ubah lencana thumbnail preview di form utama
            const badge = document.getElementById("miniMapBadge");
            badge.className = "z-20 text-[10px] bg-emerald-600 text-white font-extrabold px-2.5 py-0.5 rounded-full uppercase tracking-wider shadow font-sans";
            badge.innerText = "Sawah Tergambar";
        } else {
            document.getElementById("wktCoordinates").value = '';
            document.getElementById("geoJsonText").innerText = "[kosong - belum dipetakan]";
            
            const badge = document.getElementById("miniMapBadge");
            badge.className = "z-20 text-[10px] bg-slate-600 text-white font-extrabold px-2.5 py-0.5 rounded-full uppercase tracking-wider shadow font-sans";
            badge.innerText = "Belum Tergambar";
        }

        tutupModalPeta();
    }

    // --- INTEGRASI PENCARIAN NOMINATIM GEOLOKASI (FREE & GRATIS) ---
    function handleSearchMap(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            searchAddressMap();
        }
    }

    function searchAddressMap() {
        const address = document.getElementById('mapSearchInput').value.trim();
        if (!address) return;

        const helpText = document.getElementById('mapHelpText');
        helpText.innerText = "Mencari lokasi di Jawa Tengah...";

        // Mencari koordinat alamat lewat API Nominatim OpenStreetMap (Gratis & Cepat)
        fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}+Jawa+Tengah`)
            .then(res => res.json())
            .then(data => {
                if (data.length > 0) {
                    const lat = parseFloat(data[0].lat);
                    const lon = parseFloat(data[0].lon);
                    
                    // Arahkan peta Leaflet dan perbesar
                    map.setView([lat, lon], 15);
                    helpText.innerText = `Fokus ke: ${data[0].display_name.split(',')[0]}`;
                } else {
                    helpText.innerText = "Lokasi tidak ditemukan! Coba masukkan kata kunci yang lebih spesifik.";
                }
            })
            .catch(err => {
                console.error("Gagal melakukan pencarian Nominatim:", err);
                helpText.innerText = "Layanan pencarian sedang sibuk. Coba geser peta secara manual.";
            });
    }

    // --- INTEGRASI GPS SMARTPHONE (GEOLOCATION API) ---
    function getUserLocation() {
        const helpText = document.getElementById('mapHelpText');
        
        if (!navigator.geolocation) {
            alert("Perangkat atau browser Anda tidak mendukung fitur pelacakan GPS!");
            return;
        }

        helpText.innerText = "Melacak posisi GPS Anda...";

        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude;
                const lon = position.coords.longitude;

                // Geser peta Leaflet ke posisi pengguna saat ini
                map.setView([lat, lon], 16);
                helpText.innerText = "GPS Terkunci! Sawah siap dipetakan.";

                // Letakkan marker pembantu posisi pengguna
                L.marker([lat, lon]).addTo(map).bindPopup("<b>Lokasi GPS Anda</b>").openPopup();
            },
            function(error) {
                alert("Gagal membaca GPS! Pastikan GPS pada perangkat Anda sudah aktif dan izin lokasi telah disetujui.");
                helpText.innerText = "Gagal mengunci GPS.";
            },
            { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
        );
    }
</script>
