<div>
    <x-title>
        CPF Cases

        @can('pension-cases.create')
            <x-slot:buttons>
                <a href="{{ route('pension-cases.create') }}" class="btn btn-success waves-effect waves-light">
                    <i class="mdi mdi-plus me-2"></i> New CPF Case
                </a>
            </x-slot:buttons>
        @endcan
    </x-title>

    @php
        $activeCount = collect($filterRows)
            ->filter(fn($r) => !empty($r['field']) && !empty($r['operator']))
            ->count();

        $quickActive =
            ($openClosed !== 'all' ? 1 : 0) +
            ($claimType ? 1 : 0) +
            ($statusId ? 1 : 0) +
            ($vulnerable ? 1 : 0);

        $totalActive = $activeCount + $quickActive;
        $grouped = collect($fieldConfig)->groupBy('group', true);
    @endphp

    <div class="row">
        <div class="col-12 col-md-9">
            <div class="card shadow-sm">
                <div class="card-body">

                    {{-- Controls --}}
                    <div class="row align-items-center mb-3 g-2">
                        <div class="col">
                            <input class="form-control"
                                   wire:model.live.debounce.300ms="search"
                                   placeholder="Search case #, NI, client name, reference…">
                        </div>

                        <div class="col-auto">
                            <select class="form-select form-select-sm" wire:model.live="perPage" style="width:auto;">
                                <option value="25">25 / page</option>
                                <option value="50">50 / page</option>
                                <option value="100">100 / page</option>
                            </select>
                        </div>

                        <div class="col-auto">
                            <span class="badge bg-secondary fs-6">{{ number_format($cases->total()) }}</span>
                        </div>

                        <div class="col-auto">
                            <div class="dropdown">
                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle"
                                        type="button"
                                        data-bs-toggle="dropdown"
                                        data-bs-auto-close="outside">
                                    <i class="mdi mdi-table-column me-1"></i> Table / Export Columns
                                </button>

                                <div class="dropdown-menu p-3"
                                     style="min-width:300px; max-height:450px; overflow-y:auto;">
                                    @foreach($exportFields as $key => $column)
                                        <label class="dropdown-item">
                                        <input type="checkbox"
                                            class="form-check-input me-2"
                                            value="{{ $key }}"
                                            wire:model.live="selectedExportFields"
                                            @checked(in_array($key, $selectedExportFields) || in_array($key, $defaultExportFields))
                                            @disabled(in_array($key, $defaultExportFields))>
                                            {{ $column['label'] }} {{$key}}
                                        </label>
                                    @endforeach
                                </div>
                            </div>
                        </div>

                        <div class="col-auto">
                            <select class="form-select form-select-sm"
                                    wire:model.live="exportLimit"
                                    style="width:170px;">
                                <option value="filtered">Current Results</option>
                                <option value="all">All CPF Cases</option>
                            </select>
                        </div>

                        <div class="col-auto">
                            <button wire:click="export"
                                    wire:loading.attr="disabled"
                                    class="btn btn-sm btn-success"
                                    title="Export matching cases to CSV">
                                <span wire:loading.remove wire:target="export">
                                    <i class="mdi mdi-download me-1"></i>Export CSV
                                </span>
                                <span wire:loading wire:target="export">
                                    <span class="spinner-border spinner-border-sm me-1"></span>
                                    Exporting…
                                </span>
                            </button>
                        </div>
                    </div>

                    {{-- Active filter pills --}}
                    @if($totalActive)
                        <div class="mb-3 d-flex flex-wrap gap-1 align-items-center">
                            <span class="text-muted small me-1">Filtered by:</span>

                            @if($openClosed !== 'all')
                                <span class="badge rounded-pill bg-info-subtle text-info border border-info-subtle fw-normal px-2 py-1" style="font-size:.78rem;">
                                    {{ ucfirst($openClosed) }}
                                </span>
                            @endif

                            @if($claimType)
                                <span class="badge rounded-pill bg-info-subtle text-info border border-info-subtle fw-normal px-2 py-1" style="font-size:.78rem;">
                                    Type: <strong>{{ strtoupper($claimType) }}</strong>
                                </span>
                            @endif

                            @if($statusId && $statuses->isNotEmpty())
                                <span class="badge rounded-pill bg-info-subtle text-info border border-info-subtle fw-normal px-2 py-1" style="font-size:.78rem;">
                                    Status: <strong>{{ $statuses->firstWhere('id', $statusId)?->display_name }}</strong>
                                </span>
                            @endif

                            @if($vulnerable)
                                <span class="badge rounded-pill bg-info-subtle text-info border border-info-subtle fw-normal px-2 py-1" style="font-size:.78rem;">
                                    Vulnerable
                                </span>
                            @endif

                            @foreach($filterRows as $row)
                                @if(!empty($row['field']) && !empty($row['operator']))
                                    @php
                                        $pill = $fieldConfig[$row['field']]['label'] ?? $row['field'];
                                        $ops = \App\Filters\PensionCaseFilterConfig::operatorsForType($fieldConfig[$row['field']]['type'] ?? 'string');
                                        $opLbl = $ops[$row['operator']] ?? $row['operator'];
                                        $val = $row['value'] ?? '';
                                        $val2 = $row['value2'] ?? '';
                                    @endphp

                                    <span class="badge rounded-pill bg-primary-subtle text-primary border border-primary-subtle fw-normal px-2 py-1" style="font-size:.78rem;">
                                        {{ $pill }}
                                        <span class="opacity-75 fw-light fst-italic mx-1">{{ strtolower($opLbl) }}</span>
                                        @if($val)
                                            <strong>{{ $val }}</strong>
                                            @if($val2)
                                                &ndash; <strong>{{ $val2 }}</strong>
                                            @endif
                                        @endif
                                    </span>
                                @endif
                            @endforeach
                        </div>
                    @endif
                    <div class="alert alert-info d-flex align-items-center py-2 px-3 mb-3">
                        <i class="mdi mdi-information-outline me-2 fs-5"></i>

                        <div class="small">
                            <strong>Tip:</strong> You can <strong>drag and drop the table columns</strong> to change their order.
                            Your selected order will also be used when exporting to CSV.
                        </div>
                    </div>

                    {{-- Table --}}
                    <div class="table-responsive">
                        <table class="table table-centered table-striped table-nowrap mb-0">
                            <thead class="table-light">
                                <tr id="cpf-table-columns">
                                    @foreach($visibleColumns as $key => $column)
                                        <th
                                            data-column-key="{{ $key }}"
                                            class="cpf-sortable-column"
                                            style="cursor: grab; user-select: none;"
                                        >
                                            <span class="column-drag-handle d-inline-flex align-items-center">
                                                <i class="mdi mdi-drag-vertical me-1 text-muted"></i>
                                                {{ $column['label'] }}
                                            </span>
                                        </th>
                                    @endforeach

                                    <th class="text-end" data-fixed-column="actions"></th>
                                </tr>
                            </thead>

                            <tbody>
                                @forelse($cases as $case)
                                    <tr>
                                        @foreach($visibleColumns as $column)
                                            <td>{{ $column['value']($case) }}</td>
                                        @endforeach

                                        <td class="text-end">
                                            <a href="{{ route('pension-cases.view', $case) }}"
                                               class="text-secondary me-2"
                                               title="View">
                                                <i class="mdi mdi-eye"></i>
                                            </a>

                                            @can('edit', $case)
                                                <a href="{{ route('pension-cases.edit', $case) }}"
                                                   class="text-primary me-2"
                                                   title="Edit">
                                                    <i class="mdi mdi-pencil"></i>
                                                </a>
                                            @endcan

                                            @can('delete', $case)
                                                <button type="button"
                                                        wire:click="deleteCase({{ $case->id }})"
                                                        wire:confirm="Permanently delete this CPF case and all its interim payments? This cannot be undone."
                                                        wire:loading.attr="disabled"
                                                        wire:target="deleteCase({{ $case->id }})"
                                                        class="btn btn-link p-0 align-baseline text-danger"
                                                        title="Delete">
                                                    <i class="mdi mdi-trash-can-outline"></i>
                                                </button>
                                            @endcan
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="{{ count($visibleColumns) + 1 }}" class="text-center text-muted py-5">
                                            <i class="mdi mdi-magnify fs-2 d-block mb-2 opacity-25"></i>
                                            No pension cases found.
                                        </td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-3">
                        {{ $cases->links() }}
                    </div>
                </div>
            </div>
        </div>

        {{-- Sidebar --}}
        <div class="col-12 col-md-3">
            <div class="card shadow-sm mb-3">
                <div class="card-header d-flex align-items-center py-2 px-3">
                    <span class="fw-semibold me-auto">
                        <i class="mdi mdi-filter-outline me-1"></i>Filters
                    </span>

                    @if($totalActive)
                        <span class="badge bg-primary rounded-pill me-2">{{ $totalActive }}</span>
                    @endif

                    @if($activeCount)
                        <button wire:click="clearFilters"
                                class="btn btn-link btn-sm text-danger p-0 text-decoration-none"
                                title="Clear advanced filters">
                            Clear
                        </button>
                    @endif
                </div>

                <div class="card-body p-0">
                    {{-- Quick Filters --}}
                    <div class="p-2 border-bottom" style="background: #f0f4ff;">
                        <p class="text-uppercase text-muted fw-semibold mb-2" style="font-size:.68rem;letter-spacing:.06em;">
                            Quick Filters
                        </p>

                        <div class="mb-2">
                            <label class="form-label small mb-1">Open / Closed</label>
                            <select class="form-select form-select-sm {{ $openClosed !== 'all' ? 'border-primary' : '' }}"
                                    wire:model.live="openClosed">
                                <option value="all">All</option>
                                <option value="open">Open</option>
                                <option value="closed">Closed</option>
                            </select>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small mb-1">Claim Type</label>
                            <select class="form-select form-select-sm {{ $claimType ? 'border-primary' : '' }}"
                                    wire:model.live="claimType">
                                <option value="">All Types</option>
                                <option value="bank">Bank</option>
                                <option value="fos">FOS</option>
                                <option value="fscs">FSCS</option>
                            </select>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small mb-1">Status</label>

                            @if($claimType && $statuses->isNotEmpty())
                                <select class="form-select form-select-sm {{ $statusId ? 'border-primary' : '' }}"
                                        wire:model.live="statusId">
                                    <option value="">Any Status</option>
                                    @foreach($statuses as $s)
                                        <option value="{{ $s->id }}">{{ $s->display_name }}</option>
                                    @endforeach
                                </select>
                            @else
                                <select class="form-select form-select-sm" disabled>
                                    <option>Select a type first</option>
                                </select>
                            @endif
                        </div>

                        <div>
                            <label class="form-label small mb-1">Vulnerable</label>
                            <select class="form-select form-select-sm {{ $vulnerable ? 'border-primary' : '' }}"
                                    wire:model.live="vulnerable">
                                <option value="">Any</option>
                                <option value="1">Vulnerable only</option>
                            </select>
                        </div>
                    </div>

                    {{-- Advanced Filters --}}
                    <div class="p-2">
                        <p class="text-uppercase text-muted fw-semibold mb-2" style="font-size:.68rem;letter-spacing:.06em;">
                            Advanced Filters
                        </p>

                        @foreach($filterRows as $i => $row)
                            @php
                                $rowField = $row['field'] ?? '';
                                $rowOp = $row['operator'] ?? '';
                                $rowCfg = $rowField ? ($fieldConfig[$rowField] ?? null) : null;
                                $rowType = $rowCfg['type'] ?? '';
                                $noValue = in_array($rowOp, ['is_empty','is_not_empty','is_true','is_false']);
                                $isBetween = $rowOp === 'between';
                            @endphp

                            <div class="bg-light rounded p-2 mb-2 position-relative">
                                <button wire:click="removeFilterRow({{ $i }})"
                                        class="btn btn-link btn-sm text-danger p-0 position-absolute top-0 end-0 mt-1 me-1 lh-1"
                                        title="Remove filter"
                                        style="font-size:1rem;">
                                    <i class="mdi mdi-close"></i>
                                </button>

                                <div class="mb-1" style="padding-right:1.4rem;">
                                    <select class="form-select form-select-sm"
                                            wire:model.live="filterRows.{{ $i }}.field">
                                        <option value="">— Field —</option>

                                        @foreach($grouped as $groupName => $groupFields)
                                            <optgroup label="{{ $groupName }}">
                                                @foreach($groupFields as $key => $cfg)
                                                    <option value="{{ $key }}">{{ $cfg['label'] }}</option>
                                                @endforeach
                                            </optgroup>
                                        @endforeach
                                    </select>
                                </div>

                                @if($rowField && $rowCfg)
                                    <div class="mb-1">
                                        <select class="form-select form-select-sm"
                                                wire:model.live="filterRows.{{ $i }}.operator">
                                            <option value="">— Operator —</option>

                                            @foreach(\App\Filters\PensionCaseFilterConfig::operatorsForType($rowType) as $opKey => $opLabel)
                                                <option value="{{ $opKey }}">{{ $opLabel }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                @endif

                                @if($rowField && $rowOp && $rowCfg)
                                    @if($noValue)
                                        <p class="text-muted small mb-0 fst-italic ps-1">No value needed</p>
                                    @else
                                        @if($rowType === 'boolean')
                                            <select class="form-select form-select-sm"
                                                    wire:model.live="filterRows.{{ $i }}.value">
                                                <option value="">— Select —</option>
                                                <option value="1">Yes</option>
                                                <option value="0">No</option>
                                            </select>

                                        @elseif($rowType === 'enum')
                                            <select class="form-select form-select-sm"
                                                    wire:model.live="filterRows.{{ $i }}.value">
                                                <option value="">— Select —</option>

                                                @foreach($rowCfg['options'] as $opt)
                                                    <option value="{{ $opt }}">{{ ucfirst($opt) }}</option>
                                                @endforeach
                                            </select>

                                        @elseif($rowType === 'status')
                                            <select class="form-select form-select-sm"
                                                    wire:model.live="filterRows.{{ $i }}.value">
                                                <option value="">— Select status —</option>

                                                @foreach($allStatuses->groupBy('type') as $sType => $statusGroup)
                                                    <optgroup label="{{ strtoupper(str_replace('pension-', '', $sType)) }}">
                                                        @foreach($statusGroup as $s)
                                                            <option value="{{ $s->id }}">{{ $s->display_name }}</option>
                                                        @endforeach
                                                    </optgroup>
                                                @endforeach
                                            </select>

                                        @elseif($rowType === 'select_distinct')
                                            <select class="form-select form-select-sm"
                                                    wire:model.live="filterRows.{{ $i }}.value">
                                                <option value="">— Select —</option>

                                                @foreach(\App\Filters\PensionCaseFilterConfig::distinctValues($rowField) as $v)
                                                    <option value="{{ $v }}">{{ $v }}</option>
                                                @endforeach
                                            </select>

                                        @elseif($rowType === 'date')
                                            <input type="date"
                                                   class="form-control form-control-sm mb-1"
                                                   wire:model.live="filterRows.{{ $i }}.value">

                                            @if($isBetween)
                                                <div class="text-muted small text-center mb-1">and</div>
                                                <input type="date"
                                                       class="form-control form-control-sm"
                                                       wire:model.live="filterRows.{{ $i }}.value2">
                                            @endif

                                        @elseif($rowType === 'number')
                                            <input type="number"
                                                   step="any"
                                                   class="form-control form-control-sm mb-1"
                                                   placeholder="Value…"
                                                   wire:model.live="filterRows.{{ $i }}.value">

                                            @if($isBetween)
                                                <div class="text-muted small text-center mb-1">and</div>
                                                <input type="number"
                                                       step="any"
                                                       class="form-control form-control-sm"
                                                       placeholder="Value…"
                                                       wire:model.live="filterRows.{{ $i }}.value2">
                                            @endif

                                        @else
                                            <input type="text"
                                                   class="form-control form-control-sm"
                                                   placeholder="Value…"
                                                   wire:model.live.debounce.500ms="filterRows.{{ $i }}.value">
                                        @endif
                                    @endif
                                @endif
                            </div>
                        @endforeach

                        @if(empty($filterRows))
                            <p class="text-muted small text-center py-2 mb-1">No filters added yet.</p>
                        @endif

                        <button wire:click="addFilterRow"
                                class="btn btn-outline-secondary btn-sm w-100 mt-1">
                            <i class="mdi mdi-plus me-1"></i>Add Filter
                        </button>
                    </div>
                </div>
            </div>

            {{-- Saved Presets --}}
            <div class="card shadow-sm">
                <div class="card-header py-2 px-3">
                    <span class="fw-semibold">
                        <i class="mdi mdi-bookmark-outline me-1"></i>Saved Presets
                    </span>
                </div>

                <div class="card-body p-2">
                    @if($presets->isNotEmpty())
                        <select class="form-select form-select-sm mb-2"
                                wire:change="loadPreset($event.target.value)">
                            <option value="">Load preset…</option>

                            @foreach($presets as $p)
                                <option value="{{ $p->id }}" @selected($loadedPresetId === $p->id)>
                                    {{ $p->name }}
                                </option>
                            @endforeach
                        </select>
                    @else
                        <p class="text-muted small text-center py-1 mb-2">No saved presets.</p>
                    @endif

                    @if($loadedPresetId)
                        <button wire:click="deletePreset({{ $loadedPresetId }})"
                                wire:confirm="Delete this preset? This cannot be undone."
                                class="btn btn-outline-danger btn-sm w-100 mb-2">
                            <i class="mdi mdi-trash-can-outline me-1"></i>Delete Preset
                        </button>
                    @endif

                    @if(!$showSavePreset)
                        <button wire:click="$set('showSavePreset', true)"
                                class="btn btn-outline-primary btn-sm w-100">
                            <i class="mdi mdi-content-save-outline me-1"></i>Save Current Filters
                        </button>
                    @else
                        <input type="text"
                               class="form-control form-control-sm mb-1"
                               wire:model.live="newPresetName"
                               placeholder="Preset name…"
                               autofocus>

                        @error('newPresetName')
                            <div class="text-danger small mb-1">{{ $message }}</div>
                        @enderror

                        <div class="d-flex gap-1">
                            <button wire:click="savePreset" class="btn btn-success btn-sm flex-fill">
                                Save
                            </button>
                            <button wire:click="$set('showSavePreset', false)"
                                    class="btn btn-outline-secondary btn-sm flex-fill">
                                Cancel
                            </button>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

@push('styles')
<style>
    #cpf-table-columns .cpf-sortable-column {
        transition: background-color 0.15s ease, opacity 0.15s ease;
    }

    #cpf-table-columns .cpf-sortable-column:hover {
        background-color: rgba(0, 0, 0, 0.035);
    }

    #cpf-table-columns .cpf-column-ghost {
        opacity: 0.4;
        background-color: rgba(13, 110, 253, 0.12);
    }

    #cpf-table-columns .cpf-column-chosen {
        background-color: rgba(13, 110, 253, 0.08);
    }

    #cpf-table-columns .cpf-column-dragging {
        cursor: grabbing;
    }
</style>
@endpush

@script
<script>
    let cpfColumnSortable = null;

    const initialiseCpfColumnSorting = () => {
        const headerRow = document.getElementById('cpf-table-columns');

        if (!headerRow || typeof window.Sortable === 'undefined') {
            return;
        }

        if (cpfColumnSortable) {
            cpfColumnSortable.destroy();
            cpfColumnSortable = null;
        }

        cpfColumnSortable = new window.Sortable(headerRow, {
            animation: 150,
            handle: '.column-drag-handle',
            draggable: 'th[data-column-key]',
            filter: '.column-actions',
            preventOnFilter: false,
            ghostClass: 'opacity-50',
            chosenClass: 'bg-light',

            onEnd() {
                const orderedFields = Array.from(
                    headerRow.querySelectorAll('th[data-column-key]')
                ).map(column => column.dataset.columnKey);

                $wire.updateColumnOrder(orderedFields);
            },
        });
    };

    const scheduleCpfColumnSorting = () => {
        requestAnimationFrame(() => {
            initialiseCpfColumnSorting();
        });
    };

    // Initialise immediately when the component first loads.
    scheduleCpfColumnSorting();

    // Initialise when Livewire itself becomes available.
    document.addEventListener('livewire:init', scheduleCpfColumnSorting);

    // Reinitialise after Livewire updates the component.
    Livewire.hook('morph.updated', ({ el }) => {
        if (
            el.id === 'cpf-table-columns' ||
            el.querySelector?.('#cpf-table-columns')
        ) {
            scheduleCpfColumnSorting();
        }
    });
</script>
@endscript