App.BrowseTracks = function BrowseTracks() {
    const [tracks, setTracks] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [search, setSearch] = React.useState('');
    const [sortOrder, setSortOrder] = React.useState('a-z');
    const [contentMode, setContentMode] = App.useContentFilter();
    const [selectedTrack, setSelectedTrack] = React.useState(null);

    React.useEffect(() => {
        App.API.get('tracks').then(data => {
            setTracks(data);
            setLoading(false);
        });
    }, []);

    let filtered = search
        ? tracks.filter(t => t.name.toLowerCase().includes(search.toLowerCase()))
        : [...tracks];

    filtered.sort((a, b) => {
        const cmp = a.name.localeCompare(b.name);
        return sortOrder === 'z-a' ? -cmp : cmp;
    });

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

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

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

    return (
        <div className="page">
            <h1>Tracks</h1>
            <p className="page-subtitle">{subtitleText}</p>
            <App.ContentToggle mode={contentMode} onChange={setContentMode} />
            <div className="search-sort-row">
                <input
                    type="text"
                    className="search-input"
                    placeholder="Search tracks..."
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                />
                <select
                    className="sort-dropdown"
                    value={sortOrder}
                    onChange={e => setSortOrder(e.target.value)}
                >
                    <option value="a-z">Name (A-Z)</option>
                    <option value="z-a">Name (Z-A)</option>
                </select>
            </div>
            <div className="card-grid">
                {filtered.map(track => (
                    <App.TrackCard key={track.id} track={track} onClick={setSelectedTrack} />
                ))}
            </div>

            {selectedTrack && (
                <App.TrackConfigModal
                    track={selectedTrack}
                    onClose={() => setSelectedTrack(null)}
                />
            )}
        </div>
    );
};
