<x-app-layout>
    <div class="container-fluid p-0">
        <!-- Map Section (Initially hidden) -->
        <div id="searching-map" style="height: 300px; width: 100%; display: none;"></div>

        <!-- Ride Status Card (Slide-up Panel) -->
        <div class="card border-0 shadow-lg rounded-top-4" style="position: relative; margin-top: -30px; z-index: 1000;">
            <div class="card-header bg-dark text-white border-0 rounded-top-4">
                <h4 class="mb-0 fw-bold" id="page-title">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                        <path d="M11.251.068a.5.5 0 0 1 .227.58L9.677 6.5H13a.5.5 0 0 1 .364.843l-8 8.5a.5.5 0 0 1-.842-.49L6.323 9.5H3a.5.5 0 0 1-.364-.843l8-8.5a.5.5 0 0 1 .615-.09zM4.157 8.5H7a.5.5 0 0 1 .478.647L6.11 13.59l5.732-6.09H9a.5.5 0 0 1-.478-.647L9.89 2.41 4.157 8.5z"/>
                    </svg>
                    Searching for Captain...
                </h4>
            </div>
            
            <div class="card-body">
                <!-- Loading State -->
                <div id="searching-loader" class="text-center py-4">
                    <div class="spinner-border text-success" style="width: 3rem; height: 3rem;" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <h5 class="mt-3 fw-bold">Finding your ride</h5>
                    <p class="text-muted">Please wait while we connect you with a captain</p>
                </div>

                <!-- Accepted Ride Details (Initially hidden) -->
                <div id="accepted-ride-details" style="display: none;">
                    <div id="status-messages" class="mb-4"></div>
                    
                    <!-- Captain Card -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-white border-0">
                            <h5 class="mb-0 fw-bold">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                                    <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
                                    <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                                </svg>
                                Captain Details
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="d-flex align-items-center mb-3">
                                <div class="bg-success rounded-circle p-2 me-3">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#fff" viewBox="0 0 16 16">
                                        <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10z"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="small text-muted mb-0">Captain</p>
                                    <h5 class="mb-0" id="captain-name">-</h5>
                                </div>
                            </div>
                            
                            <div class="d-flex align-items-center mb-3">
                                <div class="bg-success rounded-circle p-2 me-3">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#fff" viewBox="0 0 16 16">
                                        <path d="M6 1a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v1h3a1 1 0 0 1 1 1v1.5a1.5 1.5 0 0 1-1.5 1.5h-1a.5.5 0 0 1 0-1h1a.5.5 0 0 0 .5-.5V3h-3v-.5A.5.5 0 0 0 9 2H7a.5.5 0 0 0-.5.5V3H4v-.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 1 0-1h1A1.5 1.5 0 0 1 4 2.5V2a1 1 0 0 1 1-1h3V1z"/>
                                        <path d="M4 5v9a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V5H4zm1 1a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm3-6a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1z"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="small text-muted mb-0">Vehicle</p>
                                    <h5 class="mb-0" id="captain-vehicle">-</h5>
                                </div>
                            </div>
                            
                            <div class="d-flex align-items-center">
                                <div class="bg-success rounded-circle p-2 me-3">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#fff" viewBox="0 0 16 16">
                                        <path d="M6 1a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v1h3a1 1 0 0 1 1 1v1.5a1.5 1.5 0 0 1-1.5 1.5h-1a.5.5 0 0 1 0-1h1a.5.5 0 0 0 .5-.5V3h-3v-.5A.5.5 0 0 0 9 2H7a.5.5 0 0 0-.5.5V3H4v-.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 1 0-1h1A1.5 1.5 0 0 1 4 2.5V2a1 1 0 0 1 1-1h3V1z"/>
                                        <path d="M4 5v9a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V5H4zm1 1a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm3-6a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1zm0 3a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1z"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="small text-muted mb-0">License Plate</p>
                                    <h5 class="mb-0" id="captain-plate">-</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Ride Details Card -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-header bg-white border-0">
                            <h5 class="mb-0 fw-bold">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                                    <path d="M12.166 8.94c-.524 1.062-1.234 2.12-1.96 3.07A31.493 31.493 0 0 1 8 14.58a31.481 31.481 0 0 1-2.206-2.57c-.726-.95-1.436-2.008-1.96-3.07C3.304 7.867 3 6.862 3 6a5 5 0 0 1 10 0c0 .862-.305 1.867-.834 2.94zM8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10z"/>
                                    <path d="M8 8a2 2 0 1 1 0-4 2 2 0 0 1 0 4zm0 1a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
                                </svg>
                                Ride Details
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="d-flex align-items-start mb-3">
                                <div class="bg-success rounded-circle p-1 me-3 mt-1">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="#fff" viewBox="0 0 16 16">
                                        <path fill-rule="evenodd" d="M6 8a.5.5 0 0 0 .5.5h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 0 0-.708.708L12.293 7.5H6.5A.5.5 0 0 0 6 8z"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="small text-muted mb-1">Pickup Location</p>
                                    <p class="mb-0" id="pickup-address">{{ $rideRequest->pickup_address }}</p>
                                </div>
                            </div>
                            
                            <div class="d-flex align-items-start mb-3">
                                <div class="bg-success rounded-circle p-1 me-3 mt-1">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="#fff" viewBox="0 0 16 16">
                                        <path fill-rule="evenodd" d="M10 16a6 6 0 0 0 6-6c0-1.667-.61-3.182-1.618-4.314a6 6 0 0 0-2.048-5.303A5.99 5.99 0 0 0 10 4a6 6 0 0 0-6 6 6 6 0 0 0 6 6zM8.5 4.5a.5.5 0 0 1 1 0v1.5H11a.5.5 0 0 1 0 1H9.5V8.5a.5.5 0 0 1-1 0V7H7a.5.5 0 0 1 0-1h1.5V4.5z"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="small text-muted mb-1">Drop-off Location</p>
                                    <p class="mb-0" id="dropoff-address">{{ $rideRequest->dropoff_address }}</p>
                                </div>
                            </div>
                            
                            <div class="d-flex align-items-start">
                                <div class="bg-success rounded-circle p-1 me-3 mt-1">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="#fff" viewBox="0 0 16 16">
                                        <path d="M8 3.5a.5.5 0 0 0-1 0V9a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 8.71V3.5z"/>
                                        <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="small text-muted mb-1">Estimated Arrival</p>
                                    <h5 class="mb-0 text-success" id="eta-display">Calculating...</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Ride Progress Updates -->
                    <div id="ride-progress-container" class="mt-4"></div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

<script async defer src="https://maps.googleapis.com/maps/api/js?key={{ env('GOOGLE_MAPS_API_KEY') }}&libraries=places,directions&callback=initSearchingMap"></script>

<script>
let searchingMap;
let directionsService;
let directionsRenderer;
let captainMarker;
let passengerMarker;
let destinationMarker;
let rideStatusInterval;
let etaInterval;
let currentRoute = null;
const rideId = '{{ $rideRequest->id }}';

function initSearchingMap() {
    searchingMap = new google.maps.Map(document.getElementById('searching-map'), {
        center: { lat: {{ $rideRequest->pickup_lat }}, lng: {{ $rideRequest->pickup_lng }} },
        zoom: 14,
        styles: [
            {
                "featureType": "all",
                "elementType": "labels.text.fill",
                "stylers": [
                    {
                        "color": "#000000"
                    }
                ]
            },
            {
                "featureType": "poi",
                "elementType": "labels.icon",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            }
        ]
    });

    directionsService = new google.maps.DirectionsService();
    directionsRenderer = new google.maps.DirectionsRenderer({
        map: searchingMap,
        suppressMarkers: true,
        polylineOptions: {
            strokeColor: "#E2712F",
            strokeOpacity: 0.8,
            strokeWeight: 5
        }
    });

    // Add passenger pickup marker
    passengerMarker = new google.maps.Marker({
        position: { lat: {{ $rideRequest->pickup_lat }}, lng: {{ $rideRequest->pickup_lng }} },
        map: searchingMap,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 8,
            fillColor: "#E2712F",
            fillOpacity: 1,
            strokeColor: "#fff",
            strokeWeight: 2
        },
        title: "Pickup Location"
    });

    // Add destination marker
    destinationMarker = new google.maps.Marker({
        position: { lat: {{ $rideRequest->dropoff_lat }}, lng: {{ $rideRequest->dropoff_lng }} },
        map: searchingMap,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 8,
            fillColor: "#FF0000",
            fillOpacity: 1,
            strokeColor: "#fff",
            strokeWeight: 2
        },
        title: "Destination"
    });

    // Start polling for ride status
    checkRideStatus();
    rideStatusInterval = setInterval(checkRideStatus, 5000);
}

async function checkRideStatus() {
    try {
        const response = await fetch(`/ride/${rideId}/status`, {
            headers: {
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        if (!response.ok) throw new Error('Network response was not ok');
        
        const rideData = await response.json();
        updateRideDisplay(rideData);
        
    } catch (error) {
        console.error('Error checking ride status:', error);
        document.getElementById('status-messages').innerHTML = `
            <div class="alert alert-danger d-flex align-items-center">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="me-2" viewBox="0 0 16 16">
                    <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
                </svg>
                Error updating ride status. Please refresh the page.
            </div>`;
    }
}

function updateRideDisplay(rideData) {
    const loader = document.getElementById('searching-loader');
    const details = document.getElementById('accepted-ride-details');
    const map = document.getElementById('searching-map');
    const pageTitle = document.getElementById('page-title');
    
    if (rideData.status !== 'pending') {
        loader.style.display = 'none';
        details.style.display = 'block';
        map.style.display = 'block';
        
        // Update captain details
if (rideData.captain && rideData.captain.captain_profile) {
    document.getElementById('captain-name').textContent = rideData.captain.name;
    document.getElementById('captain-vehicle').textContent = 
        `${rideData.captain.captain_profile.vehicle_make} ${rideData.captain.captain_profile.vehicle_model}`;
    document.getElementById('captain-plate').textContent = 
        rideData.captain.captain_profile.license_number || 'Not available';
}
        
        // Update status title and messages
        updateStatusMessages(rideData.status, pageTitle);
        
        // Update map based on status
        updateMapDisplay(rideData);
        
        // Start ETA calculation if not already running
        if (!etaInterval && (rideData.status === 'in_progress' || rideData.status === 'on_ride')) {
            calculateETA();
            etaInterval = setInterval(calculateETA, 30000); // Update ETA every 30 seconds
        }
    }
    
    if (rideData.status === 'completed') {
        clearInterval(rideStatusInterval);
        clearInterval(etaInterval);
        window.location.href = `/ride/${rideId}/review`;
    }
}

function updateStatusMessages(status, pageTitle) {
    const statusMessages = document.getElementById('status-messages');
    
    switch(status) {
        case 'in_progress':
            pageTitle.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                    <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
                    <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                </svg>
                Captain is on the way`;
            statusMessages.innerHTML = `
                <div class="alert alert-info d-flex align-items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="me-2" viewBox="0 0 16 16">
                        <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"/>
                    </svg>
                    Your captain is coming to your pickup location
                </div>`;
            break;
            
        case 'at_pickup':
            pageTitle.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                    <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm3.5-7.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 8.5H11.5z"/>
                </svg>
                Captain has arrived`;
            statusMessages.innerHTML = `
                <div class="alert alert-success d-flex align-items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="me-2" viewBox="0 0 16 16">
                        <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
                    </svg>
                    Your captain has reached your pickup location
                </div>`;
            break;
            
        case 'on_ride':
            pageTitle.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                    <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm3.5-7.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 8.5H11.5z"/>
                </svg>
                Ride in progress`;
            statusMessages.innerHTML = `
                <div class="alert alert-primary d-flex align-items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="me-2" viewBox="0 0 16 16">
                        <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zM7 6.5C7 7.328 6.552 8 6 8s-1-.672-1-1.5S5.448 5 6 5s1 .672 1 1.5zM4.285 9.567a.5.5 0 0 1 .683.183A3.498 3.498 0 0 0 8 11.5a3.498 3.498 0 0 0 3.032-1.75.5.5 0 1 1 .866.5A4.498 4.498 0 0 1 8 12.5a4.498 4.498 0 0 1-3.898-2.25.5.5 0 0 1 .183-.683zM10 8c-.552 0-1-.672-1-1.5S9.448 5 10 5s1 .672 1 1.5S10.552 8 10 8z"/>
                    </svg>
                    Your ride has started. Enjoy your trip!
                </div>`;
            break;
            
        case 'completed':
            pageTitle.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                    <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
                </svg>
                Ride completed`;
            statusMessages.innerHTML = `
                <div class="alert alert-success d-flex align-items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="me-2" viewBox="0 0 16 16">
                        <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
                    </svg>
                    You have arrived at your destination
                </div>`;
            break;
    }
}

function updateMapDisplay(rideData) {
    if (!rideData.captain) return;
    
    const captainLocation = {
        lat: parseFloat(rideData.captain.captain_profile.current_lat),
        lng: parseFloat(rideData.captain.captain_profile.current_lng)
    };
    
    // Update or create captain marker
    if (captainMarker) {
        captainMarker.setPosition(captainLocation);
    } else {
        captainMarker = new google.maps.Marker({
            position: captainLocation,
            map: searchingMap,
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 8,
                fillColor: "#1E90FF",
                fillOpacity: 1,
                strokeColor: "#fff",
                strokeWeight: 2
            },
            title: "Captain's Location"
        });
    }
    
    // Calculate and display route based on status
    let origin, destination;
    
    if (rideData.status === 'in_progress') {
        // Captain to Pickup
        origin = captainLocation;
        destination = { lat: {{ $rideRequest->pickup_lat }}, lng: {{ $rideRequest->pickup_lng }} };
    } else if (rideData.status === 'on_ride') {
        // Pickup to Dropoff
        origin = captainLocation;
        destination = { lat: {{ $rideRequest->dropoff_lat }}, lng: {{ $rideRequest->dropoff_lng }} };
    }
    
    if (origin && destination) {
        calculateAndDisplayRoute(origin, destination);
    }
}

function calculateAndDisplayRoute(origin, destination) {
    directionsService.route({
        origin: origin,
        destination: destination,
        travelMode: 'DRIVING',
        provideRouteAlternatives: false,
        drivingOptions: {
            departureTime: new Date(),
            trafficModel: 'bestguess'
        }
    }, (response, status) => {
        if (status === 'OK') {
            currentRoute = response;
            directionsRenderer.setDirections(response);
            
            // Adjust viewport to show both markers and route
            const bounds = new google.maps.LatLngBounds();
            bounds.extend(origin);
            bounds.extend(destination);
            searchingMap.fitBounds(bounds);
            
            updateETADisplay(response);
        }
    });
}

function calculateETA() {
    if (currentRoute) {
        updateETADisplay(currentRoute);
    } else {
        // Recalculate route if we don't have one
        const rideData = {
            status: document.getElementById('page-title').textContent.includes('way') ? 'in_progress' : 'on_ride',
            captain: {
                captain_profile: {
                    current_lat: captainMarker.getPosition().lat(),
                    current_lng: captainMarker.getPosition().lng()
                }
            }
        };
        updateMapDisplay(rideData);
    }
}
// Update ETA display
function updateETADisplay(route) {
    if (!route || !route.routes || route.routes.length === 0) return;
    
    const leg = route.routes[0].legs[0];
    const duration = leg.duration.text;
    const distance = leg.distance.text;
    
    document.getElementById('eta-display').innerHTML = `
        <span class="fw-bold">${duration}</span> (${distance} away)
    `;
    
    // Update progress - replace previous instead of appending
    const now = new Date();
    const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    const progressContainer = document.getElementById('ride-progress-container');
    
    progressContainer.innerHTML = `
        <div class="alert alert-light d-flex align-items-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#E2712F" class="me-2" viewBox="0 0 16 16">
                <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
                <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
            </svg>
            <div>
                <p class="small text-muted mb-0">${timeString}</p>
                <p class="mb-0">ETA updated: ${duration} (${distance})</p>
            </div>
        </div>
    `;
}

// Clean up when leaving the page
window.addEventListener('beforeunload', () => {
    clearInterval(rideStatusInterval);
    clearInterval(etaInterval);
});
</script>