<!-- MapLibre GL CSS (only loaded when maplibre provider is selected) -->
@if(trim(env('MAP_PROVIDER', 'leaflet')) == 'maplibre')
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css" />
@endif
<!-- Leaflet CSS (loaded for leaflet provider) -->
@if(trim(env('MAP_PROVIDER', 'leaflet')) == 'leaflet')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
@endif

<script>
// Multi-engine map: Google Maps / Leaflet+OSM / MapLibre GL JS
// Provider is selected from admin panel → MAP_PROVIDER env variable
(function() {
    var map, marker, geocoder, autocomplete;
    var defaultLat = 23.8103, defaultLng = 90.4125; // Dhaka, Bangladesh
    var mapInitialized = false;
    var mapEngine = null; // 'google', 'leaflet', or 'maplibre'
    var mapEl = document.getElementById('checkout_map');
    var searchInput = document.getElementById('map_search_input');
    var hiddenInput = document.getElementById('map_link_input');
    var addressSpan = document.getElementById('map_address_text');
    var addressDiv = document.getElementById('map_selected_address');
    var toggleBtn = document.getElementById('map_toggle_btn');
    var googleLoadTimer = null;

    // Read provider from server-side env
    var MAP_PROVIDER = '{{ trim(env("MAP_PROVIDER", "leaflet")) }}';
    var localDeliveryEnabled = @json($localDeliveryEnabled ?? false);
    var deliveryZones = @json(\App\Models\LocalDeliveryZone::where('is_enabled', 1)->with('points')->get());

    // Toggle map visibility
    window.toggleMap = function() {
        var container = document.getElementById('map_container');
        if (container.style.display === 'none' || container.style.display === '') {
            container.style.display = 'block';
            if (toggleBtn) {
                toggleBtn.innerHTML = '<i class="fa-solid fa-map"></i> ম্যাপ বন্ধ করুন';
                toggleBtn.style.background = '#fff7ed';
                toggleBtn.style.borderColor = '#FF9900';
                toggleBtn.style.color = '#FF9900';
            }
            if (!mapInitialized) {
                loadMap();
            } else if (map) {
                setTimeout(function() {
                    if (mapEngine === 'leaflet') {
                        map.invalidateSize();
                    } else if (mapEngine === 'google') {
                        google.maps.event.trigger(map, 'resize');
                        map.setCenter(new google.maps.LatLng(defaultLat, defaultLng));
                    } else if (mapEngine === 'maplibre') {
                        map.resize();
                    }
                }, 200);
            }
        } else {
            container.style.display = 'none';
            if (toggleBtn) {
                toggleBtn.innerHTML = '<i class="fa-solid fa-map"></i> ম্যাপে দেখুন';
                toggleBtn.style.background = '#fff';
                toggleBtn.style.borderColor = '#d1d5db';
                toggleBtn.style.color = '#333';
            }
        }
    };

    // ==================== GOOGLE MAPS ENGINE ====================
    function initGoogleMap() {
        if (!mapEl || mapInitialized) return;
        mapInitialized = true;
        mapEngine = 'google';

        map = new google.maps.Map(mapEl, {
            center: { lat: defaultLat, lng: defaultLng },
            zoom: 13,
            mapTypeControl: false,
            streetViewControl: false,
            fullscreenControl: false,
            zoomControl: true,
            styles: [{ featureType: "poi", stylers: [{ visibility: "off" }] }]
        });

        geocoder = new google.maps.Geocoder();

        marker = new google.maps.Marker({
            position: { lat: defaultLat, lng: defaultLng },
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP
        });

        map.addListener('click', function(e) {
            marker.setPosition(e.latLng);
            updateHiddenField(e.latLng.lat(), e.latLng.lng());
        });

        marker.addListener('dragend', function() {
            var pos = marker.getPosition();
            updateHiddenField(pos.lat(), pos.lng());
        });

        if (searchInput) {
            autocomplete = new google.maps.places.Autocomplete(searchInput, {
                componentRestrictions: { country: 'bd' },
                fields: ['geometry', 'formatted_address']
            });
            autocomplete.addListener('place_changed', function() {
                var place = autocomplete.getPlace();
                if (place.geometry) {
                    var loc = place.geometry.location;
                    setMarkerGoogle(loc.lat(), loc.lng(), true);
                }
            });
        }

        if (localDeliveryEnabled && typeof deliveryZones !== 'undefined') {
            deliveryZones.forEach(function(zone) {
                new google.maps.Circle({
                    strokeColor: '#ea4335',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#ea4335',
                    fillOpacity: 0.15,
                    map: map,
                    center: { lat: parseFloat(zone.lat), lng: parseFloat(zone.lng) },
                    radius: parseFloat(zone.radius) * 1000
                });
            });
        }

        loadExistingMarker();
    }

    function setMarkerGoogle(lat, lng, fly) {
        var pos = new google.maps.LatLng(lat, lng);
        marker.setPosition(pos);
        if (fly) { map.panTo(pos); map.setZoom(16); }
        else { map.setCenter(pos); map.setZoom(16); }
        updateHiddenField(lat, lng);
    }

    function reverseGeocodeGoogle(lat, lng) {
        geocoder.geocode({ location: { lat: lat, lng: lng } }, function(results, status) {
            if (status === 'OK' && results[0]) {
                addressSpan.textContent = results[0].formatted_address;
                addressDiv.style.display = 'block';
            }
        });
    }

    // ==================== LEAFLET/OSM ENGINE ====================
    function initLeafletMap() {
        if (!mapEl || mapInitialized) return;
        mapInitialized = true;
        mapEngine = 'leaflet';

        map = L.map('checkout_map').setView([defaultLat, defaultLng], 13);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            maxZoom: 19
        }).addTo(map);

        marker = L.marker([defaultLat, defaultLng], { draggable: true }).addTo(map);
        marker.on('dragend', function() {
            var pos = marker.getLatLng();
            updateHiddenField(pos.lat, pos.lng);
        });

        map.on('click', function(e) {
            marker.setLatLng(e.latlng);
            updateHiddenField(e.latlng.lat, e.latlng.lng);
        });

        // Search with Nominatim
        if (searchInput) {
            var searchTimer;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimer);
                var query = this.value.trim();
                if (query.length < 3) return;
                searchTimer = setTimeout(function() {
                    fetch('https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(query + ', Bangladesh') + '&limit=5&accept-language=bn')
                        .then(function(r) { return r.json(); })
                        .then(function(results) {
                            if (results.length > 0) {
                                var r = results[0];
                                setMarkerLeaflet(parseFloat(r.lat), parseFloat(r.lon), true);
                            }
                        }).catch(function() {});
                }, 600);
            });
        }

        if (localDeliveryEnabled && typeof deliveryZones !== 'undefined') {
            deliveryZones.forEach(function(zone) {
                L.circle([parseFloat(zone.lat), parseFloat(zone.lng)], {
                    color: '#ea4335',
                    fillColor: '#ea4335',
                    fillOpacity: 0.15,
                    radius: parseFloat(zone.radius) * 1000
                }).addTo(map);
            });
        }

        setTimeout(function() { map.invalidateSize(); }, 300);
        loadExistingMarker();
    }

    function setMarkerLeaflet(lat, lng, fly) {
        marker.setLatLng([lat, lng]);
        if (fly) { map.flyTo([lat, lng], 16, { duration: 1 }); }
        else { map.setView([lat, lng], 16); }
        updateHiddenField(lat, lng);
    }

    function reverseGeocodeLeaflet(lat, lng) {
        fetch('https://nominatim.openstreetmap.org/reverse?format=json&lat=' + lat + '&lon=' + lng + '&accept-language=bn')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.display_name) {
                    addressSpan.textContent = data.display_name;
                    addressDiv.style.display = 'block';
                }
            }).catch(function() {});
    }

    // ==================== MAPLIBRE GL JS ENGINE ====================
    function initMapLibreMap() {
        if (!mapEl || mapInitialized) return;
        mapInitialized = true;
        mapEngine = 'maplibre';

        var styleUrl = '{{ trim(env("MAPLIBRE_STYLE_URL", "")) }}';
        // Fallback to a free OSM-based style if no style URL configured
        if (!styleUrl) {
            styleUrl = 'https://demotiles.maplibre.org/style.json';
        }

        map = new maplibregl.Map({
            container: 'checkout_map',
            style: styleUrl,
            center: [defaultLng, defaultLat], // [lng, lat] order for MapLibre
            zoom: 13,
            attributionControl: true
        });

        map.addControl(new maplibregl.NavigationControl(), 'top-right');

        // Create a custom marker using a DOM element (since MapLibre doesn't have draggable markers built-in)
        var markerEl = document.createElement('div');
        markerEl.innerHTML = '<div style="width:32px;height:32px;background:#ea4335;border:3px solid #fff;border-radius:50% 50% 50% 0;transform:rotate(-45deg);box-shadow:0 2px 6px rgba(0,0,0,0.3);cursor:grab;"></div>';
        markerEl.style.width = '32px';
        markerEl.style.height = '32px';
        markerEl.style.cursor = 'pointer';

        marker = new maplibregl.Marker({
            element: markerEl,
            draggable: true,
            anchor: 'bottom'
        })
        .setLngLat([defaultLng, defaultLat])
        .addTo(map);

        marker.on('dragend', function() {
            var lngLat = marker.getLngLat();
            updateHiddenField(lngLat.lat, lngLat.lng);
        });

        map.on('click', function(e) {
            marker.setLngLat([e.lngLat.lng, e.lngLat.lat]);
            updateHiddenField(e.lngLat.lat, e.lngLat.lng);
        });

        // Search with Nominatim (same as Leaflet)
        if (searchInput) {
            var searchTimerML;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimerML);
                var query = this.value.trim();
                if (query.length < 3) return;
                searchTimerML = setTimeout(function() {
                    fetch('https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(query + ', Bangladesh') + '&limit=5&accept-language=bn')
                        .then(function(r) { return r.json(); })
                        .then(function(results) {
                            if (results.length > 0) {
                                var r = results[0];
                                setMarkerMapLibre(parseFloat(r.lat), parseFloat(r.lon), true);
                            }
                        }).catch(function() {});
                }, 600);
            });
        }

        map.on('load', function() {
            loadExistingMarker();
        });
    }

    function setMarkerMapLibre(lat, lng, fly) {
        marker.setLngLat([lng, lat]);
        if (fly) {
            map.flyTo({ center: [lng, lat], zoom: 16, duration: 1000 });
        } else {
            map.setCenter([lng, lat]);
            map.setZoom(16);
        }
        updateHiddenField(lat, lng);
    }

    function reverseGeocodeMapLibre(lat, lng) {
        // Use Nominatim for reverse geocoding (same as Leaflet)
        fetch('https://nominatim.openstreetmap.org/reverse?format=json&lat=' + lat + '&lon=' + lng + '&accept-language=bn')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.display_name) {
                    addressSpan.textContent = data.display_name;
                    addressDiv.style.display = 'block';
                }
            }).catch(function() {});
    }

    // ==================== SHARED FUNCTIONS ====================
    function updateHiddenField(lat, lng) {
        var url = 'https://maps.google.com/?q=' + lat.toFixed(7) + ',' + lng.toFixed(7);
        hiddenInput.value = url;
        if (mapEngine === 'google') {
            reverseGeocodeGoogle(lat, lng);
        } else if (mapEngine === 'maplibre') {
            reverseGeocodeMapLibre(lat, lng);
        } else {
            reverseGeocodeLeaflet(lat, lng);
        }
        checkLocalDeliveryZones(lat, lng);
    }

    function checkLocalDeliveryZones(lat, lng) {
        if (!localDeliveryEnabled) return;
        
        var foundZone = null;
        var minDistance = Infinity;
        
        if (typeof deliveryZones !== 'undefined' && deliveryZones.length > 0) {
            for (var i = 0; i < deliveryZones.length; i++) {
                var zone = deliveryZones[i];
                var dist = calculateDistance(lat, lng, parseFloat(zone.lat), parseFloat(zone.lng));
                if (dist <= parseFloat(zone.radius)) {
                    if (dist < minDistance) {
                        minDistance = dist;
                        foundZone = zone;
                    }
                }
            }
        }
        
        var zoneInput = document.getElementById('local_delivery_zone_id');
        var pointInput = document.getElementById('local_delivery_point_id');
        var badge = document.getElementById('detected-zone-badge');
        var badgeName = document.getElementById('detected-zone-name');
        var warning = document.getElementById('out-of-zone-warning');
        var pointSelect = document.getElementById('local_delivery_point_select');
        
        if (foundZone) {
            if (zoneInput) {
                zoneInput.value = foundZone.id;
                $(zoneInput).trigger('change.select2');
            }
            if (badge) badge.classList.remove('d-none');
            if (badgeName) badgeName.innerHTML = '<i class="fa-solid fa-compass text-primary"></i> Detected Zone: <strong>' + foundZone.name + '</strong> (Base: ৳' + foundZone.delivery_charge + ')';
            if (warning) warning.style.display = 'none';
            
            var optionsHtml = '<option value="">-- সাব-লোকেশন নির্বাচন করুন --</option>';
            if (foundZone.points && foundZone.points.length > 0) {
                foundZone.points.forEach(function(pt) {
                    optionsHtml += '<option value="' + pt.id + '" data-extra="' + pt.extra_charge + '">' + pt.name + ' (+ ৳' + pt.extra_charge + ')</option>';
                });
            } else {
                optionsHtml = '<option value="">-- কোনো সাব-লোকেশন নেই --</option>';
            }
            if (pointSelect) {
                pointSelect.innerHTML = optionsHtml;
            }
            
            updateLocalDeliveryCharge();
        } else {
            if (zoneInput) {
                zoneInput.value = '';
                $(zoneInput).trigger('change.select2');
            }
            if (pointInput) pointInput.value = '';
            if (badge) badge.classList.add('d-none');
            if (warning) warning.style.display = 'block';
            if (pointSelect) {
                pointSelect.innerHTML = '<option value="">-- সাব-লোকেশন নির্বাচন করুন --</option>';
            }
            updateTotals(0);
        }
    }
    
    function calculateDistance(lat1, lon1, lat2, lon2) {
        var R = 6371; // Earth radius in km
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var a = 
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
            Math.sin(dLon/2) * Math.sin(dLon/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c;
    }
    
    function updateLocalDeliveryCharge() {
        var zoneInput = document.getElementById('local_delivery_zone_id');
        var pointSelect = document.getElementById('local_delivery_point_select');
        
        if (!zoneInput) return;
        var zoneId = zoneInput.value;
        if (!zoneId) return;
        
        var zone = deliveryZones.find(function(z) { return z.id == zoneId; });
        if (!zone) return;
        
        var baseCharge = parseFloat(zone.delivery_charge) || 0;
        
        var extraCharge = 0;
        if (pointSelect) {
            var selectedOption = pointSelect.options[pointSelect.selectedIndex];
            if (selectedOption && selectedOption.value) {
                extraCharge = parseFloat(selectedOption.getAttribute('data-extra')) || 0;
                document.getElementById('local_delivery_point_id').value = selectedOption.value;
            } else {
                document.getElementById('local_delivery_point_id').value = '';
            }
        }
        
        var totalCharge = baseCharge + extraCharge;
        updateTotals(totalCharge);
        
        $.get('{{ route("shipping.charge") }}', { id: 'local_delivery', amount: totalCharge });
    }
    
    function updateTotals(shippingCharge) {
        var baseSubtotal = parseFloat("{{ $subtotal ?? 0 }}");
        var baseDiscount = parseFloat("{{ $discount ?? 0 }}");
        var grand = baseSubtotal + shippingCharge - baseDiscount;
        $('#shippingAmount').text('৳ ' + shippingCharge.toFixed(2));
        $('#grandTotalAmount').text('৳ ' + grand.toFixed(2));
        if (@json($hasAdvance ?? false)) {
            var advAmt = parseFloat("{{ $advance_amount ?? 0 }}") || 0;
            $('#dueAmountCell').text('৳ ' + (grand - advAmt).toFixed(2));
        }
    }

    function extractCoords(url) {
        var match = url.match(/[?&]q=([-\d.]+),([-\d.]+)/);
        if (match) return { lat: parseFloat(match[1]), lng: parseFloat(match[2]) };
        match = url.match(/@([-\d.]+),([-\d.]+)/);
        if (match) return { lat: parseFloat(match[1]), lng: parseFloat(match[2]) };
        return null;
    }

    function loadExistingMarker() {
        var existingVal = hiddenInput.value;
        if (existingVal) {
            var coords = extractCoords(existingVal);
            if (coords) {
                if (mapEngine === 'google') setMarkerGoogle(coords.lat, coords.lng, true);
                else if (mapEngine === 'maplibre') setMarkerMapLibre(coords.lat, coords.lng, true);
                else setMarkerLeaflet(coords.lat, coords.lng, true);
            }
        }
    }
    window.loadExistingMarker = loadExistingMarker;

    // GPS locate (works with all engines)
    window.locateMeOnMap = function() {
        if (!navigator.geolocation) {
            alert('Geolocation is not supported by this browser.');
            return;
        }
        var btn = document.querySelector('button[onclick="locateMeOnMap()"]');
        var oldHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Locating...';
        btn.disabled = true;
        btn.style.background = '#f0fdf4';
        btn.style.borderColor = '#16a34a';

        navigator.geolocation.getCurrentPosition(function(pos) {
            if (mapEngine === 'google') setMarkerGoogle(pos.coords.latitude, pos.coords.longitude, true);
            else if (mapEngine === 'maplibre') setMarkerMapLibre(pos.coords.latitude, pos.coords.longitude, true);
            else setMarkerLeaflet(pos.coords.latitude, pos.coords.longitude, true);
            btn.innerHTML = '<i class="fa-solid fa-check"></i> Done';
            btn.style.background = '#f0fdf4';
            btn.style.borderColor = '#16a34a';
            btn.style.color = '#16a34a';
            setTimeout(function() {
                btn.innerHTML = oldHtml;
                btn.disabled = false;
                btn.style.background = '#fff';
                btn.style.borderColor = '#d1d5db';
                btn.style.color = '#333';
            }, 2000);
        }, function(err) {
            alert('Unable to detect location. Please search your area or click on the map.');
            btn.innerHTML = oldHtml;
            btn.disabled = false;
            btn.style.background = '#fff';
            btn.style.borderColor = '#d1d5db';
            btn.style.color = '#333';
        }, { timeout: 10000, enableHighAccuracy: true });
    };

    // ==================== MAP LOADER — Provider-based ====================
    function loadMap() {
        if (MAP_PROVIDER === 'google') {
            // Google Maps
            var apiKey = '{{ trim(env("GOOGLE_MAPS_API_KEY", "")) }}';
            if (!apiKey) {
                console.warn('Google Maps API key not configured, falling back to OpenStreetMap');
                initLeafletMap();
                return;
            }

            googleLoadTimer = setTimeout(function() {
                if (!mapInitialized) {
                    console.warn('Google Maps load timed out, falling back to OpenStreetMap');
                    initLeafletMap();
                }
            }, 5000);

            var script = document.createElement('script');
            script.src = 'https://maps.googleapis.com/maps/api/js?key=' + apiKey + '&libraries=places&language=bn&region=BD';
            script.async = true;
            script.defer = true;

            script.onload = function() {
                clearTimeout(googleLoadTimer);
                if (!mapInitialized) {
                    initGoogleMap();
                }
            };

            script.onerror = function() {
                clearTimeout(googleLoadTimer);
                if (!mapInitialized) {
                    console.warn('Google Maps failed to load, falling back to OpenStreetMap');
                    initLeafletMap();
                }
            };

            document.head.appendChild(script);

        } else if (MAP_PROVIDER === 'maplibre') {
            // MapLibre GL JS
            if (typeof maplibregl === 'undefined') {
                // Dynamically load MapLibre GL JS
                var mlScript = document.createElement('script');
                mlScript.src = 'https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js';
                mlScript.async = true;
                mlScript.onload = function() {
                    if (!mapInitialized) initMapLibreMap();
                };
                mlScript.onerror = function() {
                    console.warn('MapLibre GL JS failed to load, falling back to OpenStreetMap');
                    initLeafletMap();
                };
                document.head.appendChild(mlScript);
            } else {
                initMapLibreMap();
            }

        } else {
            // Default: Leaflet + OpenStreetMap
            if (typeof L === 'undefined') {
                var lfScript = document.createElement('script');
                lfScript.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
                lfScript.async = true;
                lfScript.onload = function() {
                    if (!mapInitialized) initLeafletMap();
                };
                lfScript.onerror = function() {
                    console.error('Leaflet failed to load. Map unavailable.');
                };
                document.head.appendChild(lfScript);
            } else {
                initLeafletMap();
            }
        }
    }

    function initListeners() {
        var ptSelect = document.getElementById('local_delivery_point_select');
        if (ptSelect) {
            ptSelect.addEventListener('change', updateLocalDeliveryCharge);
        }

        // jQuery / Select2 change listener for manual local zone select dropdown
        $('#local_delivery_zone_id').on('change', function(e) {
            // Prevent event loops if triggered via map drag namespace
            if (e.namespace === 'select2') return;

            var zoneId = $(this).val();
            if (!zoneId) {
                var ptDropdown = document.getElementById('local_delivery_point_select');
                if (ptDropdown) ptDropdown.innerHTML = '<option value="">-- সাব-লোকেশন নির্বাচন করুন --</option>';
                var ptInput = document.getElementById('local_delivery_point_id');
                if (ptInput) ptInput.value = '';
                updateTotals(0);
                return;
            }

            var zone = deliveryZones.find(function(z) { return z.id == zoneId; });
            if (zone) {
                var lat = parseFloat(zone.lat);
                var lng = parseFloat(zone.lng);

                // Pan the map and position the marker at the center of the chosen zone
                if (mapEngine === 'google') setMarkerGoogle(lat, lng, true);
                else if (mapEngine === 'maplibre') setMarkerMapLibre(lat, lng, true);
                else setMarkerLeaflet(lat, lng, true);

                // Populate sub-location points dropdown
                var optionsHtml = '<option value="">-- সাব-লোকেশন নির্বাচন করুন --</option>';
                if (zone.points && zone.points.length > 0) {
                    zone.points.forEach(function(pt) {
                        optionsHtml += '<option value="' + pt.id + '" data-extra="' + pt.extra_charge + '">' + pt.name + ' (+ ৳' + pt.extra_charge + ')</option>';
                    });
                } else {
                    optionsHtml = '<option value="">-- কোনো সাব-লোকেশন নেই --</option>';
                }

                var ptDropdown = document.getElementById('local_delivery_point_select');
                if (ptDropdown) {
                    ptDropdown.innerHTML = optionsHtml;
                }

                updateLocalDeliveryCharge();
            }
        });

        if (localDeliveryEnabled) {
            setTimeout(function() {
                if (typeof toggleMap === 'function') {
                    toggleMap();
                }
            }, 800);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initListeners);
    } else {
        initListeners();
    }
})();
</script>