document.addEventListener('DOMContentLoaded', function() {
    const hamburger = document.querySelector('.hamburger');
    const navLinks = document.querySelector('.nav-links');
    const navActions = document.querySelector('.nav-actions');

    if (hamburger) {
        hamburger.addEventListener('click', () => {
            navLinks.classList.toggle('active');
            navActions.classList.toggle('active');
        });
    }

    // Location Modal
    const locationModal = document.getElementById('location-modal');
    const pinLocationBtn = document.getElementById('pin-location-btn');
    const closeModalBtn = document.querySelector('.close-button');
    const confirmLocationBtn = document.getElementById('confirm-location');
    let map, marker;
    let markerPosition = { lat: 6.9271, lng: 171.1845 }; // Default to Majuro

    function initMap() {
        if (map) {
            map.remove();
        }
        map = L.map('map').setView(markerPosition, 13);
        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);

        marker = L.marker(markerPosition, { draggable: true }).addTo(map);

        marker.on('dragend', function(event) {
            const position = marker.getLatLng();
            markerPosition = { lat: position.lat, lng: position.lng };
        });
    }

    if (pinLocationBtn) {
        pinLocationBtn.addEventListener('click', () => {
            locationModal.style.display = 'block';
            // Invalidate map size on modal open to ensure it renders correctly
            setTimeout(initMap, 10);
        });
    }

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

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

    if (confirmLocationBtn) {
        confirmLocationBtn.addEventListener('click', () => {
            sessionStorage.setItem('user_latitude', markerPosition.lat);
            sessionStorage.setItem('user_longitude', markerPosition.lng);
            locationModal.style.display = 'none';
            // Optional: Update UI to show location is set
            pinLocationBtn.textContent = 'Location Set!';
            pinLocationBtn.style.backgroundColor = '#28a745';
        });
    }
});
