document.addEventListener('DOMContentLoaded', function() {
    const mapElement = document.getElementById('map');
    const modal = document.getElementById('location-modal');
    const pinLocationBtn = document.getElementById('pin-location-btn');
    const useLocationBtn = document.getElementById('use-location-btn');
    const closeBtn = document.querySelector('.close-btn');
    const confirmLocationBtn = document.getElementById('confirm-location-btn');
    const findRestaurantsBtn = document.querySelector('.find-restaurants-btn');

    let map, marker;
    let selectedCoords = null;

    function initMap(lat, lng) {
        if (map) map.remove();
        map = L.map(mapElement).setView([lat, lng], 13);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        marker = L.marker([lat, lng], { draggable: true }).addTo(map);

        map.on('click', function(e) {
            marker.setLatLng(e.latlng);
            selectedCoords = e.latlng;
        });

        marker.on('dragend', function(e) {
            selectedCoords = marker.getLatLng();
        });
    }

    if (pinLocationBtn) {
        pinLocationBtn.addEventListener('click', function() {
            modal.style.display = 'block';
            // Default to a central Majuro location
            initMap(7.09, 171.38);
        });
    }

    if (useLocationBtn) {
        useLocationBtn.addEventListener('click', function() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    const userCoords = { lat: position.coords.latitude, lng: position.coords.longitude };
                    sessionStorage.setItem('userLocation', JSON.stringify(userCoords));
                    findRestaurantsBtn.click();
                }, function() {
                    alert('Could not get your location. Please pin it on the map.');
                });
            } else {
                alert('Geolocation is not supported by this browser.');
            }
        });
    }

    if (closeBtn) {
        closeBtn.addEventListener('click', () => modal.style.display = 'none');
    }

    window.addEventListener('click', (e) => {
        if (e.target == modal) {
            modal.style.display = 'none';
        }
    });

    if (confirmLocationBtn) {
        confirmLocationBtn.addEventListener('click', function() {
            if (selectedCoords) {
                sessionStorage.setItem('userLocation', JSON.stringify(selectedCoords));
                modal.style.display = 'none';
                findRestaurantsBtn.click();
            } else {
                alert('Please select a location on the map.');
            }
        });
    }

    if(findRestaurantsBtn) {
        findRestaurantsBtn.addEventListener('click', function(e) {
            const userLocation = sessionStorage.getItem('userLocation');
            if (!userLocation) {
                e.preventDefault();
                alert('Please set your location first to find restaurants near you.');
                pinLocationBtn.click();
            }
        });
    }
});