import { useState, useEffect, useRef } from 'react';
import DateTimePicker from './DateTimePicker';
import api from '../api';
import { Plus, Trash2, Edit, X, Save, Search, Calendar, Hash, User, Shield, Gauge, ImagePlus, Loader, ChevronDown, Clock, CalendarDays, LayoutGrid, Info, Car, Fuel,MapPin } from 'lucide-react';
import { useNavigate } from "react-router-dom";

const CarManagement = () => {
    const [cars, setCars] = useState([]);
    const [allCars, setAllCars] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [activeTab, setActiveTab] = useState('available');
    const [selectedModel, setSelectedModel] = useState('');
    const [modelDropdownOpen, setModelDropdownOpen] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [currentCar, setCurrentCar] = useState({
        brand: '',
        model: '',
        year: new Date().getFullYear(),
        plate_number: '',//added
        plate_category: '',
        city:'',

        price_per_day: '',
        price_per_hour: '',
        price_per_week: '',
        price_per_month: '',

        image_url: '',
        description: '',

        insurance: '',
        owner: '',
        current_km: '',
        current_fuel: '',

        start_date_of_insurance: '',
        end_date_of_insurance: '',

        car_mulkiya_id: '',
        start_date_of_mulkiya: '',
        end_date_of_mulkiya: '',

        maintenance_company: '',
        maintenance_start_date: '',
        maintenance_end_date: '',

        // New Maintenance Fields
        last_battery_change: '',
        last_oil_change_km: '',
        //Oil Change Tracking
        oil_change_interval: '',
        oil_change_completed: false,      // ← NEW - Track if interval is complete
        oil_change_interval_selected: false, // ← NEW - Track if interval was selected

        // Brake Pads Tracking
        brake_pad_interval: '',
        brake_pad_completed: false,       // ← NEW - Track if interval is complete
        brake_pad_interval_selected: false, // ← NEW - Track if interval was selected

        status: 'available',
        rental_options: []
    });
    const navigate = useNavigate();
    const [selectedOption, setSelectedOption] = useState(0);

    const [imagePreview, setImagePreview] = useState('');
    const [uploadingImage, setUploadingImage] = useState(false);
    const [submitted, setSubmitted] = useState(false);
    const fileInputRef = useRef(null);
    const dropdownRef = useRef(null);

const currentYearNum = new Date().getFullYear();
const [selectedYear, setSelectedYear] = useState(currentYearNum);

// Generate years based on selected year (20 years before & after)
const getYearOptions = (year) => {
    const startYear = year - 20;
    const endYear = year + 20;
    return Array.from({ length: endYear - startYear + 1 }, (_, i) => startYear + i).reverse();
};

const yearOptions = getYearOptions(selectedYear);

const getTodayStr = () => {
    const d = new Date();
    return d.toISOString().split('T')[0];
};

const getTomorrowStr = () => {
    const d = new Date();
    d.setDate(d.getDate() + 1);
    return d.toISOString().split('T')[0];
};

const getEndDateMin = (startDate) => {
    let minD = getTomorrowStr();
    if (startDate) {
        const startObj = new Date(startDate);
        startObj.setDate(startObj.getDate() + 1);
        const startStr = startObj.toISOString().split('T')[0];
        if (startStr > minD) minD = startStr;
    }
    return minD;
};

    useEffect(() => {
        const handleClick = (e) => {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
                setModelDropdownOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, []);

    // oilchange
    useEffect(() => {
        // Check if Oil Change Interval is Complete
        if (currentCar.current_km && currentCar.last_oil_change_km && currentCar.oil_change_interval) {
            const kmSinceOil = Number(currentCar.current_km) - Number(currentCar.last_oil_change_km);
            const remainingKm = Number(currentCar.oil_change_interval) - kmSinceOil;

            if (remainingKm <= 0) {
                setCurrentCar(prev => ({ ...prev, oil_change_completed: true }));
            } else {
                setCurrentCar(prev => ({ ...prev, oil_change_completed: false }));
            }
        }
    }
        , [currentCar.current_km, currentCar.last_oil_change_km, currentCar.oil_change_interval]);


    const fetchCars = async () => {
        try {
            const params = new URLSearchParams();
            if (searchTerm) params.append('search', searchTerm);
            const res = await api.get(`/cars${params.toString() ? `?${params}` : ''}`);

            // Response array-ah illana empty array set pannu-nu solrom
            if (Array.isArray(res.data)) {
                setAllCars(res.data);
            } else if (res.data && Array.isArray(res.data.cars)) {
                setAllCars(res.data.cars);
            } else {
                setAllCars([]); // Safety fallback
            }
        } catch (err) {
            console.error('Error fetching cars', err);
            setAllCars([]); // Error vandhalum array-ave erukatum
        }
    };

    useEffect(() => {
        const delaySearch = setTimeout(() => {
            fetchCars();
        }, 300);
        return () => clearTimeout(delaySearch);
    }, [searchTerm]);

    useEffect(() => {
        let filtered = allCars;
        if (activeTab === 'available') {
            filtered = filtered.filter(c => c.status === 'available');
        } else {
            filtered = filtered.filter(c => c.status !== 'available');
        }
        if (selectedModel) {
            filtered = filtered.filter(c => c.model === selectedModel);
        }
        setCars(filtered);
    }, [allCars, activeTab, selectedModel]);

    const uniqueModels = Array.isArray(allCars)
        ? [...new Set(allCars.map(c => c.model).filter(Boolean))].sort()
        : [];

     // added
    const handleSave = async (e) => {
    e.preventDefault();
    setSubmitted(true);

console.log("📝 Status before save:", currentCar.status);
    console.log("📝 Full data:", currentCar);


    //  10 MANDATORY FIELDS
    const requiredFields = [
        'brand', 'model', 'year', 'status',
        'current_km', 'car_mulkiya_id',
        'start_date_of_mulkiya', 'end_date_of_mulkiya',
        'plate_number'
    ];

    const missing = requiredFields.filter(field => !currentCar[field]);

    if (missing.length > 0) {
        alert('❌ Please fill these required fields:\n\n' + missing.join('\n'));
        return;
    }


    const dataToSend = {
        brand: currentCar.brand,
        model: currentCar.model,
        year: parseInt(currentCar.year),
        status: currentCar.status,
        current_km: parseFloat(currentCar.current_km) || 0,
        current_fuel: currentCar.current_fuel,
        car_mulkiya_id: currentCar.car_mulkiya_id,
        plate_number: currentCar.plate_number,
        plate_category: currentCar.plate_category || null,
        city: currentCar.city || null,
        start_date_of_mulkiya: currentCar.start_date_of_mulkiya,
        end_date_of_mulkiya: currentCar.end_date_of_mulkiya,

        // All optional fields as null
        insurance: currentCar.insurance || null,
        owner: currentCar.owner || null,
        description: currentCar.description || null,
        image_url: currentCar.image_url || null,
        start_date_of_insurance: currentCar.start_date_of_insurance || null,
        end_date_of_insurance: currentCar.end_date_of_insurance || null,
        maintenance_company: currentCar.maintenance_company || null,
        maintenance_start_date: currentCar.maintenance_start_date || null,
        maintenance_end_date: currentCar.maintenance_end_date || null,
        last_battery_change: currentCar.last_battery_change || null,
        last_oil_change_km: currentCar.last_oil_change_km || null,
        oil_change_interval: currentCar.oil_change_interval || null,
        rental_options: currentCar.rental_options || []
    };

    try {
        if (currentCar.id) {
            await api.put(`/cars/${currentCar.id}`, dataToSend);
        } else {
            await api.post('/cars', dataToSend);
        }
        alert('✅ Car saved successfully!');
        setIsEditing(false);
        resetForm();
        fetchCars();
    } catch (err) {
        console.error('Error saving car', err);
        if (err.response && err.response.data) {
            alert('❌ Error: ' + JSON.stringify(err.response.data));
        } else {
            alert('❌ Error saving car. Please try again.');
        }
    }
};

    const resetForm = () => {
        setCurrentCar({
            brand: '', model: '', year: new Date().getFullYear(),plate_number: '',plate_category: '',city: '',
            price_per_day: '', price_per_hour: '', price_per_week: '', price_per_month: '',
            image_url: '', description: '',
            insurance: '', owner: '', current_km: '',    // Reset
            current_fuel: '',
            start_date_of_insurance: '', end_date_of_insurance: '', car_mulkiya_id: '', start_date_of_mulkiya: '', end_date_of_mulkiya: '',
            maintenance_company: '', maintenance_start_date: '', maintenance_end_date: '', last_battery_change: '',
            last_oil_change_km: '',
            oil_change_interval: '',

            oil_change_completed: false,
            oil_change_interval_selected: false,

            status: 'available'
        });
        setImagePreview('');
        setSubmitted(false);
    };

    const handleImageUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        setImagePreview(URL.createObjectURL(file));
        setUploadingImage(true);
        try {
            const formData = new FormData();
            formData.append('image', file);
            const res = await api.post('/upload', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            setCurrentCar(prev => ({ ...prev, image_url: res.data.url }));
        } catch (err) {
            console.error('Image upload failed', err);
            alert('Image upload failed. Please try again.');
            setImagePreview('');
        } finally {
            setUploadingImage(false);
        }
    };

    const handleRemoveImage = (e) => {
        e.stopPropagation();
        setImagePreview('');
        setCurrentCar(prev => ({ ...prev, image_url: '' }));
        if (fileInputRef.current) fileInputRef.current.value = '';
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this car?')) {
            try {
                await api.delete(`/cars/${id}`);
                fetchCars();
            } catch (err) {
                console.error('Error deleting car', err);
            }
        }
    };

    const startEdit = (car) => {
        const formattedCar = {
            ...car,
 plate_number: car.plate_number || '', plate_category: car.plate_category || '', city: car.city || '',
            start_date_of_insurance: car.start_date_of_insurance ? car.start_date_of_insurance.split('T')[0] : '',
            end_date_of_insurance: car.end_date_of_insurance ? car.end_date_of_insurance.split('T')[0] : '',
            start_date_of_mulkiya: car.start_date_of_mulkiya ? car.start_date_of_mulkiya.split('T')[0] : '',
            end_date_of_mulkiya: car.end_date_of_mulkiya ? car.end_date_of_mulkiya.split('T')[0] : '',
            maintenance_start_date: car.maintenance_start_date ? car.maintenance_start_date.split('T')[0] : '',
            maintenance_end_date: car.maintenance_end_date ? car.maintenance_end_date.split('T')[0] : '',
            price_per_hour: car.price_per_hour || '',
            price_per_week: car.price_per_week || '',
            price_per_month: car.price_per_month || '',
            last_oil_change_km: car.last_oil_change_km || '',
            oil_change_interval: car.oil_change_interval || '',


        };
        setCurrentCar(formattedCar);
        setImagePreview(car.image_url || '');
        setIsEditing(true);
        setSubmitted(false);
    };

    const toggleStyle = {
        display: 'flex',
        background: 'rgba(15, 23, 42, 0.6)',
        borderRadius: '50px',
        padding: '6px',
        border: '1px solid rgba(255, 255, 255, 0.05)',
        gap: '4px',
        backdropFilter: 'blur(10px)',
    };

    const tabBtnStyle = (active) => ({
        padding: '8px 24px',
        borderRadius: '50px',
        border: 'none',
        fontWeight: 600,
        fontSize: '0.875rem',
        cursor: 'pointer',
        transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
        background: active ? 'linear-gradient(135deg, #a855f7, #c084fc)' : 'transparent',
        color: active ? 'white' : '#94a3b8',
        transform: 'none',
        boxShadow: active ? '0 4px 15px rgba(168, 85, 247, 0.3)' : 'none',
    });

    const availableCount = allCars.filter(c => c.status === 'available').length;
    const reservedCount = allCars.filter(c => c.status !== 'available').length;

    const addPricingOption = (category) => {
        const newOption = {
            id: Date.now(),
            category: category,
            km_limit: '',
            price: ''
        };
        setCurrentCar(prev => ({
            ...prev,
            rental_options: [...(prev.rental_options || []), newOption]
        }));
    };

    const removeOption = (id) => {
        setCurrentCar(prev => ({
            ...prev,
            rental_options: prev.rental_options.filter(opt => opt.id !== id)
        }));
    };

const updateOption = (id, field, value) => {
    // Allow decimal values for price field
    if (field === 'price' && value !== '') {
        // Allow up to 5 decimal places
        const regex = /^\d*\.?\d{0,5}$/;
        if (!regex.test(value)) return;
    }
    // Allow decimal values for km_limit field
    if (field === 'km_limit' && value !== '') {
        // Allow up to 5 decimal places
        const regex = /^\d*\.?\d{0,5}$/;
        if (!regex.test(value)) return;
    }
    setCurrentCar(prev => ({
        ...prev,
        rental_options: prev.rental_options.map(opt =>
            opt.id === id ? { ...opt, [field]: value } : opt
        )
    }));
};


// Move option left (decrease index) - WORKS WITH currentCar.rental_options
const moveOptionLeft = (categoryName, currentIndex) => {
    if (currentIndex <= 0) return;

    // Get the current options for this category
    const currentOptions = currentCar.rental_options?.filter(opt => opt.category === categoryName) || [];
    if (currentIndex >= currentOptions.length) return;

    // Get all rental options
    const allOptions = [...(currentCar.rental_options || [])];

    // Find the actual indices in the full array
    const categoryOptions = allOptions.filter(opt => opt.category === categoryName);
    const currentActualIndex = allOptions.indexOf(categoryOptions[currentIndex]);
    const previousActualIndex = allOptions.indexOf(categoryOptions[currentIndex - 1]);

    // Swap the items in the full array
    [allOptions[currentActualIndex], allOptions[previousActualIndex]] =
    [allOptions[previousActualIndex], allOptions[currentActualIndex]];

    // Update the state
    setCurrentCar({
        ...currentCar,
        rental_options: allOptions
    });
};

// Move option right (increase index)
const moveOptionRight = (categoryName, currentIndex) => {
    // Get the current options for this category
    const currentOptions = currentCar.rental_options?.filter(opt => opt.category === categoryName) || [];
    if (currentIndex >= currentOptions.length - 1) return;

    // Get all rental options
    const allOptions = [...(currentCar.rental_options || [])];

    // Find the actual indices in the full array
    const categoryOptions = allOptions.filter(opt => opt.category === categoryName);
    const currentActualIndex = allOptions.indexOf(categoryOptions[currentIndex]);
    const nextActualIndex = allOptions.indexOf(categoryOptions[currentIndex + 1]);

    // Swap the items in the full array
    [allOptions[currentActualIndex], allOptions[nextActualIndex]] =
    [allOptions[nextActualIndex], allOptions[currentActualIndex]];

    // Update the state
    setCurrentCar({
        ...currentCar,
        rental_options: allOptions
    });
};





    // update for oil & brake changes
    const handleOilChangeKM = (e) => {
        const value = e.target.value;
        setCurrentCar(prev => ({
            ...prev,
            last_oil_change_km: value,
            oil_change_completed: false
        }));
    };

    return (
        <div>
            <style>{`
                 .input-icon-wrapper {
                    position: relative;
                    width: 100%;
                }
                .input-icon-wrapper svg {
                    position: absolute;
                    left: 12px;
                    top: 50%;
                    transform: translateY(-50%);
                    color: rgba(148, 163, 184, 0.45);
                    pointer-events: none;
                    transition: all 0.25s ease;
                }
                .input-icon-wrapper input:focus ~ svg,
                .input-icon-wrapper select:focus ~ svg,
                .input-icon-wrapper input:hover ~ svg,
                .input-icon-wrapper select:hover ~ svg {
                    color: #a855f7;
                }
                .input-icon-wrapper select {
                    appearance: none !important;
                    -webkit-appearance: none !important;
                    -moz-appearance: none !important;
                    padding-right: 36px !important;
                    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2394a3b8' stroke-width='2'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'/%3E%3C/svg%3E") !important;
                    background-repeat: no-repeat !important;
                    background-position: right 12px center !important;
                    background-size: 14px !important;
                }
                .input-icon-wrapper select:focus {
                    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23a855f7' stroke-width='2'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'/%3E%3C/svg%3E") !important;
                }
                .glass-input {
                    background-color: rgba(15, 23, 42, 0.55) !important;
                    border: 1px solid rgba(255, 255, 255, 0.08) !important;
                    color: white !important;
                    font-family: "Maiandra GD", sans-serif !important;
                    border-radius: 8px !important;
                    padding: 9px 14px 9px 38px !important;
                    font-size: 14px !important;
                    height: auto !important;
                    width: 100%;
                    margin-bottom: 0 !important;
                    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
                }
                .glass-input:hover {
                    background-color: rgba(15, 23, 42, 0.75) !important;
                    border-color: rgba(168, 85, 247, 0.45) !important;
                }
                .glass-input:focus {
                    border-color: #a855f7 !important;
                    box-shadow: 0 0 0 0.25rem rgba(168, 85, 247, 0.25) !important;
                    background-color: rgba(15, 23, 42, 0.9) !important;
                    outline: none;
                }
                .glass-input option {
                    background: #1e1d24 !important;
                    color: white !important;
                }
                .field-label {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    color: #94a3b8;
                    font-size: 0.725rem;
                    text-transform: uppercase;
                    font-weight: 700;
                    margin-bottom: 6px;
                    letter-spacing: 0.06em;
                }
                .form-card {
                    background: linear-gradient(135deg, rgba(30, 41, 59, 0.45) 0%, rgba(15, 23, 42, 0.45) 100%) !important;
                    border: 1px solid rgba(255, 255, 255, 0.08) !important;
                    border-radius: 16px !important;
                    padding: 1.25rem !important;
                    margin-bottom: 1.25rem;
                    backdrop-filter: blur(16px);
                    box-shadow: 0 12px 30px -10px rgba(0, 0, 0, 0.6);
                    transition: all 0.3s ease;
                }
                .form-card:hover {
                    border-color: rgba(255, 255, 255, 0.12) !important;
                    box-shadow: 0 16px 36px -8px rgba(0, 0, 0, 0.7);
                }
                .form-card-title {
                    margin: 0 0 1.25rem 0;
                    color: #f8fafc;
                    font-size: 0.975rem;
                    font-weight: 700;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    border-left: 3px solid #a855f7;
                    padding-left: 10px;
                    padding-bottom: 2px;
                    letter-spacing: 0.02em;
                }
                .form-grid-2 {
                    display: grid;
                    grid-template-columns: repeat(2, 1fr);
                    gap: 0.75rem;
                }
                .form-grid-3 {
                    display: grid;
                    grid-template-columns: repeat(3, 1fr);
                    gap: 0.75rem;
                }
                .pkg-card {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    background: rgba(15, 23, 42, 0.8) !important;
                    border: 1px solid rgba(255, 255, 255, 0.08) !important;
                    border-radius: 10px !important;
                    padding: 8px 12px !important;
                    position: relative;
                    min-width: 155px;
                    flex-shrink: 0;
                    transition: all 0.25s ease;
                }
                .pkg-card:hover {
                    border-color: rgba(168, 85, 247, 0.4) !important;
                    transform: translateY(-2px);
                    box-shadow: 0 6px 18px rgba(168, 85, 247, 0.15);
                }
                .submit-btn {
                    background: linear-gradient(135deg, #7c3aed, #a855f7) !important;
                    color: white !important;
                    border: none !important;
                    border-radius: 8px !important;
                    padding: 12px 24px !important;
                    font-weight: 700 !important;
                    font-size: 15px !important;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 8px;
                    cursor: pointer;
                    box-shadow: 0 4px 14px rgba(124, 58, 237, 0.3);
                    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
                }
                .submit-btn:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 6px 20px rgba(124, 58, 237, 0.45);
                    filter: brightness(1.1);
                }
                .submit-btn:active {
                    transform: translateY(1px);
                    box-shadow: 0 2px 8px rgba(124, 58, 237, 0.3);
                }
                .cancel-btn {
                    background: rgba(255, 255, 255, 0.03) !important;
                    color: #94a3b8 !important;
                    border: 1px solid rgba(255, 255, 255, 0.08) !important;
                    border-radius: 8px !important;
                    padding: 12px 24px !important;
                    font-weight: 600 !important;
                    font-size: 15px !important;
                    cursor: pointer;
                    transition: all 0.2s ease;
                }
                .cancel-btn:hover {
                    background: rgba(255, 255, 255, 0.08) !important;
                    border-color: rgba(255, 255, 255, 0.15) !important;
                    color: white !important;
                }
                .add-opt-btn {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    cursor: pointer;
                    color: #94a3b8 !important;
                    font-size: 11px !important;
                    transition: all 0.2s ease;
                }
                .add-opt-btn:hover {
                    color: #ffffff !important;
                }
                .img-remove-btn:hover {
                    transform: scale(1.15) !important;
                    background: rgb(220, 38, 38) !important;
                }


       /* ── CarManagement Mobile Responsive Styles ── */



/* ─── Fix for Mobile Header Layout ─── */

/* Main header container - fix for mobile */
@media (max-width: 767.98px) {
    /* The flex container that holds everything */
    div[style*="display: flex"][style*="justify-content: space-between"] {
        flex-direction: column !important;
        align-items: stretch !important;
        gap: 12px !important;
    }

    /* The inner flex container with search + buttons */
    div[style*="display: flex"][style*="gap: 1rem"][style*="align-items: center"] {
        flex-direction: column !important;
        width: 100% !important;
        gap: 10px !important;
    }

    /* Search input wrapper */
    div[style*="position: relative"][style*="min-width: 220px"] {
        width: 100% !important;
        min-width: unset !important;
    }

    /* Search input */
    div[style*="position: relative"][style*="min-width: 220px"] input {
        width: 100% !important;
        font-size: 14px !important;
        height: 40px !important;
        padding-left: 36px !important;
    }

    /* Model dropdown button */
    div[ref] button {
        width: 100% !important;
        justify-content: center !important;
        height: 40px !important;
        font-size: 0.8rem !important;
    }

    /* Model dropdown wrapper */
    div[ref] {
        width: 100% !important;
    }

    /* Add New Car button */
    button[style*="background: linear-gradient(135deg, #7c3aed"] {
        width: 100% !important;
        justify-content: center !important;
        height: 40px !important;
        font-size: 0.8rem !important;
    }

    /* Search icon inside input */
    div[style*="position: relative"][style*="min-width: 220px"] svg {
        left: 12px !important;
        width: 14px !important;
        height: 14px !important;
    }
}

/* Extra small phones */
@media (max-width: 420px) {
    div[style*="display: flex"][style*="gap: 1rem"][style*="align-items: center"] {
        gap: 8px !important;
    }

    div[style*="position: relative"][style*="min-width: 220px"] input {
        font-size: 13px !important;
        height: 36px !important;
        padding-left: 32px !important;
    }

    div[ref] button {
        height: 36px !important;
        font-size: 0.7rem !important;
        padding: 4px 12px !important;
    }

    button[style*="background: linear-gradient(135deg, #7c3aed"] {
        height: 36px !important;
        font-size: 0.7rem !important;
        padding: 0 12px !important;
    }

    /* Hide "Fleet Management" text or make smaller */
    h1[style*="font-size: 1.75rem"] {
        font-size: 1.2rem !important;
        text-align: center !important;
    }
}

/* Landscape mobile - keep in row */
@media (max-width: 767.98px) and (orientation: landscape) {
    div[style*="display: flex"][style*="gap: 1rem"][style*="align-items: center"] {
        flex-direction: row !important;
        flex-wrap: wrap !important;
    }

    div[style*="position: relative"][style*="min-width: 220px"] {
        flex: 1 !important;
        min-width: 150px !important;
    }

    div[ref] {
        flex: 0 0 auto !important;
        width: auto !important;
    }

    div[ref] button {
        width: auto !important;
    }

    button[style*="background: linear-gradient(135deg, #7c3aed"] {
        flex: 0 0 auto !important;
        width: auto !important;
    }
}




/* Tablet and below */
@media (max-width: 991.98px) {
    /* Form layout - stack columns */
    form[style*="grid-template-columns: 1.2fr 1fr"] {
        grid-template-columns: 1fr !important;
        gap: 1rem !important;
    }

    /* Form grid - 3 columns to 2 */
    .form-grid-3 {
        grid-template-columns: repeat(2, 1fr) !important;
    }

    /* Header - wrap properly */
    .car-management-header {
        flex-direction: column !important;
        align-items: stretch !important;
    }
}

/* Mobile phones */
@media (max-width: 767.98px) {
    /* Main container padding */
    .car-management-container {
        padding-left: 10px !important;
        padding-right: 10px !important;
    }

    /* Form grids - single column */
    .form-grid-2 {
        grid-template-columns: 1fr !important;
        gap: 0.75rem !important;
    }

    .form-grid-3 {
        grid-template-columns: 1fr !important;
        gap: 0.75rem !important;
    }

    /* Header */
    .car-management-header h1 {
        font-size: 1.3rem !important;
    }

    /* Search and filters - stack vertically */
    .car-management-header > div {
        flex-direction: column !important;
        width: 100% !important;
    }

    .car-management-header .input-icon-wrapper {
        width: 100% !important;
    }

    /* Add New Car button - full width */
    .car-management-header button[style*="background: linear-gradient"] {
        width: 100% !important;
        justify-content: center !important;
    }

    /* Tabs - full width on mobile */
    .car-management-tabs {
        width: 100% !important;
        overflow-x: auto !important;
        flex-wrap: nowrap !important;
    }

    .car-management-tabs button {
        padding: 8px 16px !important;
        font-size: 0.75rem !important;
        white-space: nowrap !important;
    }

    /* Car grid - single column */
    .car-grid {
        grid-template-columns: 1fr !important;
        gap: 1rem !important;
    }

    /* Car card - adjust layout */
    .car-card {
        margin-bottom: 0 !important;
    }

    .car-card .car-img {
        height: 160px !important;
    }

    .car-card .car-info {
        padding: 1rem !important;
    }

    .car-card .car-info h3 {
        font-size: 1.1rem !important;
    }

    /* Car action buttons - stack */
    .car-card .action-buttons {
        grid-template-columns: 1fr !important;
        gap: 6px !important;
    }

    .car-card .action-buttons button {
        padding: 8px !important;
        font-size: 12px !important;
    }

    /* Form card */
    .form-card {
        padding: 1rem !important;
    }

    .form-card-title {
        font-size: 0.85rem !important;
    }

    /* Pricing options - scroll horizontally */
    .pricing-container {
        flex-direction: column !important;
        gap: 10px !important;
    }

    .pricing-container .pkg-card {
        min-width: 140px !important;
    }

    /* Image upload */
    .image-upload-container {
        flex-direction: column !important;
        align-items: center !important;
    }

    .image-upload-container > div:first-child {
        width: 100% !important;
        min-width: auto !important;
    }

    /* Form buttons */
    .form-buttons {
        flex-direction: column !important;
        gap: 8px !important;
    }

    .form-buttons button {
        width: 100% !important;
        justify-content: center !important;
    }

    /* Status badge - smaller */
    .status-badge {
        font-size: 0.6rem !important;
        padding: 2px 8px !important;
    }

    /* Model dropdown - full width */
    .model-dropdown-container {
        width: 100% !important;
    }

    /* Availability modal - full screen */
    .avail-modal {
        width: 100% !important;
        max-width: 100% !important;
        height: 100% !important;
        max-height: 100% !important;
        border-radius: 0 !important;
        padding: 0.8rem !important;
    }

    .avail-grid {
        gap: 2px !important;
    }

    .avail-cell {
        height: 24px !important;
        font-size: 10px !important;
    }

    /* Rental pricing tiers */
    .rental-tier {
        flex-direction: column !important;
        align-items: stretch !important;
        gap: 8px !important;
        padding: 10px 12px !important;
    }

    .rental-tier .tier-label {
        min-width: auto !important;
        border-right: none !important;
        border-bottom: 1px solid rgba(255,255,255,0.1) !important;
        padding-right: 0 !important;
        padding-bottom: 8px !important;
        flex-direction: row !important;
        justify-content: space-between !important;
    }

    .rental-tier .tier-options {
        gap: 8px !important;
        padding-top: 4px !important;
    }

    .rental-tier .pkg-card {
        min-width: 120px !important;
        padding: 6px 10px !important;
    }
}

/* Very small phones */
@media (max-width: 420px) {
    /* Smaller fonts */
    .car-management-header h1 {
        font-size: 1.1rem !important;
    }

    .car-card .car-info h3 {
        font-size: 1rem !important;
    }

    .car-card .car-info .price-text {
        font-size: 1.2rem !important;
    }

    /* Category buttons - smaller */
    .category-toggle button {
        padding: 4px 10px !important;
        font-size: 9px !important;
    }

    /* KM pills - wrap */
    .km-pills {
        gap: 4px !important;
    }

    .km-pills button {
        padding: 2px 8px !important;
        font-size: 9px !important;
    }

    /* Availability calendar - smaller */
    .avail-cell {
        height: 20px !important;
        font-size: 8px !important;
        border-radius: 4px !important;
    }

    .avail-dow {
        font-size: 7px !important;
    }

    /* Form inputs - smaller */
    .glass-input {
        font-size: 12px !important;
        padding: 7px 12px 7px 34px !important;
        height: auto !important;
    }

    .input-icon-wrapper svg {
        left: 10px !important;
        width: 14px !important;
        height: 14px !important;
    }

    /* Buttons - smaller */
    .submit-btn, .cancel-btn {
        padding: 10px 16px !important;
        font-size: 13px !important;
    }

    .field-label {
        font-size: 0.65rem !important;
    }
}

/* Landscape mobile */
@media (max-width: 767.98px) and (orientation: landscape) {
    .form-grid-2 {
        grid-template-columns: repeat(2, 1fr) !important;
    }

    .form-grid-3 {
        grid-template-columns: repeat(3, 1fr) !important;
    }

    .car-grid {
        grid-template-columns: repeat(2, 1fr) !important;
    }

    .car-card .car-img {
        height: 140px !important;
    }
}

/* Touch device optimizations */
@media (hover: none) and (pointer: coarse) {
    /* Larger touch targets */
    button,
    .clickable,
    .avail-btn,
    .add-opt-btn {
        min-height: 44px !important;
        min-width: 44px !important;
    }

    /* Remove hover effects on touch devices */
    .glass:hover {
        transform: none !important;
    }

    .pkg-card:hover {
        transform: none !important;
    }

    .submit-btn:hover,
    .cancel-btn:hover {
        transform: none !important;
    }
}


/* ─── Fix Dropdown Overflow ─── */

/* Model Dropdown - make sure it stays within viewport */
.model-dropdown-container {
    position: relative !important;
    width: 100% !important;
    max-width: 100% !important;
}

.model-dropdown-container .dropdown-menu {
    position: absolute !important;
    top: calc(100% + 6px) !important;
    left: 0 !important;
    right: 0 !important;
    max-height: 200px !important;
    overflow-y: auto !important;
    background: #1e293b !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    border-radius: 10px !important;
    box-shadow: 0 10px 40px rgba(0,0,0,0.4) !important;
    z-index: 9999 !important;
    min-width: 180px !important;
}

/* Fix for mobile - ensure dropdown fits screen */
@media (max-width: 767.98px) {
    .model-dropdown-container .dropdown-menu {
        position: fixed !important;
        top: auto !important;
        bottom: 0 !important;
        left: 10px !important;
        right: 10px !important;
        max-height: 50vh !important;
        border-radius: 16px 16px 0 0 !important;
        width: calc(100% - 20px) !important;
        max-width: none !important;
        padding-bottom: env(safe-area-inset-bottom, 20px) !important;
    }

    /* Better dropdown items for touch */
    .model-dropdown-container .dropdown-menu > div {
        padding: 14px 16px !important;
        font-size: 15px !important;
        min-height: 48px !important;
    }
}

/* Fix for very small screens */
@media (max-width: 420px) {
    .model-dropdown-container .dropdown-menu {
        left: 8px !important;
        right: 8px !important;
        width: calc(100% - 16px) !important;
        max-height: 45vh !important;
    }
}

/* General dropdown fix - ensure all dropdowns stay in viewport */
.position-relative .dropdown-menu,
[ref] .dropdown-menu {
    max-width: calc(100vw - 20px) !important;
    overflow: hidden !important;
}

/* Fix for DateTimePicker dropdown if used */
.react-datepicker-popper {
    z-index: 9999 !important;
}

@media (max-width: 767.98px) {
    .react-datepicker-popper {
        position: fixed !important;
        bottom: 0 !important;
        left: 0 !important;
        right: 0 !important;
        transform: none !important;
        max-height: 60vh !important;
        overflow-y: auto !important;
    }

    .react-datepicker {
        width: 100% !important;
        border-radius: 16px 16px 0 0 !important;
    }

    .react-datepicker__month-container {
        width: 100% !important;
    }
}

/* Fix for select dropdowns in general */
select.glass-input option {
    background: #1e293b !important;
    color: #e2e8f0 !important;
    padding: 8px 12px !important;
}

@media (max-width: 767.98px) {
    select.glass-input {
        font-size: 16px !important; /* Prevents iOS zoom */
    }
}


.custom-datetime-input * {
    white-space: nowrap !important;
    font-size: 0.82rem !important;
}
            `}</style>
            {/* Header: show full toolbar only when NOT editing */}
            {!isEditing && (
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', gap: '1rem', flexWrap: 'wrap' }}>
                    <h1 style={{
                        margin: 0, fontSize: '1.75rem', fontWeight: 800,
                        background: 'linear-gradient(135deg, #f8fafc 0%, #c084fc 100%)',
                        WebkitBackgroundClip: 'text',
                        WebkitTextFillColor: 'transparent',
                        letterSpacing: '-0.5px'
                    }}>Fleet Management</h1>
                    <div style={{ display: 'flex', gap: '1rem', alignItems: 'center', flex: 1, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
                        <div style={{ position: 'relative', minWidth: '220px' }}>
                            <Search size={16} style={{ position: 'absolute', left: '14px', top: '50%', transform: 'translateY(-50%)', color: '#64748b' }} />
                            <input
                                className="glass-input"
                                value={searchTerm}
                                onChange={e => setSearchTerm(e.target.value)}
                                placeholder="Search brand, model, owner..."
                                style={{ paddingLeft: '40px', marginBottom: 0, height: '42px', borderRadius: '10px', fontSize: '0.875rem', width: '100%' }}
                            />
                        </div>

                        <div ref={dropdownRef} style={{ position: 'relative' }}>
                            <button
                                onClick={() => setModelDropdownOpen(o => !o)}
                                style={{
                                    display: 'flex', alignItems: 'center', gap: '8px',
                                    background: selectedModel ? 'rgba(168, 85, 247, 0.15)' : 'rgba(15, 23, 42, 0.55)',
                                    border: `1px solid ${selectedModel ? 'rgba(168, 85, 247, 0.4)' : 'rgba(255, 255, 255, 0.08)'}`,
                                    color: selectedModel ? '#c084fc' : '#94a3b8',
                                    padding: '8px 16px', borderRadius: '10px', fontWeight: 500, fontSize: '0.875rem',
                                    whiteSpace: 'nowrap', height: '42px', transition: 'all 0.3s ease'
                                }}
                            >
                                <LayoutGrid size={15} />
                                {selectedModel || 'All Models'}
                                <ChevronDown size={14} style={{ transition: 'transform 0.2s', transform: modelDropdownOpen ? 'rotate(180deg)' : 'none' }} />
                            </button>
                            {modelDropdownOpen && (
                                <div style={{
                                    position: 'absolute', top: 'calc(100% + 6px)', right: 0, minWidth: '180px',
                                    background: '#1e293b', border: '1px solid rgba(255,255,255,0.1)',
                                    borderRadius: '10px', zIndex: 100, overflow: 'hidden',
                                    boxShadow: '0 10px 40px rgba(0,0,0,0.4)'
                                }}>
                                    <div
                                        onClick={() => { setSelectedModel(''); setModelDropdownOpen(false); }}
                                        style={{
                                            padding: '10px 16px', cursor: 'pointer', fontSize: '0.875rem',
                                            color: !selectedModel ? '#c084fc' : '#e2e8f0',
                                            background: !selectedModel ? 'rgba(168, 85, 247, 0.1)' : 'transparent',
                                            fontWeight: !selectedModel ? 600 : 400,
                                            transition: 'background 0.15s'
                                        }}
                                    >
                                        All Models
                                    </div>
                                    {uniqueModels.map(model => (
                                        <div
                                            key={model}
                                            onClick={() => { setSelectedModel(model); setModelDropdownOpen(false); }}
                                            style={{
                                                padding: '10px 16px', cursor: 'pointer', fontSize: '0.875rem',
                                                color: selectedModel === model ? '#c084fc' : '#e2e8f0',
                                                background: selectedModel === model ? 'rgba(168, 85, 247, 0.1)' : 'transparent',
                                                fontWeight: selectedModel === model ? 600 : 400,
                                                transition: 'background 0.15s',
                                                borderTop: '1px solid rgba(255,255,255,0.05)'
                                            }}
                                        >
                                            {model}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        <button
                            onClick={() => { setIsEditing(true); resetForm(); }}
                            style={{
                                display: 'flex', alignItems: 'center', gap: '8px', whiteSpace: 'nowrap',
                                height: '42px', padding: '0 20px', borderRadius: '10px',
                                background: 'linear-gradient(135deg, #7c3aed 0%, #a855f7 100%)',
                                color: 'white', border: 'none', fontWeight: 600, fontSize: '0.9rem',
                                boxShadow: '0 4px 15px rgba(124, 58, 237, 0.3)',
                                transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
                            }}
                            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 20px rgba(124, 58, 237, 0.4)'; }}
                            onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 4px 15px rgba(124, 58, 237, 0.3)'; }}
                        >
                            <Plus size={18} /> Add New Car
                        </button>
                    </div>
                </div>
            )}

            {/* Tabs & filters: hide while editing */}
            {!isEditing && (
                <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '1.75rem', flexWrap: 'wrap' }}>
                    <div style={toggleStyle}>
                        <button onClick={() => setActiveTab('available')} style={tabBtnStyle(activeTab === 'available')}>
                            Available <span style={{ marginLeft: '6px', fontSize: '0.75rem', fontWeight: 700, background: activeTab === 'available' ? 'rgba(255,255,255,0.25)' : 'rgba(255,255,255,0.08)', padding: '1px 7px', borderRadius: '50px' }}>{availableCount}</span>
                        </button>
                        <button onClick={() => setActiveTab('reserved')} style={tabBtnStyle(activeTab === 'reserved')}>
                            Reserved <span style={{ marginLeft: '6px', fontSize: '0.75rem', fontWeight: 700, background: activeTab === 'reserved' ? 'rgba(255,255,255,0.25)' : 'rgba(255,255,255,0.08)', padding: '1px 7px', borderRadius: '50px' }}>{reservedCount}</span>
                        </button>
                    </div>

                    {selectedModel && (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px', background: 'rgba(168, 85, 247, 0.1)', border: '1px solid rgba(168, 85, 247, 0.3)', borderRadius: '50px', padding: '4px 12px', fontSize: '0.8rem', color: '#c084fc' }}>
                            <span>Model: <strong>{selectedModel}</strong></span>
                            <button onClick={() => setSelectedModel('')} style={{ background: 'none', border: 'none', color: '#c084fc', cursor: 'pointer', padding: '0', display: 'flex', alignItems: 'center', transform: 'none' }}><X size={14} /></button>
                        </div>
                    )}
                </div>
            )}

            {isEditing && (
                <div style={{ marginBottom: '2rem' }}>
                    <style>
                        {`
                        .was-validated .glass-input:invalid {
                            border: 1px solid #ef4444 !important;
                            box-shadow: 0 0 5px rgba(239, 68, 68, 0.5) !important;
                        }
                        `}
                    </style>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
                        <h3 style={{ margin: 0, color: '#a855f7', fontWeight: 700 }}>{currentCar.id ? 'Edit Car Details' : 'Register New Car'}</h3>
                        <button type="button" onClick={() => setIsEditing(false)} style={{ background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', padding: '4px' }}>
                            <X size={24} />
                        </button>
                    </div>

                    <form onSubmit={handleSave} className={submitted ? 'was-validated' : ''} style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '1.5rem' }}>
                        {/* Left Column */}
                        <div>
                            {/* Vehicle Information */}
                            <div className="form-card">
                                <h4 className="form-card-title"><LayoutGrid size={16} /> Vehicle Information</h4>
                                <div className="form-grid-2">
                                    <div>
                                        <label className="field-label">Brand<span style={{color: '#ef4444'}}>*</span></label>
                                        <div className="input-icon-wrapper">
                                            <input className="glass-input" value={currentCar.brand} onChange={e => setCurrentCar({ ...currentCar, brand: e.target.value })} required />
                                            <Car size={16} />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="field-label">Model<span style={{color: '#ef4444'}}>*</span></label>
                                        <div className="input-icon-wrapper">
                                            <input className="glass-input" value={currentCar.model} onChange={e => setCurrentCar({ ...currentCar, model: e.target.value })} required />
                                            <Car size={16} />
                                        </div>
                                    </div>
                                </div>
                                <div className="form-grid-3" style={{ marginTop: '1rem' }}>
                                    <div>
                                        <label className="field-label">Year<span style={{color: '#ef4444'}}>*</span></label>
                                        <div className="input-icon-wrapper">
<select
    className="glass-input"
    value={currentCar.year}
    onChange={(e) => {
        const newYear = parseInt(e.target.value);
        setSelectedYear(newYear);
        setCurrentCar({ ...currentCar, year: newYear });
    }}
    required
>
    {yearOptions.map(y => <option key={y} value={y}>{y}</option>)}
</select>
                                            <CalendarDays size={16} />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="field-label">Status<span style={{color: '#ef4444'}}>*</span></label>
                                        <div className="input-icon-wrapper">
                                            <select className="glass-input" value={currentCar.status} onChange={e => setCurrentCar({ ...currentCar, status: e.target.value })} required>
                                                <option value="available">Available</option>
                                                <option value="reserved">Reserved</option>
                                                <option value="maintenance">Maintenance</option>
                                            </select>
                                            <Info size={16} />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="field-label">Current KM<span style={{color: '#ef4444'}}>*</span></label>
                                        <div className="input-icon-wrapper">
                                            <input type="number" min="0" onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }} className="glass-input" value={currentCar.current_km} onChange={e => setCurrentCar({ ...currentCar, current_km: e.target.value })} placeholder="Enter KM" required />
                                            <Gauge size={16} />
                                        </div>
                                    </div>
                                </div>
                                <div className="form-grid-3" style={{ marginTop: '1rem' }}>
 <div>
        <label className="field-label">City</label>
        <div className="input-icon-wrapper">
            <input
                className="glass-input"
                value={currentCar.city || ''}
                onChange={e => setCurrentCar({ ...currentCar, city: e.target.value })}
                placeholder="eg:Dubai,Abu Dhabi"
            />
            <MapPin size={16} />
        </div>
    </div>

    <div>
        <label className="field-label">Plate Category</label>
        <div className="input-icon-wrapper">
            <input
                className="glass-input"
                value={currentCar.plate_category || ''}
                onChange={e => setCurrentCar({ ...currentCar, plate_category: e.target.value })}
                //placeholder="e.g., Private, Commercial"
            />
            <Hash size={16} />
        </div>
    </div>

    <div>
        <label className="field-label">Plate Number <span style={{ color: '#ef4444' }}>*</span></label>
        <div className="input-icon-wrapper">
            <input
                className="glass-input"
                value={currentCar.plate_number || ''}
                onChange={e => setCurrentCar({ ...currentCar, plate_number: e.target.value })}
                placeholder="Enter plate number"
                required
            />
            <Hash size={16} />
        </div>
    </div>

</div>

                                <div className="form-grid-2" style={{ marginTop: '1rem' }}>
                                    <div>
                                        <label className="field-label">Current Fuel</label>
                                        <div className="input-icon-wrapper">
                                            <select className="glass-input" value={currentCar.current_fuel||''} onChange={e => setCurrentCar({ ...currentCar, current_fuel: e.target.value })} >
                                                <option value="">Select Fuel Level</option>
                                                <option value="Full Tank">Full Tank</option>
                                                <option value="7/8">7/8</option>
                                                <option value="3/4">3/4</option>
                                                <option value="1/2">1/2</option>
                                                <option value="1/4">1/4</option>
                                                <option value="1/8">1/8</option>
                                                <option value="Empty">Empty</option>
                                            </select>
                                            <Fuel size={16} />
                                        </div>
                                    </div>


                                    <div>
                                        <label className="field-label">Owner Name</label>
                                        <div className="input-icon-wrapper">
                                            <input className="glass-input" value={currentCar.owner} onChange={e => setCurrentCar({ ...currentCar, owner: e.target.value })} />
                                            <User size={16} />
                                        </div>
                                    </div>
                                </div>
                            </div>




      <div className="form-card">
                                <h4 className="form-card-title"><Shield size={16} /> Registration & Insurance</h4>
                                <div className="form-grid-3">
                                    <div>
                                        <label className="field-label">Insurance Company</label>
                                        <div className="input-icon-wrapper">
                                            <input className="glass-input" value={currentCar.insurance} onChange={e => setCurrentCar({ ...currentCar, insurance: e.target.value })} />
                                            <Shield size={16} />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="field-label">Start Date (Ins)</label>
                                        <DateTimePicker
                                            value={currentCar.start_date_of_insurance || ""}
                                            onChange={(iso) => setCurrentCar({ ...currentCar, start_date_of_insurance: iso })}
                                            placeholder="DD-MM-YYYY"
                                            className="custom-datetime-input"
                                        />
                                    </div>
                                    <div>
                                        <label className="field-label">End Date (Ins)</label>
                                        <DateTimePicker
                                            value={currentCar.end_date_of_insurance || ""}
                                            onChange={(iso) => setCurrentCar({ ...currentCar, end_date_of_insurance: iso })}
                                            placeholder="DD-MM-YYYY"
                                            className="custom-datetime-input"
                                        />
                                    </div>
                                </div>
                                <div className="form-grid-3" style={{ marginTop: '1rem' }}>
                                    <div>
                                        <label className="field-label">Car Mulkiya ID<span style={{color: '#ef4444'}}>*</span></label>
                                        <div className="input-icon-wrapper">
                                            <input className="glass-input" value={currentCar.car_mulkiya_id} onChange={e => setCurrentCar({ ...currentCar, car_mulkiya_id: e.target.value })} required />
                                            <Hash size={16} />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="field-label">Start Date (Mulkiya)<span style={{color: '#ef4444'}}>*</span></label>
                                        <DateTimePicker
                                            value={currentCar.start_date_of_mulkiya || ""}
                                            onChange={(iso) => setCurrentCar({ ...currentCar, start_date_of_mulkiya: iso })}
                                            placeholder="DD-MM-YYYY"
                                            className="custom-datetime-input"
                                        />
                                    </div>
                                    <div>
                                        <label className="field-label">End Date (Mulkiya)<span style={{color: '#ef4444'}}>*</span></label>
                                        <DateTimePicker
                                            value={currentCar.end_date_of_mulkiya || ""}
                                            onChange={(iso) => setCurrentCar({ ...currentCar, end_date_of_mulkiya: iso })}
                                            placeholder="DD-MM-YYYY"
                                            className="custom-datetime-input"
                                        />
                                    </div>
                                </div>
                            </div>



                            {/* Media & Details */}
                            <div className="form-card">
                                <h4 className="form-card-title"><ImagePlus size={16} /> Media & Details</h4>
                                <div style={{ display: 'flex', gap: '1rem', alignItems: 'flex-start' }}>
                                    <div
                                        onClick={() => fileInputRef.current.click()}
                                        style={{
                                            border: '2px dashed rgba(124, 58, 237, 0.4)',
                                            borderRadius: '10px',
                                            padding: imagePreview ? '4px' : '1.5rem',
                                            cursor: 'pointer',
                                            textAlign: 'center',
                                            overflow: 'hidden',
                                            minWidth: '150px',
                                            position: 'relative',
                                            background: 'rgba(15,23,42,0.3)'
                                        }}
                                    >
                                        {uploadingImage && (
                                            <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(15,23,42,0.7)', zIndex: 2 }}>
                                                <Loader size={24} color="#7c3aed" />
                                            </div>
                                        )}

                                        {imagePreview && (
                                            <button
                                                type="button"
                                                onClick={handleRemoveImage}
                                                style={{
                                                    position: 'absolute',
                                                    top: '6px',
                                                    right: '6px',
                                                    background: 'rgba(239, 68, 68, 0.9)',
                                                    border: 'none',
                                                    color: 'white',
                                                    borderRadius: '50%',
                                                    width: '20px',
                                                    height: '20px',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'center',
                                                    padding: 0,
                                                    cursor: 'pointer',
                                                    zIndex: 10,
                                                    transition: 'all 0.2s'
                                                }}
                                                className="img-remove-btn"
                                            >
                                                <X size={12} />
                                            </button>
                                        )}

                                        {imagePreview ? (
                                            <img
                                                src={imagePreview}
                                                alt="Preview"
                                                style={{
                                                    display: 'block',
                                                    maxHeight: '110px',
                                                    width: 'auto',
                                                    borderRadius: '8px'
                                                }}
                                            />
                                        ) : (
                                            <div style={{ color: '#64748b', fontSize: '11px' }}>
                                                <ImagePlus size={28} style={{ marginBottom: '4px' }} />
                                                <p style={{ margin: 0 }}>Click to upload image</p>
                                            </div>
                                        )}
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        <label className="field-label">Description</label>
                                        <textarea className="glass-input" value={currentCar.description} onChange={e => setCurrentCar({ ...currentCar, description: e.target.value })} style={{ height: '118px', resize: 'none' }} />
                                    </div>
                                </div>
                                <input ref={fileInputRef} type="file" accept="image/*" onChange={handleImageUpload} style={{ display: 'none' }} />

                            </div>

                        </div>



                        {/* Right Column */}
                        <div style={{ minWidth: 0 }}>

                            {/* Rental Pricing Tiers */}
                            <div className="form-card">
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', borderBottom: '1px solid rgba(255, 255, 255, 0.05)', paddingBottom: '8px' }}>
                                    <h4 style={{ margin: 0, color: '#ffffff', fontSize: '1rem', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '8px' }}><LayoutGrid size={16} /> Rental Pricing Tiers</h4>
                                    <div style={{ display: 'flex', gap: '6px' }}>
                                        {['Hour', 'Day', 'Week', 'Month'].map(cat => (
                                            <button
                                                key={cat}
                                                type="button"
                                                onClick={() => addPricingOption(`Per ${cat}`)}
                                                style={{ padding: '4px 10px', fontSize: '10px', background: '#7c3aed', borderRadius: '6px', border: 'none', color: 'white', cursor: 'pointer', fontWeight: 'bold' }}
                                            >
                                                + {cat}
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                <div style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
                                    {['Per Hour', 'Per Day', 'Per Week', 'Per Month'].map(categoryName => {
                                        const filteredOptions = currentCar.rental_options?.filter(opt => opt.category === categoryName) || [];

                                        return (
                                            <div key={categoryName} style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '20px',
                                                background: 'rgba(255,255,255,0.02)',
                                                padding: '12px 15px',
                                                borderRadius: '12px',
                                                border: '1px solid rgba(255,255,255,0.05)',
                                                width: '100%',
                                                overflow: 'hidden'
                                            }}>
                                                <div style={{
                                                    minWidth: '110px',
                                                    display: 'flex',
                                                    flexDirection: 'column',
                                                    gap: '8px',
                                                    borderRight: '1px solid rgba(255,255,255,0.1)',
                                                    paddingRight: '10px'
                                                }}>
                                                    <span style={{
                                                        fontSize: '9px',
                                                        fontWeight: 'bold',
                                                        color: categoryName.includes('Hour') ? '#60a5fa' : categoryName.includes('Day') ? '#34d399' : '#fbbf24',
                                                        background: 'rgba(255,255,255,0.05)',
                                                        padding: '4px 8px',
                                                        borderRadius: '4px',
                                                        textTransform: 'uppercase',
                                                        width: 'fit-content'
                                                    }}>
                                                        {categoryName}
                                                    </span>

                                                    <div
                                                        onClick={() => addPricingOption(categoryName)}
                                                        className="add-opt-btn"
                                                    >
                                                        <Plus
                                                            size={14}
                                                            style={{
                                                                background: 'rgba(225, 78, 202,0.1)',
                                                                borderRadius: '4px',
                                                                padding: '1px'
                                                            }}
                                                        />
                                                        <span style={{ fontWeight: 'normal' }}>Add Option</span>
                                                    </div>
                                                </div>

                                                <div style={{
                                                    display: 'flex',
                                                    flexWrap: 'nowrap',
                                                    gap: '12px',
                                                    flex: 1,
                                                    minWidth: 0,
                                                    overflowX: 'auto',
                                                    paddingTop: '10px',
                                                    paddingBottom: '5px',
                                                    scrollbarWidth: 'none'
                                                }} className="no-scrollbar">



          {filteredOptions.length > 0 ? (
    filteredOptions.map((opt, idx) => (
        <div key={opt.id} className="pkg-card" style={{
            position: 'relative',
            display: 'flex',
            alignItems: 'center',
            gap: '6px',
            padding: '6px 8px',
            background: 'rgba(15, 23, 42, 0.8)',
            border: '1px solid rgba(255, 255, 255, 0.08)',
            borderRadius: '8px',
            minWidth: '140px',
            flexShrink: 0
        }}>
            {/* KM LIMIT */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <label style={{ fontSize: '7px', color: '#64748b', marginBottom: '1px', textTransform: 'uppercase', letterSpacing: '0.3px' }}>KM</label>
                <input
                    value={opt.km_limit}
                    onChange={(e) => updateOption(opt.id, 'km_limit', e.target.value)}
                    style={{
                        margin: 0,
                        height: '22px',
                        width: '40px',
                        fontSize: '11px',
                        background: 'transparent',
                        border: 'none',
                        color: '#fff',
                        outline: 'none',
                        fontWeight: '600',
                        textAlign: 'center',
                        padding: '0'
                    }}
                />
            </div>

            <div style={{ borderLeft: '1px solid rgba(255,255,255,0.08)', height: '16px' }}></div>

            {/* PRICE */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <label style={{ fontSize: '7px', color: '#64748b', marginBottom: '1px', textTransform: 'uppercase', letterSpacing: '0.3px' }}>AED</label>
                <input
                    type="number"
                    value={opt.price}
                    onChange={(e) => updateOption(opt.id, 'price', e.target.value)}
                    style={{
                        margin: 0,
                        height: '22px',
                        width: '45px',
                        fontSize: '11px',
                        background: 'transparent',
                        border: 'none',
                        color: '#10b981',
                        fontWeight: 'bold',
                        outline: 'none',
                        textAlign: 'center',
                        padding: '0'
                    }}
                />
            </div>

            {/* Arrow buttons - Left and Right */}
            <div style={{
                display: 'flex',
                gap: '2px',
                marginLeft: '2px'
            }}>
                {idx > 0 && (
                    <button
                        type="button"
                        onClick={() => moveOptionLeft(categoryName, idx)}
                        style={{
                            background: 'transparent',
                            border: 'none',
                            color: '#475569',
                            cursor: 'pointer',
                            fontSize: '9px',
                            padding: '0px 2px',
                            borderRadius: '2px',
                            lineHeight: '1',
                            height: '12px',
                            transition: 'all 0.2s ease'
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.color = '#c084fc'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.color = '#475569'; }}
                        title="Move left"
                    >
                        ◀
                    </button>
                )}
                {idx < filteredOptions.length - 1 && (
                    <button
                        type="button"
                        onClick={() => moveOptionRight(categoryName, idx)}
                        style={{
                            background: 'transparent',
                            border: 'none',
                            color: '#475569',
                            cursor: 'pointer',
                            fontSize: '9px',
                            padding: '0px 2px',
                            borderRadius: '2px',
                            lineHeight: '1',
                            height: '12px',
                            transition: 'all 0.2s ease'
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.color = '#c084fc'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.color = '#475569'; }}
                        title="Move right"
                    >
                        ▶
                    </button>
                )}
            </div>

            {/* Delete button - Very small, subtle */}
            <button
                type="button"
                onClick={() => removeOption(opt.id)}
                style={{
                    background: 'transparent',
                    border: 'none',
                    color: '#475569',
                    cursor: 'pointer',
                    padding: '0px 2px',
                    borderRadius: '2px',
                    fontSize: '9px',
                    lineHeight: '1',
                    height: '12px',
                    transition: 'all 0.2s ease',
                    marginLeft: '2px'
                }}
                onMouseEnter={(e) => { e.currentTarget.style.color = '#ef4444'; }}
                onMouseLeave={(e) => { e.currentTarget.style.color = '#475569'; }}
                title="Delete"
            >
                ✕
            </button>
        </div>
    ))
) : (
    <div style={{ fontSize: '11px', color: '#475569', fontStyle: 'italic' }}>
        No options added
    </div>
)}
   </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>


                            {/* Maintenance Card */}
                            <div className="form-card">
                                <h4 className="form-card-title">
                                    <Clock size={16} /> Maintenance
                                </h4>

                                <div className="form-space-y">
                                    {/* Maintenance Company */}
                                    <div className="form-grid-2 mb-3">

                                        <div className="field-group">
                                            <label className="field-label">Maintenance Company</label>
                                            <div className="input-icon-wrapper">
                                                <input
                                                    className="glass-input"
                                                    value={currentCar.maintenance_company || ""}
                                                    onChange={(e) =>
                                                        setCurrentCar({
                                                            ...currentCar,
                                                            maintenance_company: e.target.value,
                                                        })
                                                    }
                                                    placeholder="Enter company name"
                                                />
                                                <Info size={16} className="input-icon" />
                                            </div>
                                        </div>

                                        {/* Start Date */}
                                        <div className="field-group">
                                            <label className="field-label">
                                                <Calendar size={12} /> Start Date (Maintenance)
                                            </label>
                                            <DateTimePicker
                                                value={currentCar.maintenance_start_date || ""}
                                                onChange={(iso) =>
                                                    setCurrentCar({
                                                        ...currentCar,
                                                        maintenance_start_date: iso,
                                                    })
                                                }
                                                placeholder="Date & Time"
                                                minDate={getTodayStr()}
                                            />
                                        </div>
                                    </div>


                                    {/* Maintenance Date Range */}
                                    <div className="form-grid-2">


                                        <div className="field-group mb-3">
                                            <label className="field-label">
                                                <Calendar size={12} /> End Date (Maintenance)
                                            </label>
                                            <DateTimePicker
                                                value={currentCar.maintenance_end_date || ""}
                                                onChange={(iso) => setCurrentCar({ ...currentCar, maintenance_end_date: iso })}
                                                placeholder="Date & Time"
                                            />
                                        </div>
                                        <div className="field-group">
                                            <label className="field-label">
                                                <Calendar size={12} />  Battery Change Date
                                            </label>
                                            <DateTimePicker
                                                value={currentCar.last_battery_change || ""}
                                                onChange={(iso) => setCurrentCar({ ...currentCar, last_battery_change: iso })}
                                                placeholder="Select Date"
                                            />
                                        </div>



                                    </div>

                                    {/* Maintenance Metrics Grid */}
                                    <div className="form-grid-2">

                                        <div className="field-group"
                                            style={{
                                                background: "rgba(48, 51, 68, 0.8)",
                                                border: "0px solid #dbe4f0",
                                                borderRadius: "12px",
                                                padding: "11px",
                                                marginTop: "10px",
                                            }}>
                                            <label className="field-label">Last Oil Change (KM)</label>
                                            <input type="number" min="0" onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }} className="glass-input" value={currentCar.last_oil_change_km || ""}
                                                onChange={handleOilChangeKM}
                                                placeholder="e.g., 35000" />

                                        </div>
                                        {/* Oil Change Interval Radio Buttons */}
                                            <div className="field-group" style={{
                                                background: "rgba(48, 51, 68, 0.8)",
                                                border: "0px solid #dbe4f0",
                                                borderRadius: "12px",
                                                padding: "11px",
                                                marginTop: "10px",
                                            }} >
                                                <label className="field-label mt-0">Oil Change Interval</label>
                                                <div className="d-flex gap-1 mt-2">
                                                    <div className="form-check d-flex align-items-center">
                                                        <input
                                                            type="radio"
                                                            name="oil_change_interval"
                                                            id="oil5000"
                                                            value="5000"
                                                            checked={currentCar.oil_change_interval === 5000}
                                                            onChange={(e) => setCurrentCar({
                                                                ...currentCar,
                                                                oil_change_interval: Number(e.target.value),
                                                                oil_change_interval_selected: true
                                                            })}
                                                            style={{ marginRight: "5px" }}
                                                            disabled={currentCar.oil_change_completed}
                                                        />
                                                        <label className="form-check-label" htmlFor="oil5000" style={{ fontSize: "12px", whiteSpace: "nowrap" }}>
                                                            5000 KM
                                                        </label>
                                                    </div>
                                                    <div className="form-check d-flex align-items-center">
                                                        <input
                                                            type="radio"
                                                            name="oil_change_interval"
                                                            id="oil10000"
                                                            value="10000"
                                                            checked={currentCar.oil_change_interval === 10000}
                                                            onChange={(e) => setCurrentCar({
                                                                ...currentCar,
                                                                oil_change_interval: Number(e.target.value),
                                                                oil_change_interval_selected: true
                                                            })}
                                                            style={{ marginRight: "5px" }}
                                                            disabled={currentCar.oil_change_completed}
                                                        />
                                                        <label className="form-check-label" htmlFor="oil10000" style={{ fontSize: "12px", whiteSpace: "nowrap" }}>
                                                            10000 KM
                                                        </label>
                                                    </div>
                                                </div>
                                                {/* ⬇️ ADD THIS MESSAGE ⬇️ */}
                                                {currentCar.oil_change_completed && (
                                                    <div style={{
                                                        marginTop: '8px',
                                                        padding: '6px 12px',
                                                        background: 'rgba(239,68,68,0.1)',
                                                        border: '1px solid rgba(239,68,68,0.3)',
                                                        borderRadius: '6px',
                                                        color: '#f87171',
                                                        fontSize: '12px',
                                                        display: 'flex',
                                                        alignItems: 'center',
                                                        gap: '6px'
                                                    }}>
                                                        ⚠️ Oil change interval complete! Update "Last Oil Change (KM)" to reset.
                                                    </div>
                                                )}
                                            </div>
                                        {/* -------------------- */}

                                    </div>
                                </div>
                            </div>
                            {/* closing */}
                            {/* Form Buttons */}
                            <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end', marginTop: '1.25rem' }}>
                                <button type="button" onClick={() => setIsEditing(false)} className="cancel-btn" style={{ flex: 1 }}>Cancel</button>
                                <button type="submit" className="submit-btn" style={{ flex: 1.5 }}><Save size={18} /> {currentCar.id ? 'Update Vehicle' : 'Register Vehicle'}</button>
                            </div>
                        </div>
                    </form>
                </div>
            )}

            {/* Car grid: only shown when NOT editing */}
            {!isEditing && (
                <div className="car-grid">
                    {cars.map(car => (
                        <div key={car.id} className="glass car-card" style={{ display: 'flex', flexDirection: 'column' }}>
                            <div style={{ position: 'relative' }}>
{car.image_url ? (
    <img src={car.image_url} alt={car.model} className="car-img" />
) : (
    <div className="car-img" style={{
        background: 'rgba(30, 41, 59, 0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#64748b',
        fontSize: '0.8rem'
    }}>
        No Image
    </div>
)}
                                <span className={`status-badge status-${car.status}`} style={{ position: 'absolute', top: '12px', right: '12px', textTransform: 'capitalize' }}>{car.status}</span>
                            </div>
                            <div className="car-info" style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '1.5rem', background: 'linear-gradient(180deg, transparent 0%, rgba(15, 23, 42, 0.8) 100%)' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
                                    <div>
                                        <h3 style={{ margin: 0, fontSize: '1.35rem', fontWeight: 800, color: '#f8fafc', letterSpacing: '-0.5px' }}>{car.brand} {car.model}</h3>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>
                                            <span style={{ color: '#94a3b8', fontSize: '0.8rem', fontWeight: 500 }}>{car.year}</span>
                                            <span style={{ width: '4px', height: '4px', borderRadius: '50%', background: '#475569' }}></span>
                                            <span style={{ color: '#94a3b8', fontSize: '0.8rem', fontWeight: 500 }}>{car.current_km || 0} km</span>
                                        </div>
                                    </div>
                                </div>

                                {car.status === 'reserved' && car.reserved_by_customer && (
                                    <div style={{
                                        background: 'linear-gradient(90deg, rgba(249,115,22,0.1), transparent)',
                                        borderLeft: '3px solid #f97316',
                                        padding: '8px 12px',
                                        marginTop: '8px',
                                        fontSize: '0.8rem',
                                        color: '#fdba74',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        borderRadius: '0 8px 8px 0'
                                    }}>
                                        <Info size={14} color="#f97316" />
                                        <span>Reserved By: <strong style={{ color: '#fff' }}>{car.reserved_by_customer}</strong></span>
                                    </div>
                                )}

                                <div style={{ margin: '16px 0', display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                    {/* Category Toggle */}
                                    <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
                                        {Array.from(new Set(car.rental_options?.map(opt => opt.category))).map((cat) => {
                                            const isActive = car.activeCategory === cat || (!car.activeCategory && car.rental_options[0]?.category === cat);
                                            return (
                                                <button
                                                    key={cat}
                                                    onClick={() => {
                                                        setCars(prev => prev.map(c => c.id === car.id ? { ...c, activeCategory: cat, activePkgIdx: 0 } : c));
                                                    }}
                                                    style={{
                                                        padding: "6px 16px",
                                                        fontSize: "11px",
                                                        borderRadius: "20px",
                                                        fontWeight: "700",
                                                        border: isActive ? "1px solid #a855f7" : "1px solid rgba(255,255,255,0.08)",
                                                        background: isActive ? "rgba(168, 85, 247, 0.15)" : "rgba(15, 23, 42, 0.4)",
                                                        color: isActive ? "#c084fc" : "#94a3b8",
                                                        cursor: "pointer",
                                                        textTransform: "uppercase",
                                                        letterSpacing: "0.5px",
                                                        transition: "all 0.2s ease",
                                                        boxShadow: isActive ? "0 0 10px rgba(168, 85, 247, 0.2)" : "none"
                                                    }}
                                                >
                                                    {cat.replace("Per ", "")}
                                                </button>
                                            );
                                        })}
                                    </div>

                                    {/* KM Limit Pills */}
                                    <div style={{ display: "flex", gap: "8px", flexWrap: "wrap", paddingTop: "4px" }}>
                                        {car.rental_options?.filter(opt => opt.category === (car.activeCategory || car.rental_options[0]?.category)).map((opt, idx) => {
                                            const isPkgActive = (car.activePkgIdx || 0) === idx;
                                            return (
                                                <button
                                                    key={idx}
                                                    onClick={() => {
                                                        setCars(prev => prev.map(c => c.id === car.id ? { ...c, activePkgIdx: idx } : c));
                                                    }}
                                                    style={{
                                                        padding: "4px 12px",
                                                        fontSize: "11px",
                                                        borderRadius: "8px",
                                                        fontWeight: "600",
                                                        cursor: "pointer",
                                                        border: isPkgActive ? "1px solid #38bdf8" : "1px solid rgba(255,255,255,0.05)",
                                                        background: isPkgActive ? "rgba(56, 189, 248, 0.1)" : "rgba(255,255,255,0.03)",
                                                        color: isPkgActive ? "#38bdf8" : "#64748b",
                                                        transition: "all 0.2s ease"
                                                    }}
                                                >
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                        <Gauge size={12} />
                                                        <span>Limit: {opt.km_limit} KM</span>
                                                    </div>
                                                </button>
                                            );
                                        })}
                                    </div>

                                    {/* Price Display */}
                                    {(() => {
                                        const activeCat = car.activeCategory || car.rental_options?.[0]?.category;
                                        const filtered = car.rental_options?.filter(o => o.category === activeCat);
                                        const selectedPkg = filtered?.[car.activePkgIdx || 0];

                                        if (!selectedPkg) return null;

                                        return (
                                            <div style={{
                                                display: "flex",
                                                justifyContent: "space-between",
                                                alignItems: "center",
                                                paddingTop: "16px",
                                                marginTop: "4px",
                                                borderTop: "1px dashed rgba(255,255,255,0.1)"
                                            }}>
                                                <div style={{ display: "flex", alignItems: "baseline", gap: "6px" }}>
                                                    <span style={{ color: "#f8fafc", fontWeight: "800", fontSize: "1.5rem", letterSpacing: "-0.5px" }}>
                                                        <span style={{ fontSize: "1rem", color: "#94a3b8", marginRight: "4px" }}>AED</span>
                                                        {selectedPkg.price}
                                                    </span>
                                                    <span style={{ fontSize: "12px", color: "#64748b", fontWeight: "500" }}>
                                                        /{activeCat.replace("Per ", "").toLowerCase()}
                                                    </span>
                                                </div>
                                                <div style={{
                                                    fontSize: '10px',
                                                    color: '#10b981',
                                                    background: 'rgba(16, 185, 129, 0.1)',
                                                    padding: '4px 10px',
                                                    borderRadius: '20px',
                                                    border: '1px solid rgba(16, 185, 129, 0.2)',
                                                    fontWeight: '700',
                                                    letterSpacing: '0.3px',
                                                    textTransform: 'uppercase'
                                                }}>
                                                    Best Value
                                                </div>
                                            </div>
                                        );
                                    })()}
                                </div>

                                {/* Action Buttons */}
                                <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr', gap: '8px', marginTop: 'auto', paddingTop: '8px' }}>
                                    <button
                                        onClick={() => navigate("/AddBooking", { state: { car } })}
                                        style={{
                                            padding: '10px',
                                            fontSize: '13px',
                                            borderRadius: '8px',
                                            fontWeight: '700',
                                            background: 'linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(22, 163, 74, 0.15))',
                                            color: '#4ade80',
                                            border: '1px solid rgba(34, 197, 94, 0.3)',
                                            cursor: 'pointer',
                                            transition: 'all 0.2s ease',
                                            display: 'flex',
                                            justifyContent: 'center',
                                            alignItems: 'center'
                                        }}
                                        onMouseEnter={e => { e.currentTarget.style.background = 'rgba(34, 197, 94, 0.25)'; e.currentTarget.style.borderColor = 'rgba(34, 197, 94, 0.5)'; }}
                                        onMouseLeave={e => { e.currentTarget.style.background = 'linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(22, 163, 74, 0.15))'; e.currentTarget.style.borderColor = 'rgba(34, 197, 94, 0.3)'; }}
                                    >
                                        Book Now
                                    </button>

                                    <button
                                        onClick={() => startEdit(car)}
                                        style={{
                                            padding: '10px',
                                            fontSize: '13px',
                                            borderRadius: '8px',
                                            fontWeight: '600',
                                            background: 'rgba(168, 85, 247, 0.1)',
                                            color: '#c084fc',
                                            border: '1px solid rgba(168, 85, 247, 0.2)',
                                            cursor: 'pointer',
                                            transition: 'all 0.2s ease',
                                            display: 'flex',
                                            justifyContent: 'center',
                                            alignItems: 'center'
                                        }}
                                        onMouseEnter={e => { e.currentTarget.style.background = 'rgba(168, 85, 247, 0.2)'; e.currentTarget.style.borderColor = 'rgba(168, 85, 247, 0.4)'; }}
                                        onMouseLeave={e => { e.currentTarget.style.background = 'rgba(168, 85, 247, 0.1)'; e.currentTarget.style.borderColor = 'rgba(168, 85, 247, 0.2)'; }}
                                    >
                                        Edit
                                    </button>

                                    <button
                                        onClick={() => handleDelete(car.id)}
                                        style={{
                                            padding: '10px',
                                            fontSize: '13px',
                                            borderRadius: '8px',
                                            fontWeight: '600',
                                            background: 'rgba(239, 68, 68, 0.05)',
                                            color: '#f87171',
                                            border: '1px solid rgba(239, 68, 68, 0.15)',
                                            cursor: 'pointer',
                                            transition: 'all 0.2s ease',
                                            display: 'flex',
                                            justifyContent: 'center',
                                            alignItems: 'center'
                                        }}
                                        onMouseEnter={e => { e.currentTarget.style.background = 'rgba(239, 68, 68, 0.15)'; e.currentTarget.style.borderColor = 'rgba(239, 68, 68, 0.3)'; }}
                                        onMouseLeave={e => { e.currentTarget.style.background = 'rgba(239, 68, 68, 0.05)'; e.currentTarget.style.borderColor = 'rgba(239, 68, 68, 0.15)'; }}
                                    >
                                        Delete
                                    </button>

                                </div>

                            </div>

                        </div>

                    ))}
                </div>

            )}
        </div>

    );
};

export default CarManagement;