// Sample car data
const cars = [
    {
        id: 1,
        name: "Toyota Corolla",
        category: "economy",
        price: 45,
        features: ["5 Seats", "2 Bags", "Automatic", "Air Conditioning"],
        image: "https://images.unsplash.com/photo-1590362891991-f776e747a588?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"
    },
    {
        id: 2,
        name: "Honda Civic",
        category: "economy",
        price: 48,
        features: ["5 Seats", "2 Bags", "Automatic", "Air Conditioning"],
        image: "https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"
    },
    {
        id: 3,
        name: "Ford Focus",
        category: "compact",
        price: 52,
        features: ["5 Seats", "3 Bags", "Automatic", "Air Conditioning"],
        image: "https://images.unsplash.com/photo-1606152421802-db97b9c7a11b?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"
    },
    {
        id: 4,
        name: "Jeep Compass",
        category: "suv",
        price: 75,
        features: ["5 Seats", "4 Bags", "Automatic", "Air Conditioning", "4x4"],
        image: "https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"
    },
    {
        id: 5,
        name: "Mercedes C-Class",
        category: "luxury",
        price: 120,
        features: ["5 Seats", "3 Bags", "Automatic", "Air Conditioning", "Leather Seats"],
        image: "https://images.unsplash.com/photo-1553440569-bcc63803a83d?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"
    },
    {
        id: 6,
        name: "BMW 3 Series",
        category: "luxury",
        price: 135,
        features: ["5 Seats", "3 Bags", "Automatic", "Air Conditioning", "Leather Seats"],
        image: "https://images.unsplash.com/photo-1549399542-7e3f8b79c341?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"
    }
];

// DOM Elements
const carsGrid = document.getElementById('cars-grid');
const categoryFilter = document.getElementById('car-category');
const priceFilter = document.getElementById('price-range');
const modal = document.getElementById('booking-modal');
const closeModalBtn = document.querySelector('.close');
const bookingForm = document.getElementById('booking-form');
const pickupLocationInput = document.getElementById('pickup-location');
const pickupDateInput = document.getElementById('pickup-date');
const returnDateInput = document.getElementById('return-date');

// Set today's date as minimum for date inputs
const today = new Date().toISOString().split('T')[0];
pickupDateInput.setAttribute('min', today);
returnDateInput.setAttribute('min', today);

// Default tomorrow as pickup date and day after tomorrow as return date
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const dayAfterTomorrow = new Date();
dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);

pickupDateInput.valueAsDate = tomorrow;
returnDateInput.valueAsDate = dayAfterTomorrow;

// Display cars
function displayCars(carsToDisplay) {
    carsGrid.innerHTML = '';

    if (carsToDisplay.length === 0) {
        carsGrid.innerHTML = '<p class="no-results">No cars found matching your criteria.</p>';
        return;
    }

    carsToDisplay.forEach(car => {
        const carCard = document.createElement('div');
        carCard.classList.add('car-card');

        const featuresHTML = car.features.map(feature => 
            `<li><i class="fas fa-check"></i>${feature}</li>`
        ).join('');

        carCard.innerHTML = `
            <img src="${car.image}" alt="${car.name}" class="car-image">
            <div class="car-details">
                <h3 class="car-name">${car.name}</h3>
                <p class="car-category">${car.category.charAt(0).toUpperCase() + car.category.slice(1)}</p>
                <ul class="car-features">
                    ${featuresHTML}
                </ul>
                <div class="car-price">$${car.price} <span>per day</span></div>
                <button class="rent-btn" data-id="${car.id}">Rent Now</button>
            </div>
        `;

        carsGrid.appendChild(carCard);
    });

    // Add event listeners to rent buttons
    const rentButtons = document.querySelectorAll('.rent-btn');
    rentButtons.forEach(button => {
        button.addEventListener('click', () => {
            modal.style.display = 'flex';
            // You could use the data-id to get the selected car
            const carId = button.getAttribute('data-id');
        });
    });
}

// Filter cars
function filterCars() {
    const categoryValue = categoryFilter.value;
    const priceValue = priceFilter.value;

    let filteredCars = [...cars];

    // Filter by category
    if (categoryValue !== 'all') {
        filteredCars = filteredCars.filter(car => car.category === categoryValue);
    }

    // Filter by price
    if (priceValue !== 'all') {
        if (priceValue === '0-50') {
            filteredCars = filteredCars.filter(car => car.price <= 50);
        } else if (priceValue === '50-100') {
            filteredCars = filteredCars.filter(car => car.price > 50 && car.price <= 100);
        } else if (priceValue === '100+') {
            filteredCars = filteredCars.filter(car => car.price > 100);
        }
    }

    displayCars(filteredCars);
}

// Search cars (called when search button is clicked)
function searchCars() {
    // In a real app, this would check availability for the selected dates
    // For now, just scroll to the cars section and show all cars
    const carsSection = document.getElementById('cars');
    carsSection.scrollIntoView({ behavior: 'smooth' });

    // Animation to show that search is being processed
    const searchBtn = document.querySelector('.search-btn');
    searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Searching...';

    setTimeout(() => {
        searchBtn.innerHTML = '<i class="fas fa-search"></i> Search Cars';
        filterCars();
    }, 1000);
}

// Event Listeners
categoryFilter.addEventListener('change', filterCars);
priceFilter.addEventListener('change', filterCars);

// Close modal
closeModalBtn.addEventListener('click', () => {
    modal.style.display = 'none';
});

// Close modal when clicking outside
window.addEventListener('click', (e) => {
    if (e.target === modal) {
        modal.style.display = 'none';
    }
});

// Handle form submission
bookingForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // Show confirmation message
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>Booking Confirmed!</h2>
            <p>Your car rental has been successfully booked. A confirmation email will be sent shortly.</p>
            <button class="book-btn" id="close-confirmation">Close</button>
        </div>
    `;

    // Add event listener to new close button and X
    document.getElementById('close-confirmation').addEventListener('click', () => {
        modal.style.display = 'none';
    });

    document.querySelector('.close').addEventListener('click', () => {
        modal.style.display = 'none';
    });
});

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    // Display all cars on page load
    displayCars(cars);

    // Handle voice interaction
    window.addEventListener('message', function(e) {
        // If you want to handle specific messages from the voice assistant
        if (e.data && e.data.type === 'vapi-action') {
            console.log('Voice action received:', e.data);

            // Example of how to handle voice commands
            if (e.data.action === 'search-cars') {
                searchCars();
            } else if (e.data.action === 'filter-category' && e.data.value) {
                categoryFilter.value = e.data.value;
                filterCars();
            }
        }
    });
});