@extends('layouts.dashboard')

@section('title', 'GPS Tracker - ' . $visit->client->name)

@section('content')
<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <a href="{{ route('visits.show', $visit) }}" 
               class="text-primary-600 hover:text-primary-700 transition-colors duration-200 inline-flex items-center mb-2">
                <i class="fas fa-arrow-left mr-2"></i> Back to Visit
            </a>
            <h1 class="text-2xl font-bold text-gray-800">GPS Tracker</h1>
            <p class="text-gray-600 mt-1">Real-time tracking for {{ $visit->client->name }}</p>
        </div>
        <div class="flex items-center space-x-3">
            <div id="connectionStatus" class="flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800">
                <i class="fas fa-wifi mr-1"></i> Connecting...
            </div>
            <div id="gpsStatus" class="flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800">
                <i class="fas fa-satellite mr-1"></i> GPS: Off
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Map -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-blue-50 to-indigo-100">
                    <h2 class="text-lg font-semibold text-gray-800">Live Tracking Map</h2>
                    <p class="text-sm text-gray-600 mt-1">Real-time position tracking</p>
                </div>
                <div class="p-4">
                    <div id="trackerMap" class="h-[500px] rounded-lg border border-gray-300"></div>
                </div>
            </div>
        </div>

        <!-- Tracking Info -->
        <div class="space-y-6">
            <!-- Visit Info Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">Visit Information</h2>
                <div class="space-y-3">
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">Client:</span>
                        <span class="font-medium text-gray-900">{{ $visit->client->name }}</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">Employee:</span>
                        <span class="font-medium text-gray-900">{{ $visit->employee->name }}</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">Status:</span>
                        @php
                            $statusColors = [
                                'scheduled' => 'bg-yellow-100 text-yellow-800',
                                'in_progress' => 'bg-blue-100 text-blue-800',
                                'completed' => 'bg-green-100 text-green-800'
                            ];
                        @endphp
                        <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium {{ $statusColors[$visit->status] }}">
                            {{ str_replace('_', ' ', ucfirst($visit->status)) }}
                        </span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">Started:</span>
                        <span class="font-medium text-gray-900">{{ $visit->started_at ? $visit->started_at->format('H:i') : 'Not started' }}</span>
                    </div>
                    @if($visit->status == 'in_progress')
                    <div class="mt-4">
                        <button id="autoCompleteBtn" 
                                class="w-full btn-primary"
                                onclick="attemptAutoComplete()">
                            <i class="fas fa-check-circle mr-2"></i> Auto-Complete Visit
                        </button>
                    </div>
                    @endif
                </div>
            </div>

            <!-- Live Stats Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">Live Tracking Stats</h2>
                <div class="space-y-4">
                    <div class="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center mr-3">
                                <i class="fas fa-ruler text-blue-600"></i>
                            </div>
                            <span class="text-sm font-medium text-gray-700">Distance to Client</span>
                        </div>
                        <span id="distanceToClient" class="text-xl font-bold text-blue-600">-- m</span>
                    </div>
                    
                    <div class="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center mr-3">
                                <i class="fas fa-tachometer-alt text-green-600"></i>
                            </div>
                            <span class="text-sm font-medium text-gray-700">Speed</span>
                        </div>
                        <span id="currentSpeed" class="text-xl font-bold text-green-600">-- km/h</span>
                    </div>
                    
                    <div class="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full bg-purple-100 flex items-center justify-center mr-3">
                                <i class="fas fa-satellite text-purple-600"></i>
                            </div>
                            <span class="text-sm font-medium text-gray-700">Accuracy</span>
                        </div>
                        <span id="gpsAccuracy" class="text-xl font-bold text-purple-600">-- m</span>
                    </div>
                    
                    <div class="flex items-center justify-between p-3 bg-yellow-50 rounded-lg">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full bg-yellow-100 flex items-center justify-center mr-3">
                                <i class="fas fa-history text-yellow-600"></i>
                            </div>
                            <span class="text-sm font-medium text-gray-700">Last Update</span>
                        </div>
                        <span id="lastUpdate" class="text-sm font-bold text-yellow-600">--</span>
                    </div>
                </div>
            </div>

            <!-- Controls Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">Tracking Controls</h2>
                <div class="space-y-3">
                    <button id="startTrackingBtn" 
                            class="w-full btn-primary"
                            onclick="startTracking()">
                        <i class="fas fa-play-circle mr-2"></i> Start Tracking
                    </button>
                    
                    <button id="stopTrackingBtn" 
                            class="w-full btn-secondary hidden"
                            onclick="stopTracking()">
                        <i class="fas fa-stop-circle mr-2"></i> Stop Tracking
                    </button>
                    
                    <button onclick="centerOnEmployee()" 
                            class="w-full btn-secondary">
                        <i class="fas fa-location-arrow mr-2"></i> Center on Employee
                    </button>
                    
                    <button onclick="showRouteHistory()" 
                            class="w-full btn-secondary">
                        <i class="fas fa-route mr-2"></i> View Route History
                    </button>
                    
                    <div class="pt-4 border-t border-gray-200">
                        <label class="flex items-center">
                            <input type="checkbox" id="autoCenter" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500" checked>
                            <span class="ml-2 text-sm text-gray-700">Auto-center map</span>
                        </label>
                        <label class="flex items-center mt-2">
                            <input type="checkbox" id="showRoute" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500" checked>
                            <span class="ml-2 text-sm text-gray-700">Show route line</span>
                        </label>
                        <label class="flex items-center mt-2">
                            <input type="checkbox" id="highAccuracy" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                            <span class="ml-2 text-sm text-gray-700">High accuracy GPS</span>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Route History Modal -->
    <div id="routeModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-xl bg-white">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-800">Route History</h3>
                <button onclick="closeRouteModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="routeMap" class="h-96 rounded-lg border border-gray-300 mb-4"></div>
            <div class="flex justify-between items-center">
                <div class="text-sm text-gray-600">
                    <i class="fas fa-route mr-1"></i>
                    <span id="routePoints">0</span> tracking points
                </div>
                <div class="flex space-x-2">
                    <button onclick="clearRouteHistory()" class="btn-secondary">
                        <i class="fas fa-trash mr-2"></i> Clear History
                    </button>
                    <button onclick="closeRouteModal()" class="btn-primary">
                        Close
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Leaflet JS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-polylinedecorator@1.6.0/dist/leaflet.polylineDecorator.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-polylinedecorator@1.6.0/dist/leaflet.polylineDecorator.js"></script>

<!-- Leaflet Plugins -->
<link rel="stylesheet" href="https://unpkg.com/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.css" />
<script src="https://unpkg.com/leaflet.locatecontrol@0.79.0/dist/L.Control.Locate.min.js"></script>

<script>
let map = null;
let routeMap = null;
let employeeMarker = null;
let clientMarker = null;
let routeLine = null;
let routeDecorator = null;
let locationHistory = [];
let watchId = null;
let updateInterval = null;
let lastLocation = null;

const visitId = {{ $visit->id }};
const clientLocation = {
    lat: {{ $visit->latitude }},
    lng: {{ $visit->longitude }},
    name: "{{ $visit->client->name }}"
};

// Initialize main map
function initMap() {
    map = L.map('trackerMap').setView([30.0444, 31.2357], 12);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    
    // Add locate control
    L.control.locate({
        position: 'topright',
        strings: {
            title: "My location"
        }
    }).addTo(map);
    
    // Add client marker
    clientMarker = L.marker([clientLocation.lat, clientLocation.lng])
        .addTo(map)
        .bindPopup(`<b>${clientLocation.name}</b><br>Client Location`)
        .openPopup();
    
    // Add client circle (100m range)
    L.circle([clientLocation.lat, clientLocation.lng], {
        color: 'green',
        fillColor: '#00ff00',
        fillOpacity: 0.1,
        radius: 100
    }).addTo(map).bindPopup('100m range from client');
    
    // Load existing route history
    loadRouteHistory();
}

// Initialize route map
function initRouteMap() {
    routeMap = L.map('routeMap').setView([clientLocation.lat, clientLocation.lng], 13);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(routeMap);
    
    // Add client marker to route map
    L.marker([clientLocation.lat, clientLocation.lng], {
        icon: L.divIcon({
            html: '<div class="w-8 h-8 bg-green-500 rounded-full border-2 border-white shadow-lg flex items-center justify-center"><i class="fas fa-handshake text-white"></i></div>',
            className: 'client-marker',
            iconSize: [32, 32],
            iconAnchor: [16, 16]
        })
    }).addTo(routeMap).bindPopup(`<b>${clientLocation.name}</b><br>Client Location`);
}

// Load route history from server
async function loadRouteHistory() {
    try {
        const response = await fetch(`/visits/${visitId}/route-history`);
        const data = await response.json();
        
        locationHistory = data.route || [];
        
        if (locationHistory.length > 0) {
            lastLocation = locationHistory[locationHistory.length - 1];
            updateEmployeeMarker(lastLocation);
            drawRouteLine();
            updateStats(lastLocation);
        }
        
        updateConnectionStatus(true);
    } catch (error) {
        console.error('Error loading route history:', error);
        updateConnectionStatus(false);
    }
}

// Update employee marker on map
function updateEmployeeMarker(location) {
    if (!location || !location.latitude || !location.longitude) return;
    
    const lat = location.latitude;
    const lng = location.longitude;
    
    if (!employeeMarker) {
        employeeMarker = L.marker([lat, lng], {
            icon: L.divIcon({
                html: '<div class="w-10 h-10 bg-blue-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center"><i class="fas fa-user text-white"></i></div>',
                className: 'employee-marker',
                iconSize: [40, 40],
                iconAnchor: [20, 20]
            }),
            zIndexOffset: 1000
        }).addTo(map);
    } else {
        employeeMarker.setLatLng([lat, lng]);
    }
    
    // Update heading arrow if available
    if (location.heading !== undefined) {
        employeeMarker.setIcon(L.divIcon({
            html: `<div class="w-10 h-10 bg-blue-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center" style="transform: rotate(${location.heading}deg);">
                      <i class="fas fa-arrow-up text-white"></i>
                   </div>`,
            className: 'employee-marker',
            iconSize: [40, 40],
            iconAnchor: [20, 20]
        }));
    }
    
    // Auto-center map if enabled
    if (document.getElementById('autoCenter').checked) {
        map.setView([lat, lng], 15);
    }
    
    // Calculate distance to client
    calculateDistanceToClient(lat, lng);
}

// Draw route line on map
function drawRouteLine() {
    if (locationHistory.length < 2) return;
    
    const points = locationHistory.map(loc => [loc.latitude, loc.longitude]);
    
    // Remove existing route line
    if (routeLine) {
        map.removeLayer(routeLine);
        if (routeDecorator) map.removeLayer(routeDecorator);
    }
    
    // Draw new route line
    routeLine = L.polyline(points, {
        color: '#3b82f6',
        weight: 3,
        opacity: 0.7,
        lineJoin: 'round'
    }).addTo(map);
    
    // Add direction arrows
    routeDecorator = L.polylineDecorator(routeLine, {
        patterns: [
            {
                offset: 25,
                repeat: 50,
                symbol: L.Symbol.arrowHead({
                    pixelSize: 15,
                    pathOptions: {
                        fillOpacity: 1,
                        weight: 0,
                        color: '#1d4ed8'
                    }
                })
            }
        ]
    }).addTo(map);
    
    // Only show if checkbox is checked
    if (!document.getElementById('showRoute').checked) {
        map.removeLayer(routeLine);
        map.removeLayer(routeDecorator);
    }
}

// Calculate distance to client
function calculateDistanceToClient(lat, lng) {
    const R = 6371; // Earth's radius in kilometers
    const dLat = (clientLocation.lat - lat) * Math.PI / 180;
    const dLon = (clientLocation.lng - lng) * Math.PI / 180;
    const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat * Math.PI / 180) * Math.cos(clientLocation.lat * Math.PI / 180) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const distanceKm = R * c;
    const distanceM = distanceKm * 1000;
    
    document.getElementById('distanceToClient').textContent = Math.round(distanceM) + ' m';
    
    // Update color based on distance
    const distanceElement = document.getElementById('distanceToClient');
    if (distanceM <= 100) {
        distanceElement.className = 'text-xl font-bold text-green-600';
    } else if (distanceM <= 500) {
        distanceElement.className = 'text-xl font-bold text-yellow-600';
    } else {
        distanceElement.className = 'text-xl font-bold text-red-600';
    }
}

// Update stats display
function updateStats(location) {
    if (location.speed !== undefined) {
        document.getElementById('currentSpeed').textContent = 
            Math.round(location.speed * 3.6) + ' km/h';
    }
    
    if (location.accuracy !== undefined) {
        document.getElementById('gpsAccuracy').textContent = 
            Math.round(location.accuracy) + ' m';
        
        const accuracyElement = document.getElementById('gpsAccuracy');
        if (location.accuracy <= 10) {
            accuracyElement.className = 'text-xl font-bold text-green-600';
        } else if (location.accuracy <= 50) {
            accuracyElement.className = 'text-xl font-bold text-yellow-600';
        } else {
            accuracyElement.className = 'text-xl font-bold text-red-600';
        }
    }
    
    document.getElementById('lastUpdate').textContent = 
        new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
}

// Start GPS tracking
function startTracking() {
    if (!navigator.geolocation) {
        alert('Geolocation is not supported by your browser');
        return;
    }
    
    const options = {
        enableHighAccuracy: document.getElementById('highAccuracy').checked,
        timeout: 5000,
        maximumAge: 0
    };
    
    // Update UI
    document.getElementById('startTrackingBtn').classList.add('hidden');
    document.getElementById('stopTrackingBtn').classList.remove('hidden');
    document.getElementById('gpsStatus').className = 
        'flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800';
    document.getElementById('gpsStatus').innerHTML = '<i class="fas fa-satellite mr-1"></i> GPS: Active';
    
    // Start watching position
    watchId = navigator.geolocation.watchPosition(
        (position) => handlePositionUpdate(position),
        (error) => handleGeolocationError(error),
        options
    );
    
    // Start periodic updates to server
    updateInterval = setInterval(sendLocationUpdate, 5000);
}

// Stop GPS tracking
function stopTracking() {
    if (watchId) {
        navigator.geolocation.clearWatch(watchId);
        watchId = null;
    }
    
    if (updateInterval) {
        clearInterval(updateInterval);
        updateInterval = null;
    }
    
    // Update UI
    document.getElementById('startTrackingBtn').classList.remove('hidden');
    document.getElementById('stopTrackingBtn').classList.add('hidden');
    document.getElementById('gpsStatus').className = 
        'flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800';
    document.getElementById('gpsStatus').innerHTML = '<i class="fas fa-satellite mr-1"></i> GPS: Off';
}

// Handle position updates
function handlePositionUpdate(position) {
    const location = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        accuracy: position.coords.accuracy,
        altitude: position.coords.altitude,
        speed: position.coords.speed,
        heading: position.coords.heading,
        timestamp: new Date(position.timestamp)
    };
    
    lastLocation = location;
    locationHistory.push(location);
    
    updateEmployeeMarker(location);
    drawRouteLine();
    updateStats(location);
}

// Send location update to server
async function sendLocationUpdate() {
    if (!lastLocation) return;
    
    try {
        const response = await fetch(`/visits/${visitId}/update-location`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify(lastLocation)
        });
        
        if (!response.ok) {
            throw new Error('Failed to update location');
        }
        
        updateConnectionStatus(true);
    } catch (error) {
        console.error('Error sending location update:', error);
        updateConnectionStatus(false);
    }
}

// Update connection status display
function updateConnectionStatus(connected) {
    const statusElement = document.getElementById('connectionStatus');
    if (connected) {
        statusElement.className = 'flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800';
        statusElement.innerHTML = '<i class="fas fa-wifi mr-1"></i> Connected';
    } else {
        statusElement.className = 'flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800';
        statusElement.innerHTML = '<i class="fas fa-wifi-slash mr-1"></i> Disconnected';
    }
}

// Handle geolocation errors
function handleGeolocationError(error) {
    console.error('Geolocation error:', error);
    let message = '';
    
    switch(error.code) {
        case error.PERMISSION_DENIED:
            message = 'Location permission denied. Please enable GPS.';
            break;
        case error.POSITION_UNAVAILABLE:
            message = 'Location information unavailable.';
            break;
        case error.TIMEOUT:
            message = 'Location request timed out.';
            break;
        default:
            message = 'Unknown geolocation error.';
            break;
    }
    
    alert('GPS Error: ' + message);
    stopTracking();
}

// Center map on employee
function centerOnEmployee() {
    if (lastLocation && employeeMarker) {
        map.setView([lastLocation.latitude, lastLocation.longitude], 15);
    } else {
        map.setView([clientLocation.lat, clientLocation.lng], 12);
    }
}

// Attempt auto-complete
async function attemptAutoComplete() {
    if (!lastLocation) {
        alert('No location data available');
        return;
    }
    
    try {
        const response = await fetch(`/visits/${visitId}/auto-complete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({
                latitude: lastLocation.latitude,
                longitude: lastLocation.longitude,
                notes: 'Auto-completed via GPS tracker'
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('Visit auto-completed successfully!');
            window.location.reload();
        } else {
            alert(`Not close enough to auto-complete. Distance: ${data.distance}m (Required: ${data.required_distance}m)`);
        }
    } catch (error) {
        console.error('Error auto-completing:', error);
        alert('Failed to auto-complete visit');
    }
}

// Show route history modal
async function showRouteHistory() {
    try {
        const response = await fetch(`/visits/${visitId}/route-history`);
        const data = await response.json();
        
        initRouteMap();
        
        // Draw route on route map
        if (data.route && data.route.length > 0) {
            const points = data.route.map(loc => [loc.latitude, loc.longitude]);
            L.polyline(points, {
                color: '#3b82f6',
                weight: 3,
                opacity: 0.7
            }).addTo(routeMap);
            
            // Add start marker
            const start = data.route[0];
            L.marker([start.latitude, start.longitude], {
                icon: L.divIcon({
                    html: '<div class="w-6 h-6 bg-blue-500 rounded-full border-2 border-white shadow-lg"></div>',
                    className: 'start-marker',
                    iconSize: [24, 24],
                    iconAnchor: [12, 12]
                })
            }).addTo(routeMap).bindPopup('Start point');
            
            document.getElementById('routePoints').textContent = data.route.length;
        }
        
        document.getElementById('routeModal').classList.remove('hidden');
    } catch (error) {
        console.error('Error loading route history:', error);
        alert('Failed to load route history');
    }
}

// Close route modal
function closeRouteModal() {
    document.getElementById('routeModal').classList.add('hidden');
    if (routeMap) {
        routeMap.remove();
        routeMap = null;
    }
}

// Clear route history
async function clearRouteHistory() {
    if (!confirm('Are you sure you want to clear the route history?')) return;
    
    try {
        // In a real app, you would call an API endpoint to clear history
        locationHistory = [];
        if (routeLine) {
            map.removeLayer(routeLine);
            routeLine = null;
        }
        if (routeDecorator) {
            map.removeLayer(routeDecorator);
            routeDecorator = null;
        }
        
        closeRouteModal();
        alert('Route history cleared locally');
    } catch (error) {
        console.error('Error clearing route history:', error);
        alert('Failed to clear route history');
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    initMap();
    
    // Add event listeners for checkboxes
    document.getElementById('showRoute').addEventListener('change', function() {
        if (this.checked && routeLine) {
            map.addLayer(routeLine);
            if (routeDecorator) map.addLayer(routeDecorator);
        } else if (routeLine) {
            map.removeLayer(routeLine);
            if (routeDecorator) map.removeLayer(routeDecorator);
        }
    });
    
    // Check GPS permission
    if ('permissions' in navigator) {
        navigator.permissions.query({name: 'geolocation'})
            .then(permissionStatus => {
                if (permissionStatus.state === 'granted') {
                    // Auto-start tracking if permission already granted
                    startTracking();
                }
            });
    }
});
</script>

<style>
.employee-marker {
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.client-marker {
    animation: bounce 2s infinite;
}

@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-5px); }
}
</style>
@endsection