<!DOCTYPE html>
<html lang="<?php echo e(str_replace('_', '-', app()->getLocale())); ?>">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo e(config('app.name', 'Laravel')); ?></title>

    <!-- Proj4js for coordinate transformation -->
    <!-- Proj4js for coordinate transformation -->
    <script src="https://cdn.jsdelivr.net/npm/proj4@2.9.2/dist/proj4.min.js"></script>

    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=inter:400,500,600,700&display=swap" rel="stylesheet" />

    <!-- Tailwind CSS (via CDN for simplicity if build not run) -->
    <script src="https://cdn.tailwindcss.com"></script>

    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        #map {
            height: 100vh;
            width: 100%;
            z-index: 10;
        }

        .leaflet-popup-content-wrapper {
            border-radius: 0.5rem;
            padding: 0;
            overflow: hidden;
        }

        .leaflet-popup-content {
            margin: 0;
            width: 300px !important;
        }

        .custom-popup .image-cover {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }

        .custom-popup .content {
            padding: 1rem;
        }

        .custom-popup h3 {
            font-size: 1.125rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #1f2937;
        }

        .custom-popup p {
            font-size: 0.875rem;
            color: #4b5563;
            margin-bottom: 0.25rem;
        }

        .custom-popup .badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-red {
            background-color: #fee2e2;
            color: #991b1b;
        }

        .badge-green {
            background-color: #dcfce7;
            color: #166534;
        }

        .badge-blue {
            background-color: #dbeafe;
            color: #1e40af;
        }

        /* Search Styles */
        #search-results {
            max-height: 200px;
            overflow-y: auto;
            position: absolute;
            width: 100%;
            top: 100%;
            left: 0;
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            border: 1px solid #f3f4f6;
            display: none;
            z-index: 1001;
        }

        .search-item {
            padding: 0.75rem 1rem;
            cursor: pointer;
            border-bottom: 1px solid #f9fafb;
            transition: background-color 0.2s;
        }

        .search-item:last-child {
            border-bottom: none;
        }

        .search-item:hover {
            background-color: #f3f4f6;
        }

        .search-item .type {
            font-size: 0.7rem;
            text-transform: uppercase;
            font-weight: 600;
            color: #6b7280;
        }

        .search-item .name {
            font-size: 0.875rem;
            font-weight: 500;
            color: #111827;
            display: block;
        }
    </style>
</head>

<body class="antialiased overflow-hidden">

    <div class="relative w-full h-screen">
        <!-- Sidebar / Overlay optional -->
        <div class="absolute top-4 left-4 z-[1000] bg-white p-4 rounded-lg shadow-lg border border-gray-100 max-w-sm">
            <h1 class="text-xl font-bold text-gray-800 mb-2">GIS Data Map</h1>
            <p class="text-sm text-gray-500 mb-4">Lihat Lokasi, Jalan.</p>

            <!-- Search Section -->
            <div class="relative mb-6">
                <div class="relative">
                    <input type="text" id="map-search" placeholder="Search roads or locations..."
                        class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all">
                    <div class="absolute left-3 top-2.5 text-gray-400">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24"
                            stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                        </svg>
                    </div>
                </div>
                <div id="search-results"></div>
            </div>

            <div class="flex flex-col gap-2">
                <div class="flex items-center gap-2">
                    <span class="w-3 h-3 rounded-full bg-green-500"></span> <span class="text-sm">Tempat Ibadah</span>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-3 h-3 rounded-full bg-blue-500"></span> <span class="text-sm">Sekolah</span>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-3 h-3 rounded-full bg-yellow-500"></span> <span class="text-sm">Rumah Sakit /
                        Puskesmas</span>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-8 h-1" style="background-color: #00FF00;"></span> <span class="text-sm">Jalan
                        Mantap</span>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-8 h-1" style="background-color: #FFFF00;"></span> <span class="text-sm">Jalan
                        Sedang</span>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-8 h-1" style="background-color: #FF0000;"></span> <span class="text-sm">Jalan
                        Rusak</span>
                </div>
                <div id="stunting-toggle"
                    class="flex items-center gap-2 cursor-pointer hover:bg-gray-50 p-1 rounded transition-colors">
                    <span class="w-4 h-4 border border-red-500 bg-red-500/20"></span> <span class="text-sm">Stunting
                        Areas (Click to toggle)</span>
                </div>
            </div>
        </div>

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

    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Initialize Map
            var map = L.map('map').setView([0.36528984159492117, 108.95468836979174], 10); // Default mempawah, adjust as needed
            var searchData = []; // Array to store searchable items
            var searchInput = document.getElementById('map-search');
            var searchResults = document.getElementById('search-results');

            var stuntingLayerGroup = L.layerGroup().addTo(map);

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

            // Function to wait for Proj4 to load
            function initBoundaries() {
                if (typeof proj4 === 'undefined') {
                    console.warn('Proj4 not ready yet, retrying...');
                    setTimeout(initBoundaries, 500);
                    return;
                }

                console.log('Proj4 loaded successfully');
                proj4.defs('EPSG:32649', '+proj=utm +zone=49 +datum=WGS84 +units=m +no_defs');

                // Fetch and display territorial boundaries
                console.log('Fetching boundaries from /batas-kecamatan.json');
                fetch('/batas-kecamatan.json')
                    .then(response => {
                        console.log('Boundary response status:', response.status);
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.text();
                    })
                    .then(text => {
                        console.log('Raw JSON length:', text.length);
                        const data = JSON.parse(text);
                        console.log('Boundary data loaded successfully');

                        L.geoJSON(data, {
                            coordsToLatLng: function (coords) {
                                return proj4('EPSG:32649', 'EPSG:4326', coords).reverse();
                            },
                            style: function (feature) {
                                return {
                                    color: '#3600f8ff',
                                    weight: 2,
                                    opacity: 0.7,
                                    fillOpacity: 0.1
                                };
                            },
                            onEachFeature: function (feature, layer) {
                                layer.bindPopup(`<strong>Batas Wilayah Mempawah</strong><br>ID: ${feature.id}`);
                            }
                        }).addTo(map);

                        console.log('Boundaries added to map successfully');
                    })
                    .catch(error => {
                        console.error('Error loading boundaries:', error);
                    });
            }

            // Start initialization
            initBoundaries();

            // Fetch and display Locations
            fetch('/api/locations')
                .then(response => response.json())
                .then(data => {
                    data.forEach(location => {
                        let markerColor = 'yellow';
                        if (location.type === 'mosque') markerColor = 'green';
                        else if (location.type === 'school') markerColor = 'blue';

                        let badgeClass = markerColor === 'green' ? 'badge-green' : (markerColor === 'blue' ? 'badge-blue' : 'bg-yellow-100 text-yellow-800');

                        let content = `
                            <div class="custom-popup">
                                ${location.photo_path ? `<img src="/storage/${location.photo_path}" class="image-cover" alt="${location.name}">` : '<div class="h-32 bg-gray-200 flex items-center justify-center text-gray-400">No Image</div>'}
                                <div class="content">
                                    <h3>${location.name}</h3>
                                    <span class="badge ${badgeClass} mb-2">${location.type === 'mosque' ? 'Tempat Ibadah' : location.type === 'school' ? 'Sekolah' : location.type === 'hospital' ? 'Rumah Sakit' : 'Puskesmas'}</span>
                                    <p><strong>Year:</strong> ${location.year_data}</p>
                                    <p><strong>Condition:</strong> ${location.building_condition}</p>
                                    ${location.number_of_students ? `<p><strong>Students:</strong> ${location.number_of_students}</p>` : ''}
                                </div>
                            </div>
                        `;

                        let marker = L.circleMarker([location.latitude, location.longitude], {
                            radius: 8,
                            fillColor: markerColor,
                            color: "#fff",
                            weight: 2,
                            opacity: 1,
                            fillOpacity: 0.8
                        })
                            .addTo(map)
                            .bindPopup(content);

                        // Add to search data
                        searchData.push({
                            name: location.name,
                            type: location.type,
                            layer: marker,
                            coords: [location.latitude, location.longitude],
                            popupContent: content
                        });
                    });
                });

            // Fetch and display Roads
            fetch('/api/roads')
                .then(response => response.json())
                .then(data => {
                    data.forEach(road => {
                        let color = road.condition === 'Good' ? 'green' : (road.condition === 'Bad' ? 'red' : 'orange');
                        try {
                            // Robust coordinate parsing
                            let coords = road.coordinates;
                            if (typeof coords === 'string') {
                                try {
                                    coords = JSON.parse(coords);
                                } catch (e) {
                                    console.error('Failed to parse road coordinates for:', road.name, e);
                                    return;
                                }
                            }

                            if (!Array.isArray(coords)) {
                                console.error('Road coordinates are not an array for:', road.name);
                                return;
                            }

                            let content = `
                                <div class="custom-popup">
                                    ${road.photo_path ? `<img src="/storage/${road.photo_path}" class="image-cover" alt="${road.name}">` : '<div class="h-32 bg-gray-200 flex items-center justify-center text-gray-400">No Image</div>'}
                                    <div class="content">
                                        <h3>${road.name}</h3>
                                        <p><strong>Length:</strong> ${road.length_meters} m</p>
                                        <p><strong>Condition:</strong> ${road.condition}</p>
                                        <p><strong>Year:</strong> ${road.year_data}</p>
                                    </div>
                                </div>
                            `;

                            let roadLayer = L.polyline(coords, { color: color, weight: 5 })
                                .addTo(map)
                                .bindPopup(content);

                            // Add to search data
                            searchData.push({
                                name: road.name,
                                type: 'Road',
                                layer: roadLayer,
                                coords: coords[0], // Use first coordinate to pan to
                                popupContent: content
                            });
                        } catch (e) {
                            console.error('Error parsing road coordinates:', e);
                        }
                    });
                });

            // Fetch and display Village Polygons (Stunting)
            fetch('/api/villages')
                .then(response => response.json())
                .then(data => {
                    data.forEach(village => {
                        try {
                            let geometry = typeof village.coordinates === 'string' ? JSON.parse(village.coordinates) : village.coordinates;

                            if (!geometry) return;

                            let stunting = village.stunting;
                            let detail = stunting ? stunting.latest_detail : null;

                            // Determine color based on stunting percentage
                            let color = '#3b82f6'; // Default blue
                            if (detail) {
                                if (detail.percentage > 20) color = '#ef4444'; // High - Red
                                else if (detail.percentage > 10) color = '#f97316'; // Medium - Orange
                                else color = '#eab308'; // Low - Yellow
                            }

                            let content = `
                                <div class="custom-popup">
                                    <div class="p-4">
                                        <h3 class="text-lg font-bold mb-2">${village.name}</h3>
                                        <div class="space-y-2">
                                            <p class="text-sm"><strong>Data Stunting ${detail ? detail.year : ''}</strong></p>
                                            ${detail ? `
                                                <div class="grid grid-cols-2 gap-2 text-xs">
                                                    <div class="bg-gray-100 p-2 rounded">
                                                        <span class="block text-gray-500">Diukur</span>
                                                        <span class="font-bold">${detail.measured}</span>
                                                    </div>
                                                    <div class="bg-gray-100 p-2 rounded">
                                                        <span class="block text-gray-500">Stunting</span>
                                                        <span class="font-bold text-red-600">${detail.stunted}</span>
                                                    </div>
                                                </div>
                                                <div class="mt-2">
                                                    <span class="text-sm font-bold">Presentase: ${detail.percentage}%</span>
                                                    <div class="w-full bg-gray-200 rounded-full h-2 mt-1">
                                                        <div class="bg-red-500 h-2 rounded-full" style="width: ${detail.percentage}%"></div>
                                                    </div>
                                                </div>
                                            ` : '<p class="text-xs text-gray-400">Belum ada data stunting</p>'}
                                        </div>
                                    </div>
                                </div>
                            `;

                            let layer = L.geoJSON({
                                type: "Feature",
                                geometry: geometry
                            }, {
                                style: {
                                    color: color,
                                    fillColor: color,
                                    fillOpacity: 0.3,
                                    weight: 2
                                },
                                onEachFeature: function (feature, layer) {
                                    layer.bindPopup(content);
                                }
                            }).addTo(stuntingLayerGroup);

                            // Add to search data
                            if (geometry.type === "Point") {
                                searchData.push({
                                    name: village.name,
                                    type: 'Desa',
                                    coords: [geometry.coordinates[1], geometry.coordinates[0]],
                                    layer: layer
                                });
                            } else if (geometry.type === "Polygon" || geometry.type === "MultiPolygon") {
                                // For polygons, use the first point to zoom to
                                let firstCoord = geometry.type === "Polygon"
                                    ? geometry.coordinates[0][0]
                                    : geometry.coordinates[0][0][0];
                                searchData.push({
                                    name: village.name,
                                    type: 'Desa',
                                    coords: [firstCoord[1], firstCoord[0]],
                                    layer: layer
                                });
                            }
                        } catch (e) {
                            console.error('Error rendering village:', village.name, e);
                        }
                    });
                });

            // Toggle for Stunting Layer
            const stuntingToggle = document.getElementById('stunting-toggle');
            let stuntingVisible = true;
            stuntingToggle.addEventListener('click', function () {
                if (stuntingVisible) {
                    map.removeLayer(stuntingLayerGroup);
                    stuntingToggle.style.opacity = '0.5';
                } else {
                    map.addLayer(stuntingLayerGroup);
                    stuntingToggle.style.opacity = '1';
                }
                stuntingVisible = !stuntingVisible;
            });

            // Search Functionality
            searchInput.addEventListener('input', function (e) {
                var query = e.target.value.toLowerCase();
                searchResults.innerHTML = '';

                if (query.length < 2) {
                    searchResults.style.display = 'none';
                    return;
                }

                var filtered = searchData.filter(item =>
                    item.name.toLowerCase().includes(query)
                ).slice(0, 10); // Limit results

                if (filtered.length > 0) {
                    filtered.forEach(item => {
                        var div = document.createElement('div');
                        div.className = 'search-item';
                        div.innerHTML = `
                            <span class="type">${item.type}</span>
                            <span class="name">${item.name}</span>
                        `;
                        div.onclick = function () {
                            map.setView(item.coords, 15);
                            if (item.layer) {
                                item.layer.openPopup();
                            }
                            searchResults.style.display = 'none';
                            searchInput.value = item.name;
                        };
                        searchResults.appendChild(div);
                    });
                    searchResults.style.display = 'block';
                } else {
                    searchResults.style.display = 'none';
                }
            });

            // Close search results when clicking outside
            document.addEventListener('click', function (e) {
                if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
                    searchResults.style.display = 'none';
                }
            });
        });
    </script>
</body>

</html><?php /**PATH D:\laragon\www\filammaps\resources\views/map.blade.php ENDPATH**/ ?>