let map;
let marker;
let locationModal;
let currentOrderId;

function showNotification(message, type = 'success') {
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    let icon = '✅';
    if (type === 'error') icon = '❌';
    else if (type === 'warning') icon = '⚠️';
    else if (type === 'info') icon = 'ℹ️';
    
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-icon">${icon}</span>
            <span class="notification-message">${message}</span>
        </div>
        <button class="notification-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.classList.add('notification-fade-out');
        setTimeout(() => notification.remove(), 300);
    }, 4000);
}

function initMap() {
    const defaultLocation = [25.3925, 49.5854];
    
    map = L.map('map').setView(defaultLocation, 13);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19
    }).addTo(map);

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

    map.on('click', function(e) {
        updateMarkerPosition(e.latlng);
    });

    marker.on('dragend', function(e) {
        updateMarkerPosition(e.target.getLatLng());
    });
    
    updateAddress(defaultLocation[0], defaultLocation[1]);
}

function updateMarkerPosition(latlng) {
    marker.setLatLng(latlng);
    updateAddress(latlng.lat, latlng.lng);
}

function updateAddress(lat, lng) {
    document.getElementById('selected-address').textContent = `Coordinates: ${lat.toFixed(6)}, ${lng.toFixed(6)}`;
}

function shareLocation(orderId) {
    currentOrderId = orderId;
    showLocationModal();
}

function updateLocation(orderId) {
    currentOrderId = orderId;
    showLocationModal();
}

function showLocationModal() {
    locationModal = document.getElementById('locationModal');
    if (!locationModal) {
        createLocationModal();
    }
    
    locationModal.style.display = 'flex';
    
    setTimeout(() => {
        if (typeof L !== 'undefined') {
            initMap();
        }
        getCurrentLocation();
    }, 100);
}

function createLocationModal() {
    const modalHTML = `
        <div id="locationModal" class="location-modal" style="display: none;">
            <div class="location-modal-content">
                <div class="location-modal-header">
                    <h3><i class="fas fa-map-marker-alt"></i> Select Your Location</h3>
                    <span class="location-modal-close" onclick="closeLocationModal()">&times;</span>
                </div>
                <div class="location-modal-body">
                    <div class="location-instructions">
                        <p>Click on the map or drag the marker to select your exact location</p>
                    </div>
                    <div id="map" class="location-map-container"></div>
                    <div class="selected-location">
                        <strong>Selected Location:</strong>
                        <div id="selected-address">Click on the map to select location</div>
                    </div>
                    <div class="location-actions">
                        <button onclick="getCurrentLocation()" class="location-action-btn secondary">
                            <i class="fas fa-crosshairs"></i> Use Current Location
                        </button>
                        <button onclick="confirmLocation()" class="location-action-btn primary">
                            <i class="fas fa-check"></i> Confirm Location
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    locationModal = document.getElementById('locationModal');
    
    locationModal.addEventListener('click', function(event) {
        if (event.target === locationModal) {
            closeLocationModal();
        }
    });
}

function getCurrentLocation() {
    if (!navigator.geolocation) {
        showNotification('Geolocation is not supported in this browser', 'error');
        return;
    }

    const btn = event?.target;
    if (btn) {
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Getting location...';
        btn.disabled = true;
        
        navigator.geolocation.getCurrentPosition(
            function(position) {
                const userLocation = [position.coords.latitude, position.coords.longitude];
                
                if (map && marker) {
                    map.setView(userLocation, 15);
                    marker.setLatLng(userLocation);
                    updateAddress(userLocation[0], userLocation[1]);
                }
                
                btn.innerHTML = originalText;
                btn.disabled = false;
            },
            function(error) {
                btn.innerHTML = originalText;
                btn.disabled = false;
                
                let errorMessage;
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        errorMessage = 'Permission denied for location access';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMessage = 'Location information unavailable';
                        break;
                    case error.TIMEOUT:
                        errorMessage = 'Location request timeout';
                        break;
                    default:
                        errorMessage = 'An error occurred while determining location';
                        break;
                }
                showNotification(errorMessage, 'error');
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 60000
            }
        );
    }
}

function confirmLocation() {
    if (!marker) {
        showNotification('Please select a location first', 'warning');
        return;
    }
    
    const position = marker.getLatLng();
    const latitude = position.lat;
    const longitude = position.lng;
    const address = `Lat: ${latitude.toFixed(6)}, Lng: ${longitude.toFixed(6)}`;
    
    const confirmBtn = event.target;
    const originalText = confirmBtn.innerHTML;
    confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
    confirmBtn.disabled = true;
    
    sendLocationToServer(currentOrderId, latitude, longitude, address)
        .then(success => {
            if (success) {
                closeLocationModal();
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                confirmBtn.innerHTML = originalText;
                confirmBtn.disabled = false;
            }
        });
}

function sendLocationToServer(orderId, latitude, longitude, address) {
    console.log('Sending location to server:', {
        order_id: orderId,
        latitude: latitude,
        longitude: longitude,
        address: address
    });
    
    return fetch('../php/update_location.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            order_id: orderId,
            latitude: latitude,
            longitude: longitude,
            address: address
        })
    })
    .then(response => {
        console.log('Response status:', response.status);
        
        return response.text().then(text => {
            console.log('Response text:', text);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${text}`);
            }
            
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON parse error:', e);
                throw new Error('Invalid JSON response from server');
            }
        });
    })
    .then(data => {
        console.log('Parsed data:', data);
        
        if (data.success) {
            showNotification('✓ Location updated successfully!', 'success');
            return true;
        } else {
            showNotification('Error: ' + (data.message || 'Unknown error'), 'error');
            return false;
        }
    })
    .catch(error => {
        console.error('Complete Error:', error);
        showNotification('Connection error: ' + error.message, 'error');
        return false;
    });
}

function closeLocationModal() {
    if (locationModal) {
        locationModal.style.display = 'none';
    }
    currentOrderId = null;
}

function loadLeaflet() {
    if (typeof L === 'undefined') {
        const cssLink = document.createElement('link');
        cssLink.rel = 'stylesheet';
        cssLink.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
        cssLink.integrity = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';
        cssLink.crossOrigin = '';
        document.head.appendChild(cssLink);
        
        const script = document.createElement('script');
        script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
        script.integrity = 'sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=';
        script.crossOrigin = '';
        document.head.appendChild(script);
    }
}

document.addEventListener('DOMContentLoaded', function() {
    loadLeaflet();
});
