<div class="main">
            <p class="fd-3">Welcome Back, Mark Williams</p>
            <div class="row my-2">
                <div class="col-md-12">
                    <!-- location card -->
                    <div class="card loc-card">
                        <div class="card-body">
                            <!-- Form for booking -->
                            <form id="bookingForm" method="POST">
                                <div class="row g-2">
                                    <div class="col-md-4">
                                        <label for="pickLocation" class="label-auth mb-2">Pick-up Location </label>
                                        <div class="input-group mb-3 position-relative">
                                            <span class="input-group-text form-input-text-d" id="basic-addon1"><img
                                                    src="./assets/images/icons/location.png" alt=""></span>
                                            <input type="text" name="pickLocation" id="pickLocation"
                                                class="form-control form-input-d border-left-0 border-right-0"
                                                placeholder="Enter pickup location" autocomplete="off" required>
                                            <button type="button" class="current-location-btn" id="currentLocationBtn" title="Use current location">
                                                📍
                                            </button>
                                            <span class="input-group-text form-input-text-d2" id="basic-addon1"><img
                                                    src="./assets/images/icons/drop.png" alt=""></span>
                                        </div>
                                        <!-- Hidden fields for pickup coordinates -->
                                        <input type="hidden" name="pickupLatitude" id="pickupLatitude">
                                        <input type="hidden" name="pickupLongitude" id="pickupLongitude">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="dropLocation" class="label-auth mb-2">Drop-off Location </label>
                                        <div class="input-group mb-3">
                                            <span class="input-group-text form-input-text-d" id="basic-addon1"><img
                                                    src="./assets/images/icons/location.png" alt=""></span>
                                            <input type="text" name="dropLocation" id="dropLocation"
                                                class="form-control form-input-d border-left-0 border-right-0"
                                                placeholder="Enter destination location" autocomplete="off" required>
                                            <span class="input-group-text form-input-text-d2" id="basic-addon1"><img
                                                    src="./assets/images/icons/drop.png" alt=""></span>
                                        </div>
                                        <!-- Hidden fields for drop-off coordinates -->
                                        <input type="hidden" name="dropLatitude" id="dropLatitude">
                                        <input type="hidden" name="dropLongitude" id="dropLongitude">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="bookingDateTime" class="label-auth mb-2">Date & Time </label>
                                        <div class="input-group mb-3">
                                            <span class="input-group-text form-input-text-d" id="basic-addon1"><img
                                                    src="./assets/images/icons/location.png" alt=""></span>
                                            <input type="datetime-local" name="bookingDateTime" id="bookingDateTime"
                                                class="form-control form-input-d border-left-0 border-right-0">
                                            <span class="input-group-text form-input-text-d2" id="basic-addon1"><img
                                                    src="./assets/images/icons/drop.png" alt=""></span>
                                        </div>
                                    </div>
                                </div>
                                <!-- filters -->
                                <div class="my-2 d-flex justify-content-between flex-wrap align-items-center">
                                    <div class="d-flex align-items-center gap-3">
                                        <p class="f-s4">Booking Type</p>
                                        <div class="d-flex align-items-center gap-2">
                                            <input type="radio" name="bookingType" value="immediate" id="immediateBook" class="d-none" checked>
                                            <label for="immediateBook" class="btn btn-filter filter-active" id="immediateLabel">Immediately Book</label>
                                            
                                            <input type="radio" name="bookingType" value="schedule" id="scheduleBook" class="d-none">
                                            <label for="scheduleBook" class="btn btn-filter" id="scheduleLabel">Schedule Booking</label>
                                        </div>
                                    </div>
                                    <button type="submit" class="btn btn-book px-3" id="bookRideBtn">Book a Ride</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-2">
                <div class="col-md-8">
                    <p class="fd-3">Ongoing Ride</p>
                    <div class="row g-2">
                        <?php if(!empty($currentride)): ?>
                            <?php foreach($currentride as $rideId => $ride): ?>
                            <div class="col-md-6">
                                <div class="card m-card">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start flex-wrap">
                                            <div>
                                                <div class="d-flex align-items-center gap-2">
                                                    <img src="<?= base_url(); ?>assets/images/rimage2.png" alt="">
                                                    <div>
                                                        <p class="fd-7 mb-0">Driver Assigned</p>
                                                        <p class="fd-5 mb-0"><?= isset($ride['carType']) ? $ride['carType'] : 'Car Type'; ?> - <?= isset($ride['pickupDate']) ? date('d F, h:i A', $ride['pickupDate']/1000) : 'Date'; ?></p>
                                                        <p class="fd-8 mb-0">Distance: <?= isset($ride['distance']) ? $ride['distance'] : 'N/A'; ?></p>
                                                    </div>
                                                </div>
                                            </div>
                                            <span class="badge bg-<?= $ride['status'] == 'booked' ? 'warning' : ($ride['status'] == 'driverAccepted' ? 'success' : 'info'); ?>"><?= ucfirst($ride['status']); ?></span>
                                        </div>
                                        <div class="row mt-3">
                                            <div class="col-12">
                                                <div class="d-flex align-items-center gap-2">
                                                    <img src="<?= base_url(); ?>assets/images/icons/loca.png" alt="">
                                                    <div>
                                                        <p class="fd-5">Pick-up Location</p>
                                                        <p class="fd-6"><?= isset($ride['pickUp']['address']) ? $ride['pickUp']['address'] : 'Location not available'; ?></p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="d-flex align-items-center gap-2">
                                                    <img src="<?= base_url(); ?>assets/images/icons/loca.png" alt="">
                                                    <div>
                                                        <p class="fd-5">Drop-off Location</p>
                                                        <p class="fd-6"><?= isset($ride['destinations'][0]['address']) ? $ride['destinations'][0]['address'] : 'Location not available'; ?></p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mt-3">
                                            <div class="col-6">
                                                <p class="fd-5 mb-1">Price</p>
                                                <p class="fd-7">$<?= isset($ride['price']) ? $ride['price'] : '0'; ?></p>
                                            </div>
                                            <div class="col-6">
                                                <p class="fd-5 mb-1">Ride ID</p>
                                                <p class="fd-6"><?= substr($rideId, 0, 8); ?>...</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="card m-card">
                                    <div class="card-body text-center">
                                        <p class="fd-5 mb-0">No ongoing rides</p>
                                        <p class="fd-6">You don't have any active rides at the moment.</p>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-md-4">
                    <p class="fd-3">Ride Map</p>
                    <div class="card m-card">
                        <div class="card-body p-0">
                            <div id="ongoingRideMap" style="height: 300px; width: 100%;"></div>
                            <?php if(!empty($currentride)): ?>
                            <div class="p-3">
                                <button class="btn btn-danger w-100" onclick="cancelRide('<?= array_keys($currentride)[0]; ?>')">
                                    <i class="fas fa-times"></i> Cancel Ride
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
$finalrates=$rates['iRide'];
           
        echo "<pre>";
        print_r($finalrates);
        echo "</pre>";
    
        ?>

<!-- Google Places API with Directions and Distance Matrix -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB0jx5yCf4vk4I5ridEorfPMqohEhpH1H4&libraries=places,geometry,directions"></script>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Stripe JavaScript -->
<script src="https://js.stripe.com/v3/"></script>

<script>
let pickupAutocomplete, dropAutocomplete;
let directionsService, directionsRenderer;
let distanceMatrixService;
let stripe;

// Pricing configuration
const PRICE_PER_KM = <?= $finalrates['pricePerMile']; ?>; // $10 per kilometer
const MINIMUM_FARE = <?= $finalrates['costOfVehicle']+$finalrates['initialFee']; ?>;
const PricePerMinute = <?= $finalrates['pricePerMin']; ?>;
const Vahicalname = "<?= $finalrates['name']; ?>";
 // Minimum fare in dollars
const CURRENCY = 'usd';

function initializeAutocomplete() {
    // Initialize Stripe
    stripe = Stripe('pk_test_51KAaUIBGRgAEMSr6K7AFDVKpXuflSgFIujtSKujaXvWjjmpAKpZgWka9cihxQrKCqNF0I4SJR4FhNXTvVhahNzwx00j0bTjSf9'); // Replace with your Stripe publishable key
    
    // Initialize Google Maps services
    directionsService = new google.maps.DirectionsService();
    directionsRenderer = new google.maps.DirectionsRenderer();
    distanceMatrixService = new google.maps.DistanceMatrixService();
    // Initialize autocomplete for pickup location
    pickupAutocomplete = new google.maps.places.Autocomplete(
        document.getElementById('pickLocation'),
        {
            types: ['establishment', 'geocode'],
            //componentRestrictions: { country: 'your_country_code' } // Replace with your country code like 'US', 'IN', etc.
        }
    );

    // Initialize autocomplete for drop-off location
    dropAutocomplete = new google.maps.places.Autocomplete(
        document.getElementById('dropLocation'),
        {
            types: ['establishment', 'geocode'],
          //  componentRestrictions: { country: 'your_country_code' } // Replace with your country code
        }
    );

    // Add listener for pickup location selection
    pickupAutocomplete.addListener('place_changed', function() {
        const place = pickupAutocomplete.getPlace();
        
        if (!place.geometry) {
            console.log("No details available for input: '" + place.name + "'");
            return;
        }

        // Extract coordinates
        const lat = place.geometry.location.lat();
        const lng = place.geometry.location.lng();
        
        // Set hidden fields
        document.getElementById('pickupLatitude').value = lat;
        document.getElementById('pickupLongitude').value = lng;
        // Ensure input shows the formatted address and mark as selected
        const pickInput = document.getElementById('pickLocation');
        if (place.formatted_address) {
            pickInput.value = place.formatted_address;
        }
        pickInput.dataset.selected = '1';
        
        console.log('Pickup Location:', place.formatted_address);
        console.log('Pickup Coordinates:', lat, lng);
        
        // Optional: Show success feedback
        showLocationFeedback('pickLocation', true);
    });

    // Add listener for drop-off location selection
    dropAutocomplete.addListener('place_changed', function() {
        const place = dropAutocomplete.getPlace();
        
        if (!place.geometry) {
            console.log("No details available for input: '" + place.name + "'");
            return;
        }

        // Extract coordinates
        const lat = place.geometry.location.lat();
        const lng = place.geometry.location.lng();
        
        // Set hidden fields
        document.getElementById('dropLatitude').value = lat;
        document.getElementById('dropLongitude').value = lng;
        // Ensure input shows the formatted address and mark as selected
        const dropInput = document.getElementById('dropLocation');
        if (place.formatted_address) {
            dropInput.value = place.formatted_address;
        }
        dropInput.dataset.selected = '1';
        
        console.log('Drop-off Location:', place.formatted_address);
        console.log('Drop-off Coordinates:', lat, lng);
        
        // Optional: Show success feedback
        showLocationFeedback('dropLocation', true);
    });
}

// Function to show visual feedback when location is selected
function showLocationFeedback(inputId, isValid) {
    const input = document.getElementById(inputId);
    if (input) {
        if (isValid) {
            input.style.borderColor = '#28a745';
            input.style.boxShadow = '0 0 0 0.2rem rgba(40, 167, 69, 0.25)';
            
            // Remove feedback after 2 seconds
            setTimeout(() => {
                input.style.borderColor = '';
                input.style.boxShadow = '';
            }, 2000);
        } else {
            input.style.borderColor = '#dc3545';
            input.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
        }
    }
}

// Function to get current location (optional)
function getCurrentLocation() {
    if (!navigator.geolocation) {
        Swal.fire({
            icon: 'error',
            title: 'Location Not Supported',
            text: 'Your browser does not support location services.',
            confirmButtonColor: '#dc3545'
        });
        return;
    }

    // Show permission request dialog
    requestLocationPermission().then((result) => {
        if (result.isConfirmed) {
            // Show loading while getting location
            Swal.fire({
                title: 'Getting Your Location',
                html: `
                    <div class="location-loader">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p style="margin-top: 15px;">Accessing your current location...</p>
                    </div>
                `,
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false
            });

            navigator.geolocation.getCurrentPosition(
                function(position) {
                    const lat = position.coords.latitude;
                    const lng = position.coords.longitude;
                    
                    // Reverse geocoding to get address
                    const geocoder = new google.maps.Geocoder();
                    const latlng = new google.maps.LatLng(lat, lng);
                    
                    geocoder.geocode({ location: latlng }, function(results, status) {
                        if (status === 'OK' && results[0]) {
                            document.getElementById('pickLocation').value = results[0].formatted_address;
                            document.getElementById('pickupLatitude').value = lat;
                            document.getElementById('pickupLongitude').value = lng;
                            
                            showLocationFeedback('pickLocation', true);
                            
                            // Show success
                            Swal.fire({
                                icon: 'success',
                                title: 'Location Found!',
                                text: 'Your current location has been set as pickup location.',
                                timer: 2000,
                                timerProgressBar: true,
                                showConfirmButton: false
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Address Not Found',
                                text: 'Could not determine your address. Please enter manually.',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    });
                },
                function(error) {
                    let errorMessage = 'Could not access your location.';
                    
                    switch(error.code) {
                        case error.PERMISSION_DENIED:
                            errorMessage = 'Location access denied. Please enable location services.';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMessage = 'Location information is unavailable.';
                            break;
                        case error.TIMEOUT:
                            errorMessage = 'Location request timed out.';
                            break;
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Location Error',
                        text: errorMessage,
                        confirmButtonColor: '#dc3545'
                    });
                }
            );
        }
    });
}

// Validate coordinates before form submission
function validateLocations() {
    const pickupLat = document.getElementById('pickupLatitude').value;
    const pickupLng = document.getElementById('pickupLongitude').value;
    const dropLat = document.getElementById('dropLatitude').value;
    const dropLng = document.getElementById('dropLongitude').value;
    
    if (!pickupLat || !pickupLng) {
        Swal.fire({
            icon: 'warning',
            title: 'Invalid Pickup Location',
            text: 'Please select a valid pickup location from the suggestions.',
            confirmButtonColor: '#007bff'
        });
        showLocationFeedback('pickLocation', false);
        return false;
    }
    
    if (!dropLat || !dropLng) {
        Swal.fire({
            icon: 'warning',
            title: 'Invalid Drop-off Location',
            text: 'Please select a valid drop-off location from the suggestions.',
            confirmButtonColor: '#007bff'
        });
        showLocationFeedback('dropLocation', false);
        return false;
    }
    
    return true;
}

// Handle radio button styling
function handleRadioButtons() {
    const immediateRadio = document.getElementById('immediateBook');
    const scheduleRadio = document.getElementById('scheduleBook');
    const immediateLabel = document.getElementById('immediateLabel');
    const scheduleLabel = document.getElementById('scheduleLabel');
    const dateTimeField = document.getElementById('bookingDateTime');
    const dateTimeContainer = dateTimeField.closest('.col-md-4');

    // Handle immediate booking selection
    immediateLabel.addEventListener('click', function() {
        immediateRadio.checked = true;
        immediateLabel.classList.add('filter-active');
        scheduleLabel.classList.remove('filter-active');
        
        // Hide datetime field for immediate booking
        dateTimeContainer.style.display = 'none';
        dateTimeField.removeAttribute('required');
    });

    // Handle schedule booking selection
    scheduleLabel.addEventListener('click', function() {
        scheduleRadio.checked = true;
        scheduleLabel.classList.add('filter-active');
        immediateLabel.classList.remove('filter-active');
        
        // Show datetime field for scheduled booking
        dateTimeContainer.style.display = 'block';
        dateTimeField.setAttribute('required', 'required');
    });

    // Set initial state (immediate booking selected)
    dateTimeContainer.style.display = 'none';
}

// AJAX form submission
function handleFormSubmission() {
    const bookingForm = document.getElementById('bookingForm');
    const submitBtn = document.getElementById('bookRideBtn');

    bookingForm.addEventListener('submit', function(e) {
        e.preventDefault();

        // Validate locations first
        if (!validateLocations()) {
            return;
        }

        // Get form data
        const formData = new FormData(bookingForm);
        
        // Add validation for scheduled booking
        const bookingType = formData.get('bookingType');
        if (bookingType === 'schedule') {
            const dateTime = formData.get('bookingDateTime');
            if (!dateTime) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Date & Time',
                    text: 'Please select date and time for scheduled booking.',
                    confirmButtonColor: '#007bff'
                });
                return;
            }
        }

        // Prepare data for route calculation
        const bookingData = {
            pickLocation: formData.get('pickLocation'),
            pickupLatitude: formData.get('pickupLatitude'),
            pickupLongitude: formData.get('pickupLongitude'),
            dropLocation: formData.get('dropLocation'),
            dropLatitude: formData.get('dropLatitude'),
            dropLongitude: formData.get('dropLongitude'),
            bookingType: formData.get('bookingType'),
            bookingDateTime: formData.get('bookingDateTime') || null
        };

        // Show loading while calculating route
        Swal.fire({
            title: 'Calculating Route',
            html: `
                <div class="route-loader">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p style="margin-top: 15px;">Calculating distance, time and directions...</p>
                </div>
            `,
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: false
        });

        // Calculate route details
        calculateRouteDetails(
            bookingData.pickupLatitude,
            bookingData.pickupLongitude,
            bookingData.dropLatitude,
            bookingData.dropLongitude
        ).then((routeDetails) => {
            // Add route details to booking data
            bookingData.routeDetails = routeDetails;
            
            // Show route details and confirmation
            showRouteDetails(routeDetails).then(async (result) => {
                if (result.isConfirmed) {
                    // Calculate price and proceed to payment
                    const estimatedPrice = calculatePrice(routeDetails.distanceValue, routeDetails.durationValue);
                    
                    try {
                        // Show payment form
                        const paymentResult = await showPaymentForm(estimatedPrice, bookingData);
                        
                        if (paymentResult.isConfirmed) {
                            // Process payment with the payment method
                            await processPaymentAndBooking(estimatedPrice, bookingData, paymentResult.value, submitBtn);
                        }
                    } catch (error) {
                        console.error('Payment flow error:', error);
                        Swal.fire({
                            icon: 'error',
                            title: 'Payment Error',
                            text: 'There was an error processing your payment. Please try again.',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                }
            });
        }).catch((error) => {
            console.error('Route calculation error:', error);
            
            // Show error but allow user to proceed
            Swal.fire({
                icon: 'warning',
                title: 'Route Calculation Failed',
                text: 'Could not calculate route details. Do you want to proceed with booking?',
                showCancelButton: true,
                confirmButtonColor: '#ffc107',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Proceed Anyway',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Proceed without route details
                    processBooking(bookingData, submitBtn);
                }
            });
        });
    });
}

// Show booking confirmation dialog
function showBookingConfirmation(bookingData) {
    const bookingType = bookingData.bookingType;
    const isScheduled = bookingType === 'schedule';
    
    const confirmationText = `
        <div style="text-align: left; margin-top: 15px;">
            <p><strong>📍 Pickup:</strong> ${bookingData.pickLocation}</p>
            <p><strong>🎯 Drop-off:</strong> ${bookingData.dropLocation}</p>
            <p><strong>🚗 Type:</strong> ${isScheduled ? 'Scheduled Booking' : 'Immediate Booking'}</p>
            ${isScheduled ? `<p><strong>📅 Date & Time:</strong> ${new Date(bookingData.bookingDateTime).toLocaleString()}</p>` : ''}
        </div>
    `;
    
    return Swal.fire({
        title: 'Confirm Your Booking',
        html: confirmationText,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, Book Ride!',
        cancelButtonText: 'Cancel'
    });
}

// Calculate distance, time and get directions
async function calculateRouteDetails(pickupLat, pickupLng, dropLat, dropLng) {
    return new Promise((resolve, reject) => {
        const origin = new google.maps.LatLng(pickupLat, pickupLng);
        const destination = new google.maps.LatLng(dropLat, dropLng);

        // Use Distance Matrix Service for accurate distance and time
        distanceMatrixService.getDistanceMatrix({
            origins: [origin],
            destinations: [destination],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }, function(response, status) {
            if (status === 'OK' && response.rows[0].elements[0].status === 'OK') {
                const element = response.rows[0].elements[0];
                
                // Get directions for route details
                directionsService.route({
                    origin: origin,
                    destination: destination,
                    travelMode: google.maps.TravelMode.DRIVING
                }, function(result, status) {
                    if (status === 'OK') {
                        const route = result.routes[0];
                        const leg = route.legs[0];
                        
                        const routeDetails = {
                            distance: element.distance.text,
                            distanceValue: element.distance.value, // in meters
                            duration: element.duration.text,
                            durationValue: element.duration.value, // in seconds
                            startAddress: leg.start_address,
                            endAddress: leg.end_address,
                            steps: leg.steps,
                            directionsResult: result
                        };
                        
                        resolve(routeDetails);
                    } else {
                        reject('Could not calculate directions: ' + status);
                    }
                });
            } else {
                reject('Could not calculate distance: ' + status);
            }
        });
    });
}

// Calculate estimated price based on distance and duration
function calculatePrice(distanceInMeters, durationInSeconds) {
    const distanceInKm = distanceInMeters / 1000;
    const durationInMinutes = durationInSeconds / 60;
    
    const distanceCost = distanceInKm * PRICE_PER_KM;
    const timeCost = durationInMinutes * PricePerMinute;
    
    const estimatedPrice = MINIMUM_FARE + distanceCost + timeCost;
    return Math.round(estimatedPrice * 100) / 100; // Round to 2 decimal places
}

// Show route details with pricing
function showRouteDetails(routeDetails) {
    const estimatedPrice = calculatePrice(routeDetails.distanceValue, routeDetails.durationValue);
    
    const stepsHtml = routeDetails.steps.map((step, index) => `
        <div class="route-step">
            <span class="step-number">${index + 1}</span>
            <span class="step-instruction">${step.instructions}</span>
            <span class="step-distance">${step.distance.text}</span>
        </div>
    `).join('');

    return Swal.fire({
        title: 'Route & Pricing Details',
        html: `
            <div class="route-summary">
                <div class="route-info">
                    <div class="info-item">
                        <strong>📏 Distance:</strong> ${routeDetails.distance}
                    </div>
                    <div class="info-item">
                        <strong>⏱️ Estimated Time:</strong> ${routeDetails.duration}
                    </div>
                    <div class="info-item">
                        <strong>🚗 Travel Mode:</strong> Driving
                    </div>
                    <div class="info-item price-highlight">
                        <strong>💰 Estimated Price:</strong> $${estimatedPrice}
                        <small style="display: block; color: #6c757d; margin-top: 5px;">
                            Rate: $${PRICE_PER_KM}/km, $${PricePerMinute}/min | Minimum fare: $${MINIMUM_FARE}
                        </small>
                    </div>
                </div>
                <div class="route-directions">
                    <h6>Turn-by-turn Directions:</h6>
                    <div class="directions-list">
                        ${stepsHtml}
                    </div>
                </div>
            </div>
        `,
        width: '650px',
        confirmButtonColor: '#28a745',
        confirmButtonText: 'Pay & Book Ride',
        showCancelButton: true,
        cancelButtonText: 'Cancel',
        customClass: {
            popup: 'route-details-popup'
        }
    });
}

// Process Stripe payment
async function processStripePayment(amount, bookingData) {
    try {
        // Show payment processing loader
        Swal.fire({
            title: 'Processing Payment',
            html: `
                <div class="payment-loader">
                    <div class="spinner-border text-success" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p style="margin-top: 15px;">Processing your payment of $${amount}...</p>
                    <small style="color: #6c757d;">Please do not close this window</small>
                </div>
            `,
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: false
        });

        // Create payment intent on backend
        const response = await fetch('<?php echo base_url('dashboard/create_payment_intent'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                amount: Math.round(amount * 100), // Convert to cents
                currency: CURRENCY,
                bookingData: bookingData
            })
        });

        const { client_secret, error } = await response.json();

        if (error) {
            throw new Error(error);
        }

        // Confirm payment with Stripe
        const { error: stripeError, paymentIntent } = await stripe.confirmCardPayment(client_secret, {
            payment_method: {
                card: {
                    // Use Stripe Elements or a test card
                    number: '4242424242424242',
                    exp_month: 12,
                    exp_year: 2025,
                    cvc: '123'
                }
            }
        });

        if (stripeError) {
            throw new Error(stripeError.message);
        }

        if (paymentIntent.status === 'succeeded') {
            // Payment successful, add payment details to booking data
            bookingData.paymentDetails = {
                paymentIntentId: paymentIntent.id,
                amount: amount,
                currency: CURRENCY,
                status: 'paid',
                paymentMethod: 'stripe'
            };

            return { success: true, paymentIntent };
        } else {
            throw new Error('Payment was not completed');
        }

    } catch (error) {
        console.error('Payment error:', error);
        throw error;
    }
}

// Show payment form with Stripe Elements
function showPaymentForm(amount, bookingData) {
    return Swal.fire({
        title: 'Payment Details',
        html: `
            <div class="payment-form">
                <div class="price-summary">
                    <h5>Trip Summary</h5>
                    <div class="price-breakdown">
                        <div class="price-item">
                            <span>Distance:</span>
                            <span>${bookingData.routeDetails.distance}</span>
                        </div>
                        <div class="price-item">
                            <span>Rate:</span>
                            <span>$${PRICE_PER_KM}/km</span>
                        </div>
                        <div class="price-item total">
                            <span><strong>Total Amount:</strong></span>
                            <span><strong>$${amount}</strong></span>
                        </div>
                    </div>
                </div>
                <div class="payment-method">
                    <h6>Payment Method</h6>
                    <div id="card-element" style="padding: 15px; border: 1px solid #ddd; border-radius: 8px; margin: 10px 0;">
                        <!-- Stripe Elements will create form elements here -->
                    </div>
                    <div id="card-errors" role="alert" style="color: #dc3545; margin-top: 10px;"></div>
                </div>
            </div>
        `,
        width: '500px',
        confirmButtonColor: '#28a745',
        confirmButtonText: `Pay $${amount}`,
        showCancelButton: true,
        cancelButtonText: 'Cancel',
        customClass: {
            popup: 'payment-popup'
        },
        didOpen: () => {
            // Initialize Stripe Elements
            const elements = stripe.elements();
            const cardElement = elements.create('card', {
                style: {
                    base: {
                        fontSize: '16px',
                        color: '#424770',
                        '::placeholder': {
                            color: '#aab7c4',
                        },
                    },
                },
            });
            
            cardElement.mount('#card-element');
            
            // Handle real-time validation errors from the card Element
            cardElement.on('change', ({error}) => {
                const displayError = document.getElementById('card-errors');
                if (error) {
                    displayError.textContent = error.message;
                } else {
                    displayError.textContent = '';
                }
            });
            
            // Store card element for later use
            Swal.getPopup().cardElement = cardElement;
        },
        preConfirm: async () => {
            const cardElement = Swal.getPopup().cardElement;
            
            // Create payment method
            const {error, paymentMethod} = await stripe.createPaymentMethod({
                type: 'card',
                card: cardElement,
            });
            
            if (error) {
                Swal.showValidationMessage(error.message);
                return false;
            }
            
            return paymentMethod;
        }
    });
}

// Process payment and booking
async function processPaymentAndBooking(amount, bookingData, paymentMethod, submitBtn) {
    try {
        
        // Show payment processing loader
        Swal.fire({
            title: 'Processing Payment',
            html: `
                <div class="payment-loader">
                    <div class="spinner-border text-success" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p style="margin-top: 15px;">Processing payment of $${amount}...</p>
                    <small style="color: #6c757d;">Please do not close this window</small>
                </div>
            `,
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: false
        });
        
        // Create payment intent and process payment
        const paymentResponse = await fetch('<?php echo base_url('dashboard/process_payment'); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                amount: Math.round(amount * 100), // Convert to cents
                currency: CURRENCY,
                payment_method_id: paymentMethod.id,
                bookingData: bookingData
            })
        });

        console.log("paymentResponse",paymentResponse);
        const responseText = await paymentResponse.text();
        console.log("Raw response:", responseText);
        let paymentResult = null;
        if (responseText && responseText.trim().length > 0) {
            try {
                paymentResult = JSON.parse(responseText);
            } catch (e) {
                console.error("Failed to parse JSON:", e);
                console.error("Raw response:", responseText);
                await Swal.fire({
                    icon: 'error',
                    title: 'Payment Error',
                    html: `<div style="text-align:left; word-break: break-all;">${responseText.substring(0, 800)}</div>`,
                });
                throw new Error("Invalid JSON response");
            }
        } else {
            // Empty response
            console.error("Empty response body", paymentResponse.status, paymentResponse.statusText);
            await Swal.fire({
                icon: 'error',
                title: 'Payment Error',
                text: `Empty response (${paymentResponse.status} ${paymentResponse.statusText}). Please try again.`,
            });
            throw new Error("Empty response from server");
        }
        

        if (paymentResult.success) {
            // Payment successful, proceed with booking
            bookingData.paymentDetails = paymentResult.paymentDetails;
            
            // Now create the booking
            const bookingResponse = await fetch('<?php echo base_url('dashboard/book_ride'); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(bookingData)
            });

            const bookingResult = await bookingResponse.json();

            if (bookingResult.success) {
                // Show success with payment and booking details
                Swal.fire({
                    icon: 'success',
                    title: 'Payment & Booking Successful!',
                    html: `
                        <div style="text-align: center;">
                            <div style="background: #e8f5e8; padding: 15px; border-radius: 8px; margin: 15px 0;">
                                <h6>✅ Payment Confirmed</h6>
                                <p><strong>Amount Paid:</strong> $${amount}</p>
                                <p><strong>Payment ID:</strong> ${paymentResult.paymentDetails.paymentIntentId}</p>
                            </div>
                            <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin: 15px 0;">
                                <h6>🚗 Booking Confirmed</h6>
                                <p><strong>Booking ID:</strong> ${bookingResult.bookingId}</p>
                                <p><strong>Distance:</strong> ${bookingData.routeDetails.distance}</p>
                                <p><strong>Est. Time:</strong> ${bookingData.routeDetails.duration}</p>
                            </div>
                        </div>
                    `,
                    confirmButtonColor: '#28a745',
                    timer: 8000,
                    timerProgressBar: true,
                    showCancelButton: true,
                    cancelButtonText: 'View My Rides',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.dismiss === Swal.DismissReason.cancel) {
                        // Redirect to my rides page
                        window.location.href = '<?php echo base_url('dashboard/myrides'); ?>';
                    }
                    
                    // Reload if immediate booking, else reset form
                    if (bookingData.bookingType === 'immediate') {
                        window.location.reload();
                    } else {
                        resetBookingForm();
                    }
                });
            } else {
                throw new Error(bookingResult.message || 'Booking failed after payment');
            }
        } else {
            throw new Error(paymentResult.message || 'Payment failed');
        }

    } catch (error) {
        console.error('Payment/Booking error:', error);
        return;
        
        Swal.fire({
            icon: 'error',
            title: 'Payment Failed',
            text: error.message || 'Payment could not be processed. Please try again.',
            confirmButtonColor: '#dc3545',
            footer: '<small>Your card was not charged</small>'
        });
    } finally {
        // Re-enable submit button
        submitBtn.disabled = false;
    }
}

// Show location permission request
function requestLocationPermission() {
    return Swal.fire({
        title: 'Location Access',
        text: 'Allow access to your location to auto-fill pickup address?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#007bff',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Allow',
        cancelButtonText: 'Skip'
    });
}

// Process the actual booking
function processBooking(bookingData, submitBtn) {

    // Show loading alert
    Swal.fire({
        title: 'Booking Your Ride',
        html: `
            <div class="booking-loader">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p style="margin-top: 15px;">Please wait while we process your booking...</p>
            </div>
        `,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showConfirmButton: false
    });

    // Disable submit button
    submitBtn.disabled = true;

    // Send AJAX request
    fetch('<?php echo base_url('dashboard/book_ride'); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(bookingData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message with route details
            const routeInfo = bookingData.routeDetails ? `
                <div style="background: #e8f5e8; padding: 15px; border-radius: 8px; margin: 15px 0;">
                    <h6>Trip Details:</h6>
                    <p><strong>📏 Distance:</strong> ${bookingData.routeDetails.distance}</p>
                    <p><strong>⏱️ Estimated Time:</strong> ${bookingData.routeDetails.duration}</p>
                </div>
            ` : '';

            Swal.fire({
                icon: 'success',
                title: 'Booking Successful!',
                html: `
                    <div style="text-align: center;">
                        <p>${data.message || 'Your ride has been booked successfully!'}</p>
                        ${routeInfo}
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 15px;">
                            <p><strong>Booking ID:</strong> ${data.bookingId}</p>
                            <p><strong>Status:</strong> <span class="badge bg-warning">Pending</span></p>
                        </div>
                    </div>
                `,
                confirmButtonColor: '#28a745',
                timer: 5000,
                timerProgressBar: true,
                showCancelButton: true,
                cancelButtonText: 'View My Rides',
                confirmButtonText: 'OK'
            }).then((result) => {
                if (result.dismiss === Swal.DismissReason.cancel) {
                    // Redirect to my rides page
                    window.location.href = '<?php echo base_url('dashboard/myrides'); ?>';
                }
                
                // Reload if immediate booking, else reset form
                if (bookingData.bookingType === 'immediate') {
                    window.location.reload();
                } else {
                    resetBookingForm();
                }
            });
        } else {
            // Show error message with SweetAlert
            Swal.fire({
                icon: 'error',
                title: 'Booking Failed',
                text: data.message || 'Failed to book ride. Please try again.',
                confirmButtonColor: '#dc3545',
                footer: '<a href="#">Need help? Contact support</a>'
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Network Error',
            text: 'Please check your connection and try again.',
            confirmButtonColor: '#dc3545',
            showCancelButton: true,
            cancelButtonText: 'Retry',
            confirmButtonText: 'OK'
        }).then((result) => {
            if (result.dismiss === Swal.DismissReason.cancel) {
                // Retry the booking
                processBooking(bookingData, submitBtn);
            }
        });
    })
    .finally(() => {
        // Re-enable submit button
        submitBtn.disabled = false;
    });
}

// Reset booking form to initial state
function resetBookingForm() {
    const bookingForm = document.getElementById('bookingForm');
    bookingForm.reset();
    
    // Clear coordinate fields
    document.getElementById('pickupLatitude').value = '';
    document.getElementById('pickupLongitude').value = '';
    document.getElementById('dropLatitude').value = '';
    document.getElementById('dropLongitude').value = '';
    
    // Reset radio buttons to default
    document.getElementById('immediateBook').checked = true;
    document.getElementById('immediateLabel').classList.add('filter-active');
    document.getElementById('scheduleLabel').classList.remove('filter-active');
    document.getElementById('bookingDateTime').closest('.col-md-4').style.display = 'none';
    document.getElementById('bookingDateTime').removeAttribute('required');
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Check if Google Maps API is loaded
    if (typeof google !== 'undefined' && google.maps && google.maps.places) {
        initializeAutocomplete();
    } else {
        console.error('Google Maps API not loaded properly');
    }
    
    // Initialize radio button handling
    handleRadioButtons();
    
    // Initialize form submission
    handleFormSubmission();
    
    // Add current location button functionality
    const addCurrentLocationBtn = document.getElementById('currentLocationBtn');
    if (addCurrentLocationBtn) {
        addCurrentLocationBtn.addEventListener('click', getCurrentLocation);
    }
});

// Handle input validation on blur
document.addEventListener('DOMContentLoaded', function() {
    const pickupInput = document.getElementById('pickLocation');
    const dropInput = document.getElementById('dropLocation');
    
    if (pickupInput) {
        pickupInput.addEventListener('input', function() {
            // User is typing, mark as not selected yet
            this.dataset.selected = '0';
        });
        pickupInput.addEventListener('blur', function() {
            const lat = document.getElementById('pickupLatitude').value;
            const lng = document.getElementById('pickupLongitude').value;
            
            if (this.value && (!lat || !lng) && this.dataset.selected !== '1') {
                showLocationFeedback('pickLocation', false);
                // Clear the input if it's not a valid selection
                setTimeout(() => {
                    if (!lat || !lng) {
                        this.value = '';
                        document.getElementById('pickupLatitude').value = '';
                        document.getElementById('pickupLongitude').value = '';
                    }
                }, 100);
            }
        });
    }
    
    if (dropInput) {
        dropInput.addEventListener('input', function() {
            // User is typing, mark as not selected yet
            this.dataset.selected = '0';
        });
        dropInput.addEventListener('blur', function() {
            const lat = document.getElementById('dropLatitude').value;
            const lng = document.getElementById('dropLongitude').value;
            
            if (this.value && (!lat || !lng) && this.dataset.selected !== '1') {
                showLocationFeedback('dropLocation', false);
                // Clear the input if it's not a valid selection
                setTimeout(() => {
                    if (!lat || !lng) {
                        this.value = '';
                        document.getElementById('dropLatitude').value = '';
                        document.getElementById('dropLongitude').value = '';
                    }
                }, 100);
            }
        });
    }
});

// Initialize ongoing ride map
let ongoingRideMap;
let ongoingDirectionsService, ongoingDirectionsRenderer;

function initializeOngoingRideMap() {
    <?php if(!empty($currentride)): ?>
    <?php $firstRide = reset($currentride); ?>
    const pickupLat = <?= isset($firstRide['pickUp']['lat']) ? $firstRide['pickUp']['lat'] : '0'; ?>;
    const pickupLng = <?= isset($firstRide['pickUp']['lng']) ? $firstRide['pickUp']['lng'] : '0'; ?>;
    const dropLat = <?= isset($firstRide['destinations'][0]['lat']) ? $firstRide['destinations'][0]['lat'] : '0'; ?>;
    const dropLng = <?= isset($firstRide['destinations'][0]['lng']) ? $firstRide['destinations'][0]['lng'] : '0'; ?>;
    console.log("ongoing ride map",pickupLat, pickupLng, dropLat, dropLng);

    const centerLat = (pickupLat + dropLat) / 2;
    const centerLng = (pickupLng + dropLng) / 2;
    
    ongoingRideMap = new google.maps.Map(document.getElementById('ongoingRideMap'), {
        zoom: 13,
        center: { lat: centerLat, lng: centerLng }
    });
    
    ongoingDirectionsService = new google.maps.DirectionsService();
    ongoingDirectionsRenderer = new google.maps.DirectionsRenderer({
        draggable: false,
        map: ongoingRideMap
    });
    
    // Add pickup marker
    const pickupMarker = new google.maps.Marker({
        position: { lat: pickupLat, lng: pickupLng },
        map: ongoingRideMap,
        title: 'Pickup Location',
        icon: {
            url: '<?= base_url(); ?>assets/images/icons/loca.png',
            scaledSize: new google.maps.Size(30, 30)
        }
    });
    
    // Add drop-off marker
    const dropMarker = new google.maps.Marker({
        position: { lat: dropLat, lng: dropLng },
        map: ongoingRideMap,
        title: 'Drop-off Location',
        icon: {
            url: '<?= base_url(); ?>assets/images/icons/loca.png',
            scaledSize: new google.maps.Size(30, 30)
        }
    });
    
    // Draw route
    const request = {
        origin: { lat: pickupLat, lng: pickupLng },
        destination: { lat: dropLat, lng: dropLng },
        travelMode: google.maps.TravelMode.DRIVING
    };
    
    ongoingDirectionsService.route(request, function(result, status) {
        if (status === 'OK') {
            ongoingDirectionsRenderer.setDirections(result);
        }
    });
    <?php else: ?>
    // No ongoing rides - show default map
    ongoingRideMap = new google.maps.Map(document.getElementById('ongoingRideMap'), {
        zoom: 10,
        center: { lat: 33.6844, lng: 73.0479 } // Default to Islamabad
    });
    <?php endif; ?>
}

// Check if user has ongoing ride and prevent immediate booking
function checkOngoingRide() {
    <?php if(!empty($currentride)): ?>
    return {
        hasOngoing: true,
        rideId: '<?= array_keys($currentride)[0]; ?>',
        ride: <?= json_encode(reset($currentride)); ?>
    };
    <?php else: ?>
    return { hasOngoing: false };
    <?php endif; ?>
}

// Cancel ride function
function cancelRide(rideId) {
    Swal.fire({
        title: 'Cancel Ride?',
        text: "Are you sure you want to cancel this ride?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, cancel it!',
        cancelButtonText: 'No, keep it'
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: 'Cancelling...',
                text: 'Please wait while we cancel your ride',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Make AJAX request to cancel ride
            fetch('<?= base_url(); ?>dashboard/cancel_ride', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    rideId: rideId
                })
            })
            .then(response => response.json())
            .then(data => {
                Swal.close();
                if (data.success) {
                    Swal.fire({
                        title: 'Cancelled!',
                        text: 'Your ride has been cancelled successfully.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: data.message || 'Failed to cancel ride. Please try again.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            })
            .catch(error => {
                Swal.close();
                Swal.fire({
                    title: 'Error!',
                    text: 'Network error. Please try again.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            });
        }
    });
}

// Initialize map when page loads
document.addEventListener('DOMContentLoaded', function() {
    initializeOngoingRideMap();
    restrictBookingType();
});

// Override book ride function to check for ongoing rides
const originalBookRide = window.bookRide;
window.bookRide = function() {
    const ongoingRide = checkOngoingRide();
    
    if (ongoingRide.hasOngoing) {
        Swal.fire({
            title: 'Booking Not Allowed',
            html: `
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle text-warning mb-3" style="font-size: 3rem;"></i>
                    <h4>You already have an ongoing ride!</h4>
                    <p class="text-muted mb-3">You cannot book an immediate ride while you have an active ride in progress.</p>
                    <div class="card">
                        <div class="card-body">
                            <h6>Current Ride Details:</h6>
                            <p class="mb-1"><strong>Status:</strong> ${ongoingRide.ride.status}</p>
                            <p class="mb-1"><strong>Car Type:</strong> ${ongoingRide.ride.carType || 'N/A'}</p>
                            <p class="mb-1"><strong>Price:</strong> $${ongoingRide.ride.price || '0'}</p>
                        </div>
                    </div>
                    <div class="mt-3">
                        <button class="btn btn-primary me-2" onclick="viewCurrentRide('${ongoingRide.rideId}')">
                            <i class="fas fa-eye"></i> View Current Ride
                        </button>
                        <button class="btn btn-danger" onclick="cancelRide('${ongoingRide.rideId}')">
                            <i class="fas fa-times"></i> Cancel Current Ride
                        </button>
                    </div>
                </div>
            `,
            showCancelButton: false,
            confirmButtonText: 'OK',
            confirmButtonColor: '#3085d6'
        });
        return false;
    }
    
    // If no ongoing ride, proceed with original booking
    if (originalBookRide) {
        return originalBookRide();
    }
};

// Override booking type selection to restrict immediate booking
function restrictBookingType() {
    const ongoingRide = checkOngoingRide();
    
    if (ongoingRide.hasOngoing) {
        // Disable immediate booking option
        const immediateOption = document.querySelector('input[value="immediate"]');
        const scheduleOption = document.querySelector('input[value="schedule"]');
        
        if (immediateOption) {
            immediateOption.disabled = true;
            immediateOption.parentElement.classList.add('text-muted');
        }
        
        if (scheduleOption) {
            scheduleOption.checked = true; // Auto-select schedule
        }
        
        // Show warning message
        const warningDiv = document.createElement('div');
        warningDiv.className = 'alert alert-warning mt-2';
        warningDiv.innerHTML = '<i class="fas fa-info-circle"></i> You have an ongoing ride. Only scheduled rides are allowed.';
        
        const bookingTypeContainer = document.querySelector('.booking-type-container');
        if (bookingTypeContainer) {
            bookingTypeContainer.appendChild(warningDiv);
        }
    }
}

// View current ride function
function viewCurrentRide(rideId) {
    window.location.href = '<?= base_url(); ?>dashboard/view_ride/' + rideId;
}
</script>

<style>
/* Autocomplete styling */
.pac-container {
    z-index: 9999 !important;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    border: none;
    margin-top: 5px;
}

.pac-item {
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.pac-item:hover {
    background-color: #f8f9fa;
}

.pac-item-selected {
    background-color: #007bff !important;
    color: white !important;
}

.pac-matched {
    font-weight: bold;
}

/* Location input styling */
.form-input-d:focus {
    border-color: #007bff !important;
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25) !important;
}

/* Location validation feedback */
.location-valid {
    border-color: #28a745 !important;
    box-shadow: 0 0 0 0.2rem rgba(33, 111, 51, 0.25) !important;
}

.location-invalid {
    border-color: #dc3545 !important;
    box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

/* Current location button */
.current-location-btn {
    position: absolute;
    right: 45px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: #007bff;
    cursor: pointer;
    padding: 5px;
    border-radius: 3px;
    transition: all 0.2s ease;
    z-index: 10;
}

.current-location-btn:hover {
    background-color: #f8f9fa;
    color: #0056b3;
}

/* Radio button styling */
.btn-filter {
    transition: all 0.3s ease;
    border: 2px solid #007bff;
    background: transparent;
    color: #007bff;
}

.btn-filter.filter-active {
    background: #007bff;
    color: white;
}

.btn-filter:hover {
    background: #007bff;
    color: white;
    transform: translateY(-1px);
}

/* Book ride button */
.btn-book {
    background: linear-gradient(135deg, #28a745, #20c997);
    border: none;
    color: white;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-book:hover {
    background: linear-gradient(135deg, #218838, #1ea080);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.btn-book:disabled {
    background: #6c757d;
    cursor: not-allowed;
    transform: none;
}

/* Booking notifications */
.booking-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    min-width: 300px;
    max-width: 400px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    animation: slideInRight 0.3s ease-out;
}

.booking-notification.success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.booking-notification.error {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

.notification-content {
    padding: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.notification-icon {
    font-size: 18px;
}

.notification-message {
    flex: 1;
    font-weight: 500;
}

.notification-close {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    padding: 0;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background-color 0.2s ease;
}

.notification-close:hover {
    background-color: rgba(0,0,0,0.1);
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* Form validation styling */
.form-input-d.is-invalid {
    border-color: #dc3545 !important;
    box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

.form-input-d.is-valid {
    border-color: #28a745 !important;
    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25) !important;
}

/* Custom loader styles */
.booking-loader, .location-loader {
    text-align: center;
    padding: 20px;
}

.booking-loader .spinner-border,
.location-loader .spinner-border {
    width: 3rem;
    height: 3rem;
    border-width: 0.3em;
}

.booking-loader p,
.location-loader p {
    color: #6c757d;
    font-size: 14px;
    margin: 0;
}

/* SweetAlert custom styling */
.swal2-popup {
    border-radius: 15px !important;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2) !important;
}

.swal2-title {
    font-size: 1.5rem !important;
    font-weight: 600 !important;
}

.swal2-content {
    font-size: 1rem !important;
}

.swal2-confirm {
    border-radius: 25px !important;
    padding: 10px 25px !important;
    font-weight: 600 !important;
}

.swal2-cancel {
    border-radius: 25px !important;
    padding: 10px 25px !important;
    font-weight: 600 !important;
}

/* Badge styling in SweetAlert */
.badge {
    display: inline-block;
    padding: 0.375rem 0.75rem;
    font-size: 0.75rem;
    font-weight: 700;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.375rem;
}

.bg-warning {
    background-color: #ffc107 !important;
    color: #000 !important;
}

/* Loading button state */
.btn-book:disabled {
    background: #6c757d !important;
    cursor: not-allowed !important;
    transform: none !important;
    opacity: 0.7;
}

/* Enhanced visual feedback for form inputs */
.form-input-d.location-loading {
    background-image: linear-gradient(45deg, transparent 33%, rgba(0,123,255,0.1) 33%, rgba(0,123,255,0.1) 66%, transparent 66%);
    background-size: 20px 20px;
    animation: loading-stripes 1s linear infinite;
}

@keyframes loading-stripes {
    0% {
        background-position: 0 0;
    }
    100% {
        background-position: 20px 0;
    }
}

/* Route details styling */
.route-summary {
    text-align: left;
    max-height: 400px;
    overflow-y: auto;
}

.route-info {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 15px;
}

.info-item {
    margin-bottom: 8px;
    padding: 5px 0;
    border-bottom: 1px solid #e9ecef;
}

.info-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
}

.route-directions {
    margin-top: 15px;
}

.route-directions h6 {
    color: #495057;
    margin-bottom: 10px;
    font-weight: 600;
}

.directions-list {
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 10px;
}

.route-step {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
    padding: 8px;
    background: #fff;
    border-radius: 5px;
    border-left: 3px solid #007bff;
}

.step-number {
    background: #007bff;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
    margin-right: 10px;
    flex-shrink: 0;
}

.step-instruction {
    flex: 1;
    font-size: 14px;
    line-height: 1.4;
    margin-right: 10px;
}

.step-distance {
    font-size: 12px;
    color: #6c757d;
    font-weight: 500;
    flex-shrink: 0;
}

/* Route loader styling */
.route-loader {
    text-align: center;
    padding: 20px;
}

.route-loader .spinner-border {
    width: 3rem;
    height: 3rem;
    border-width: 0.3em;
}

.route-loader p {
    color: #6c757d;
    font-size: 14px;
    margin: 0;
}

/* Enhanced route details popup */
.route-details-popup {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.route-details-popup .swal2-html-container {
    padding: 0 !important;
    margin: 0 !important;
}

/* Price highlight styling */
.price-highlight {
    background: linear-gradient(135deg, #fff3cd, #ffeaa7) !important;
    border: 2px solid #ffc107 !important;
    border-radius: 8px !important;
    padding: 15px !important;
    margin: 10px 0 !important;
    text-align: center;
}

.price-highlight strong {
    color: #856404;
    font-size: 1.1em;
}

/* Payment form styling */
.payment-form {
    text-align: left;
}

.price-summary {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 20px;
    border: 1px solid #e9ecef;
}

.price-summary h5 {
    color: #495057;
    margin-bottom: 15px;
    text-align: center;
}

.price-breakdown {
    space-y: 10px;
}

.price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #e9ecef;
}

.price-item:last-child {
    border-bottom: none;
}

.price-item.total {
    background: #e8f5e8;
    padding: 12px 15px;
    border-radius: 8px;
    margin-top: 10px;
    border: 2px solid #28a745;
}

.payment-method {
    margin-top: 20px;
}

.payment-method h6 {
    color: #495057;
    margin-bottom: 15px;
}

/* Stripe Elements styling */
.StripeElement {
    background: white;
    padding: 15px;
    border-radius: 8px;
    border: 1px solid #ddd;
    transition: border-color 0.3s ease;
}

.StripeElement:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
}

.StripeElement--invalid {
    border-color: #dc3545;
}

.StripeElement--complete {
    border-color: #28a745;
}

/* Payment popup styling */
.payment-popup {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.payment-popup .swal2-html-container {
    padding: 0 !important;
    margin: 0 !important;
}

/* Payment loader styling */
.payment-loader {
    text-align: center;
    padding: 20px;
}

.payment-loader .spinner-border {
    width: 3rem;
    height: 3rem;
    border-width: 0.3em;
}

.payment-loader p {
    color: #6c757d;
    font-size: 16px;
    margin: 15px 0 5px 0;
    font-weight: 500;
}

.payment-loader small {
    font-size: 12px;
}

/* Mobile responsive improvements */
@media (max-width: 768px) {
    .current-location-btn {
        right: 35px;
        font-size: 14px;
    }
    
    .swal2-popup {
        margin: 0 10px !important;
    }
    
    .booking-loader, .location-loader, .route-loader {
        padding: 15px;
    }
    
    .route-details-popup {
        width: 95% !important;
        max-width: none !important;
    }
    
    .directions-list {
        max-height: 150px;
    }
    
    .route-step {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .step-number {
        margin-bottom: 5px;
    }
    
    .step-distance {
        margin-top: 5px;
        align-self: flex-end;
    }
}
</style>