App.BrowseCars = function BrowseCars() {
    const [cars, setCars] = React.useState([]);
    const [categories, setCategories] = React.useState([]);
    const [activeCategory, setActiveCategory] = React.useState(null);
    const [loading, setLoading] = React.useState(true);
    const [search, setSearch] = React.useState('');
    const [contentMode, setContentMode] = App.useContentFilter();

    React.useEffect(() => {
        Promise.all([
            App.API.get('cars'),
            App.API.get('categories'),
        ]).then(([carsData, catsData]) => {
            setCars(carsData);
            setCategories(catsData);
            setLoading(false);
        });
    }, []);

    let filtered = activeCategory
        ? cars.filter(c => c.category_id == activeCategory)
        : cars;

    if (search) {
        const q = search.toLowerCase();
        filtered = filtered.filter(c => c.name.toLowerCase().includes(q));
    }

    if (contentMode === 'included') {
        filtered = filtered.filter(c => c.is_free == 1);
    }

    const subtitleText = contentMode === 'included'
        ? filtered.length + ' free cars included with iRacing membership'
        : filtered.length + ' total cars';

    if (loading) return <App.Loading />;

    return (
        <div className="page">
            <h1>Cars</h1>
            <p className="page-subtitle">{subtitleText}</p>
            <App.ContentToggle mode={contentMode} onChange={setContentMode} />
            <App.CategoryFilter categories={categories} activeId={activeCategory} onChange={setActiveCategory} />
            <div className="search-sort-row">
                <input
                    type="text"
                    className="search-input"
                    placeholder="Search cars..."
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                />
            </div>
            <div className="card-grid">
                {filtered.map(car => (
                    <App.CarCard key={car.id} car={car} />
                ))}
            </div>
        </div>
    );
};
