// GPS and Map functionality for visits
class VisitMap {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        this.map = null;
        this.markers = [];
        this.options = {
            zoom: 12,
            ...options
        };
        
        if (this.container) {
            this.init();
        }
    }

    async init() {
        await this.loadOpenStreetMap();
        this.initGeolocation();
    }

    loadOpenStreetMap() {
        return new Promise((resolve) => {
            // OpenStreetMap doesn't require API key
            this.map = L.map(this.container).setView([30.0444, 31.2357], this.options.zoom); // Default to Cairo
            
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(this.map);
            
            resolve();
        });
    }

    initGeolocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const { latitude, longitude } = position.coords;
                    this.map.setView([latitude, longitude], this.options.zoom);
                    this.addMarker([latitude, longitude], 'Your Location', 'blue');
                },
                (error) => {
                    console.warn('Geolocation failed:', error);
                    this.showNotification('Unable to get your location. Using default map view.', 'warning');
                }
            );
        }
    }

    addMarker(coords, title = '', color = 'red') {
        const icon = L.divIcon({
            html: `<div class="w-6 h-6 bg-${color}-500 rounded-full border-2 border-white shadow-lg"></div>`,
            className: 'custom-marker',
            iconSize: [24, 24],
            iconAnchor: [12, 12]
        });

        const marker = L.marker(coords, { icon })
            .addTo(this.map)
            .bindPopup(title);

        this.markers.push(marker);
        return marker;
    }

    addVisitMarker(coords, clientName, visitDetails) {
        const marker = this.addMarker(coords, clientName, 'purple');
        marker.bindPopup(`
            <div class="p-2">
                <h3 class="font-bold text-lg">${clientName}</h3>
                <p class="text-sm text-gray-600">${visitDetails}</p>
                <button onclick="startVisitFromMap(${coords[0]}, ${coords[1]})" 
                        class="mt-2 bg-primary-600 text-white px-3 py-1 rounded text-sm">
                    Start Visit
                </button>
            </div>
        `);
        return marker;
    }

    clearMarkers() {
        this.markers.forEach(marker => {
            this.map.removeLayer(marker);
        });
        this.markers = [];
    }

    getCurrentLocation() {
        return new Promise((resolve, reject) => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        resolve({
                            latitude: position.coords.latitude,
                            longitude: position.coords.longitude
                        });
                    },
                    (error) => {
                        reject(error);
                    }
                );
            } else {
                reject(new Error('Geolocation is not supported by this browser.'));
            }
        });
    }

    calculateDistance(lat1, lon1, lat2, lon2) {
        const R = 6371; // Earth's radius in kilometers
        const dLat = this.deg2rad(lat2 - lat1);
        const dLon = this.deg2rad(lon2 - lon1);
        
        const a = 
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2);
        
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
        const distance = R * c; // Distance in kilometers
        
        return distance;
    }

    deg2rad(deg) {
        return deg * (Math.PI/180);
    }
}

// Global function to start visit from map
function startVisitFromMap(latitude, longitude) {
    if (window.InnovaxcessApp) {
        window.InnovaxcessApp.showNotification('Starting visit at selected location...', 'info');
    }
    // This would typically make an AJAX call to start the visit
    console.log('Starting visit at:', latitude, longitude);
}

// Initialize map when needed
function initVisitMap(containerId, options = {}) {
    return new VisitMap(containerId, options);
}