@extends('layouts.app')

@section('title', 'Каталог автомобилей — Точка')

@php
    $fuelLabels = ['petrol'=>'Бензин','diesel'=>'Дизель','hybrid'=>'Гибрид','electric'=>'Электро','gas'=>'Газ','other'=>'Другое'];
    $countryFlags = ['Германия'=>'🇩🇪','Япония'=>'🇯🇵','Корея'=>'🇰🇷','США'=>'🇺🇸','Китай'=>'🇨🇳','ОАЭ'=>'🇦🇪','Грузия'=>'🇬🇪','Великобритания'=>'🇬🇧','Франция'=>'🇫🇷','Италия'=>'🇮🇹'];

    $conditions = $activeFilters['conditions'] ?? [];
    $countries  = $activeFilters['countries']  ?? [];
    $fuels      = $activeFilters['fuels']      ?? [];
    $make       = $activeFilters['make']       ?? '';
    $priceTo    = $activeFilters['priceTo']    ?? null;
    $year       = $activeFilters['year']       ?? null;
    $sort       = $activeFilters['sort']       ?? '';
    $priceMax   = $filterOptions['price_max']  ?? 50000000;
    $priceMin   = $filterOptions['price_min']  ?? 0;
    $sliderMax  = $priceTo ?: $priceMax;
    $hasFilters = $conditions || $countries || $fuels || $make || $priceTo || $year;
@endphp

@section('content')

<section class="page-hdr">
    <div class="container">
        <div class="sh-label reveal-up">Все автомобили</div>
        <h1 class="reveal">КАТАЛОГ</h1>
        <nav class="breadcrumb">
            <a href="{{ route('home') }}">Главная</a>
            <span>/</span>
            <span>Каталог</span>
        </nav>
    </div>
</section>

<section class="section sec-alt" style="padding-top:32px">
    <div class="container">

        {{-- Кнопка фильтров (мобильные) --}}
        <button class="btn btn-outline mob-filter-btn" id="mobFilterBtn">
            ⚙ Фильтры@if($hasFilters) <span class="chip chip-red" style="margin-left:8px;font-size:10px;padding:2px 8px">активны</span>@endif
        </button>

        {{-- form оборачивает ВСЁ — так aside и div стают прямыми детьми catalog-layout --}}
        <form method="GET" action="{{ route('catalog') }}" id="filterForm">

            <div class="catalog-layout">

                {{-- ═══ ФИЛЬТРЫ ═══ --}}
                <aside class="filters" id="filterPanel">
                    <div class="filter-hdr">
                        Фильтры
                        @if($hasFilters)
                            <a href="{{ route('catalog') }}" class="filter-reset">Сбросить</a>
                        @endif
                    </div>

                    <div class="filter-group">
                        <label>Состояние</label>
                        <div class="f-checks">
                            <label class="f-check"><input type="checkbox" name="condition[]" value="new"  {{ in_array('new',  $conditions) ? 'checked' : '' }}> Новый</label>
                            <label class="f-check"><input type="checkbox" name="condition[]" value="used" {{ in_array('used', $conditions) ? 'checked' : '' }}> С пробегом</label>
                        </div>
                    </div>

                    @if(!empty($filterOptions['makes']))
                    <div class="filter-group">
                        <label>Марка</label>
                        <select class="f-sel" name="make">
                            <option value="">Все марки</option>
                            @foreach($filterOptions['makes'] as $m)
                                <option value="{{ $m }}" {{ $make === $m ? 'selected' : '' }}>{{ $m }}</option>
                            @endforeach
                        </select>
                    </div>
                    @endif

                    @if(!empty($filterOptions['countries']))
                    <div class="filter-group">
                        <label>Страна поставки</label>
                        <div class="f-checks">
                            @foreach($filterOptions['countries'] as $c)
                                <label class="f-check">
                                    <input type="checkbox" name="country_origin[]" value="{{ $c }}" {{ in_array($c, $countries) ? 'checked' : '' }}>
                                    {{ $countryFlags[$c] ?? '' }} {{ $c }}
                                </label>
                            @endforeach
                        </div>
                    </div>
                    @endif

                    @if($priceMax > 0)
                    <div class="filter-group">
                        <label>Цена до (₽)</label>
                        <input type="range" class="f-range" id="priceRange" name="price_to"
                               min="{{ $priceMin }}" max="{{ $priceMax }}" step="100000" value="{{ $sliderMax }}"
                               oninput="document.getElementById('priceVal').textContent=Number(this.value).toLocaleString('ru-RU')+' ₽'">
                        <div class="f-range-row">от 0 до <strong id="priceVal">{{ number_format($sliderMax, 0, '.', ' ') }} ₽</strong></div>
                    </div>
                    @endif

                    @if(!empty($filterOptions['years']))
                    <div class="filter-group">
                        <label>Год</label>
                        <select class="f-sel" name="year">
                            <option value="">Любой</option>
                            @foreach($filterOptions['years'] as $y)
                                <option value="{{ $y }}" {{ (string)$year === (string)$y ? 'selected' : '' }}>{{ $y }}</option>
                            @endforeach
                        </select>
                    </div>
                    @endif

                    <div class="filter-group">
                        <label>Топливо</label>
                        <div class="f-checks">
                            @foreach($fuelLabels as $val => $label)
                                <label class="f-check">
                                    <input type="checkbox" name="engine_type[]" value="{{ $val }}" {{ in_array($val, $fuels) ? 'checked' : '' }}>
                                    {{ $label }}
                                </label>
                            @endforeach
                        </div>
                    </div>

                    {{-- Скрытое поле сортировки --}}
                    <input type="hidden" name="sort" id="sortHidden" value="{{ $sort }}">

                    <button type="submit" class="btn btn-red" style="width:100%;justify-content:center;margin-top:8px">
                        Применить
                    </button>
                </aside>

                {{-- ═══ ОСНОВНАЯ ОБЛАСТЬ ═══ --}}
                <div>

                    {{-- Активные теги --}}
                    @if($hasFilters)
                    <div class="active-tags" style="margin-bottom:12px">
                        @foreach($conditions as $c)
                            <span class="atag">{{ $c === 'new' ? 'Новый' : 'С пробегом' }}</span>
                        @endforeach
                        @if($make)<span class="atag">{{ $make }}</span>@endif
                        @foreach($countries as $c)
                            <span class="atag">{{ $countryFlags[$c] ?? '' }} {{ $c }}</span>
                        @endforeach
                        @foreach($fuels as $f)
                            <span class="atag">{{ $fuelLabels[$f] ?? $f }}</span>
                        @endforeach
                        @if($priceTo)<span class="atag">до {{ number_format($priceTo, 0, '.', ' ') }} ₽</span>@endif
                        @if($year)<span class="atag">{{ $year }} г.</span>@endif
                        <a href="{{ route('catalog') }}" class="atag" style="text-decoration:none">✕ Сбросить</a>
                    </div>
                    @endif

                    {{-- Top-bar --}}
                    <div class="cat-top">
                        <div class="cat-count">Найдено: <strong>{{ $cars->total() }}</strong> авт.</div>
                        <div style="display:flex;gap:12px;align-items:center">
                            <div class="cat-sort">
                                <label style="font-size:13px;color:var(--muted)">Сортировка:</label>
                                <select onchange="applySort(this.value)">
                                    <option value=""           {{ $sort===''           ?'selected':'' }}>По умолчанию</option>
                                    <option value="price_asc"  {{ $sort==='price_asc'  ?'selected':'' }}>Цена ↑</option>
                                    <option value="price_desc" {{ $sort==='price_desc' ?'selected':'' }}>Цена ↓</option>
                                    <option value="year_desc"  {{ $sort==='year_desc'  ?'selected':'' }}>Год ↓</option>
                                </select>
                            </div>
                            <div class="view-btns">
                                <button type="button" class="vbtn active" id="btnGrid" onclick="setView('grid')" title="Сетка">▦</button>
                                <button type="button" class="vbtn" id="btnList" onclick="setView('list')" title="Список">☰</button>
                            </div>
                        </div>
                    </div>

                    {{-- Сетка карточек --}}
                    <div class="cars-grid" id="carsGrid">
                        @forelse($cars as $car)
                            @include('pages.partials._car_card', compact('car', 'fuelLabels', 'countryFlags'))
                        @empty
                            <div class="no-results" style="grid-column:1/-1">
                                <div class="nr-i">🔍</div>
                                <h3>Ничего не найдено</h3>
                                <p>Попробуйте изменить фильтры</p>
                            </div>
                        @endforelse
                    </div>

                    {{-- Пагинация --}}
                    @if($cars->hasPages())
                    <div class="pagination" style="margin-top:36px">
                        @if($cars->onFirstPage())
                            <span class="pag" style="opacity:.35">←</span>
                        @else
                            <a class="pag" href="{{ $cars->previousPageUrl() }}">←</a>
                        @endif
                        @foreach($cars->getUrlRange(1, $cars->lastPage()) as $pg => $url)
                            <a class="pag {{ $pg===$cars->currentPage()?'active':'' }}" href="{{ $url }}">{{ $pg }}</a>
                        @endforeach
                        @if($cars->hasMorePages())
                            <a class="pag" href="{{ $cars->nextPageUrl() }}">→</a>
                        @else
                            <span class="pag" style="opacity:.35">→</span>
                        @endif
                    </div>
                    @endif

                </div>
            </div>
        </form>

    </div>
</section>

@endsection

@push('styles')
<style>
.mob-filter-btn { display: none; }
@media(max-width:1024px) {
    .catalog-layout { grid-template-columns: 1fr !important; }
    .filters        { display: none; }
    .filters.open   { display: block; }
    .mob-filter-btn { display: flex; width: 100%; justify-content: center; margin-bottom: 16px; }
}
</style>
@endpush

@push('scripts')
<script>
function applySort(v) {
    document.getElementById('sortHidden').value = v;
    document.getElementById('filterForm').submit();
}
function setView(v) {
    document.getElementById('carsGrid').classList.toggle('list-view', v === 'list');
    document.getElementById('btnGrid').classList.toggle('active', v === 'grid');
    document.getElementById('btnList').classList.toggle('active', v === 'list');
}
document.getElementById('mobFilterBtn').addEventListener('click', function () {
    document.getElementById('filterPanel').classList.toggle('open');
});
</script>
@endpush
