{{--
    Filtros server-side da lista de atividades (abas Tabela e Linha do tempo).

    Variáveis:
      $project            → Project
      $filterParams       → query string persistida
      $viewTab            → table|timeline
      $pageParam          → ap|tp (paginação da aba; resetada ao filtrar)
      $activityFilters    → valores normalizados dos filtros atuais
      $statusOptions      → list<CronogramaActivityStatus> (selecionáveis)
      $responsibleOptions → array{users, empresas, structures, unidades}
      $filtersActive      → bool
      $filtersCount       → int
      $selectId           → sufixo único para ids dos campos (ex.: 'table')
--}}
@php
    $f = $activityFilters ?? [];
    $suffix = $selectId ?? $viewTab;
    $collapseId = 'cr-activity-filters-' . $suffix;

    // Parâmetros preservados como hidden: tudo, menos a aba, a página da aba e os próprios filtros.
    $hiddenParams = collect($filterParams ?? [])
        ->except(array_merge(['tab', $pageParam ?? 'ap'], app(\App\Http\Resources\Accounts\Cronogramas\CronogramasResource::class)->activityFilterKeys()))
        ->all();

    // Parâmetros para "Limpar": preserva ordenação/itens-por-página, descarta filtros e página.
    $clearParams = array_merge($hiddenParams, ['tab' => $viewTab]);
@endphp

<div class="mb-3">
    <div class="d-flex flex-wrap align-items-center gap-2">
        <button type="button"
                class="btn btn-outline-secondary btn-sm"
                data-bs-toggle="collapse"
                data-bs-target="#{{ $collapseId }}"
                aria-expanded="{{ $filtersActive ? 'true' : 'false' }}"
                aria-controls="{{ $collapseId }}">
            <i class="fa-solid fa-filter" aria-hidden="true"></i> {{ __('Filtros') }}
            @if(($filtersCount ?? 0) > 0)
                <span class="badge bg-primary ms-1">{{ $filtersCount }}</span>
            @endif
        </button>
        @if($filtersActive)
            <a class="btn btn-outline-danger btn-sm"
               href="{{ route('admin.cronogramas.projetos.show', array_merge(['project' => $project->id], $clearParams)) }}">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i> {{ __('Limpar filtros') }}
            </a>
        @endif
    </div>

    <div class="collapse mt-2 @if($filtersActive) show @endif" id="{{ $collapseId }}">
        <form method="get"
              action="{{ route('admin.cronogramas.projetos.show', $project) }}"
              class="card card-body border bg-light">
            <input type="hidden" name="tab" value="{{ $viewTab }}">
            @include('components.cronogramas.persist-query', ['params' => $hiddenParams])

            <div class="row g-3">
                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1" for="cr-f-q-{{ $suffix }}">{{ __('Busca (todas as páginas)') }}</label>
                    <input type="search"
                           name="f_q"
                           id="cr-f-q-{{ $suffix }}"
                           class="form-control form-control-sm"
                           maxlength="150"
                           value="{{ $f['q'] ?? '' }}"
                           placeholder="{{ __('Código, título, descrição ou observação') }}">
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1" for="cr-f-status-{{ $suffix }}">{{ __('Status') }}</label>
                    <select name="f_status" id="cr-f-status-{{ $suffix }}" class="form-select form-select-sm">
                        <option value="">{{ __('Todos') }}</option>
                        @foreach($statusOptions as $st)
                            <option value="{{ $st->value }}" @selected(($f['status'] ?? null) === $st->value)>{{ $st->label() }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1" for="cr-f-overdue-{{ $suffix }}">{{ __('Situação de prazo') }}</label>
                    <select name="f_overdue" id="cr-f-overdue-{{ $suffix }}" class="form-select form-select-sm">
                        <option value="">{{ __('Todas') }}</option>
                        <option value="yes" @selected(($f['overdue'] ?? null) === 'yes')>{{ __('Apenas atrasadas') }}</option>
                        <option value="no" @selected(($f['overdue'] ?? null) === 'no')>{{ __('Apenas no prazo') }}</option>
                    </select>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1" for="cr-f-parent-{{ $suffix }}">{{ __('Atividade pai') }}</label>
                    <select name="f_parent" id="cr-f-parent-{{ $suffix }}" class="form-select form-select-sm">
                        <option value="">{{ __('Todos') }}</option>
                        <option value="yes" @selected(($f['has_parent'] ?? null) === 'yes')>{{ __('Sim (subatividade)') }}</option>
                        <option value="no" @selected(($f['has_parent'] ?? null) === 'no')>{{ __('Não (atividade raiz)') }}</option>
                    </select>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1" for="cr-f-pred-{{ $suffix }}">{{ __('Predecessora') }}</label>
                    <select name="f_pred" id="cr-f-pred-{{ $suffix }}" class="form-select form-select-sm">
                        <option value="">{{ __('Todas') }}</option>
                        <option value="yes" @selected(($f['has_pred'] ?? null) === 'yes')>{{ __('Sim (possui predecessora)') }}</option>
                        <option value="no" @selected(($f['has_pred'] ?? null) === 'no')>{{ __('Não (sem predecessora)') }}</option>
                    </select>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1" for="cr-f-resp-{{ $suffix }}">{{ __('Responsável') }}</label>
                    <select name="f_resp" id="cr-f-resp-{{ $suffix }}" class="form-select form-select-sm">
                        <option value="">{{ __('Todos') }}</option>
                        @if(! empty($responsibleOptions['users']) && count($responsibleOptions['users']))
                            <optgroup label="{{ __('Pessoa') }}">
                                @foreach($responsibleOptions['users'] as $u)
                                    <option value="user:{{ $u->id }}" @selected(($f['resp_combined'] ?? null) === 'user:' . $u->id)>{{ trim($u->firstName . ' ' . $u->lastName) }}</option>
                                @endforeach
                            </optgroup>
                        @endif
                        @if(! empty($responsibleOptions['empresas']) && count($responsibleOptions['empresas']))
                            <optgroup label="{{ __('Empresa') }}">
                                @foreach($responsibleOptions['empresas'] as $empresa)
                                    <option value="empresa:{{ $empresa->id }}" @selected(($f['resp_combined'] ?? null) === 'empresa:' . $empresa->id)>{{ $empresa->nomeFantasia ?: $empresa->razaoSocial }}</option>
                                @endforeach
                            </optgroup>
                        @endif
                        @if(! empty($responsibleOptions['structures']) && count($responsibleOptions['structures']))
                            <optgroup label="{{ __('Órgão') }}">
                                @foreach($responsibleOptions['structures'] as $structure)
                                    <option value="structure:{{ $structure->id }}" @selected(($f['resp_combined'] ?? null) === 'structure:' . $structure->id)>{{ $structure->name }}</option>
                                @endforeach
                            </optgroup>
                        @endif
                        @if(! empty($responsibleOptions['unidades']) && count($responsibleOptions['unidades']))
                            <optgroup label="{{ __('Unidade Organizacional') }}">
                                @foreach($responsibleOptions['unidades'] as $unidade)
                                    <option value="unidade:{{ $unidade->id }}" @selected(($f['resp_combined'] ?? null) === 'unidade:' . $unidade->id)>{{ $unidade->name }}</option>
                                @endforeach
                            </optgroup>
                        @endif
                    </select>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1">{{ __('Início planejado') }}</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text">{{ __('De') }}</span>
                        <input type="date" name="f_start_from" class="form-control" value="{{ $f['start_from'] ?? '' }}" aria-label="{{ __('Início planejado (de)') }}">
                        <span class="input-group-text">{{ __('Até') }}</span>
                        <input type="date" name="f_start_to" class="form-control" value="{{ $f['start_to'] ?? '' }}" aria-label="{{ __('Início planejado (até)') }}">
                    </div>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1">{{ __('Término planejado') }}</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text">{{ __('De') }}</span>
                        <input type="date" name="f_end_from" class="form-control" value="{{ $f['end_from'] ?? '' }}" aria-label="{{ __('Término planejado (de)') }}">
                        <span class="input-group-text">{{ __('Até') }}</span>
                        <input type="date" name="f_end_to" class="form-control" value="{{ $f['end_to'] ?? '' }}" aria-label="{{ __('Término planejado (até)') }}">
                    </div>
                </div>

                <div class="col-md-6 col-lg-4">
                    <label class="form-label small mb-1">{{ __('Progresso (%)') }}</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text">{{ __('Mín') }}</span>
                        <input type="number" name="f_prog_min" class="form-control" min="0" max="100" step="1" value="{{ $f['prog_min'] ?? '' }}" aria-label="{{ __('Progresso mínimo') }}">
                        <span class="input-group-text">{{ __('Máx') }}</span>
                        <input type="number" name="f_prog_max" class="form-control" min="0" max="100" step="1" value="{{ $f['prog_max'] ?? '' }}" aria-label="{{ __('Progresso máximo') }}">
                    </div>
                </div>

                <div class="col-12 d-flex flex-wrap gap-2">
                    <button type="submit" class="btn btn-primary btn-sm">
                        <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i> {{ __('Aplicar filtros') }}
                    </button>
                    <a class="btn btn-outline-secondary btn-sm"
                       href="{{ route('admin.cronogramas.projetos.show', array_merge(['project' => $project->id], $clearParams)) }}">
                        {{ __('Limpar') }}
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>
