const DEFAULT_LOCATION = {
    lat: 25.3925,
    lng: 49.5854,
    name: 'Al-Ahsa, Saudi Arabia'
};

let currentLocation = null;
let deliveryMap = null;
let deliveryMarker = null;

function showLocationModal(latitude, longitude, address) {
    const lat = parseFloat(latitude) || DEFAULT_LOCATION.lat;
    const lng = parseFloat(longitude) || DEFAULT_LOCATION.lng;
    const displayAddress = address || DEFAULT_LOCATION.name;
    
    currentLocation = { lat, lng, address: displayAddress };
    
    document.getElementById('locationAddress').innerHTML = displayAddress;
    document.getElementById('locationModal').style.display = 'flex';
    
    const googleMapsUrl = `https://www.google.com/maps?q=${lat},${lng}`;
    const directionsUrl = `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`;
    
    document.getElementById('openGoogleMaps').onclick = () => window.open(googleMapsUrl, '_blank');
    document.getElementById('getDirections').onclick = () => window.open(directionsUrl, '_blank');
    
    setTimeout(() => {
        if (deliveryMap) {
            deliveryMap.remove();
        }
        
        deliveryMap = L.map('locationMap').setView([lat, lng], 15);
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
            maxZoom: 19
        }).addTo(deliveryMap);
        
        deliveryMarker = L.marker([lat, lng]).addTo(deliveryMap);
        deliveryMarker.bindPopup(`<b>Customer Location</b><br>${displayAddress}`).openPopup();
    }, 100);
}

function closeLocationModal() {
    document.getElementById('locationModal').style.display = 'none';
    
    if (deliveryMap) {
        deliveryMap.remove();
        deliveryMap = null;
        deliveryMarker = null;
    }
    
    currentLocation = null;
}

window.onclick = function(event) {
    const modal = document.getElementById('locationModal');
    if (event.target === modal) {
        closeLocationModal();
    }
}
