<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">Cases</h2>
    </x-slot>

    <div class="py-8">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="card p-5 mb-6 flex flex-wrap items-center justify-between gap-4">
                <div>
                    <div class="text-xs uppercase tracking-wide text-gray-500">Case Workspace</div>
                    <div class="text-xl font-semibold text-gray-900">All Cases</div>
                </div>
                <div class="flex items-center gap-2">
                    @can('cases.create')
                        <a href="{{ route('cases.create') }}" class="btn-primary">New Case</a>
                    @endcan
                    @can('cases.export')
                        <a href="{{ route('cases.export', request()->query()) }}" class="btn-outline">Export CSV</a>
                    @endcan
                </div>
            </div>

            <form method="GET" class="card p-4 mb-6 grid grid-cols-1 md:grid-cols-4 gap-3">
                @if (!auth()->user()->hasRole('Client Viewer'))
                    <select id="filterClient" name="client_id" class="border-gray-300 rounded-md">
                        <option value="">All Clients</option>
                        @foreach ($clients as $client)
                            <option value="{{ $client->id }}" @selected(request('client_id') == $client->id)>{{ $client->name }}</option>
                        @endforeach
                    </select>
                @endif
                <select id="filterLabel" name="label" class="border-gray-300 rounded-md">
                    <option value="">All Labels</option>
                    @foreach ($options['label'] as $value)
                        <option value="{{ $value }}" @selected(request('label') == $value)>{{ $value }}</option>
                    @endforeach
                </select>
                <select name="source" class="border-gray-300 rounded-md">
                    <option value="">All Sources</option>
                    @foreach ($options['source'] as $value)
                        <option value="{{ $value }}" @selected(request('source') == $value)>{{ $value }}</option>
                    @endforeach
                </select>
                <select name="sentiment" class="border-gray-300 rounded-md">
                    <option value="">All Sentiment</option>
                    @foreach ($options['sentiment'] as $value)
                        <option value="{{ $value }}" @selected(request('sentiment') == $value)>{{ $value }}</option>
                    @endforeach
                </select>
                <select name="status" class="border-gray-300 rounded-md">
                    <option value="">All Status</option>
                    @foreach ($options['status'] as $value)
                        <option value="{{ $value }}" @selected(request('status') == $value)>{{ $value }}</option>
                    @endforeach
                </select>
                <input type="date" name="date_from" value="{{ request('date_from') }}" class="border-gray-300 rounded-md" />
                <input type="date" name="date_to" value="{{ request('date_to') }}" class="border-gray-300 rounded-md" />
                <div class="flex items-center gap-2">
                    <input type="checkbox" name="overdue_only" value="1" class="rounded" @checked(request('overdue_only')) />
                    <span class="text-sm text-gray-600">Overdue only</span>
                </div>
                <button class="btn-primary">Filter</button>
            </form>

            <form method="POST" action="{{ route('cases.bulk-destroy') }}" onsubmit="return confirm('Delete selected cases?');">
                @csrf
                @method('DELETE')
                <div class="mb-3 flex justify-end">
                    @can('cases.edit')
                        <button class="inline-flex items-center px-3 py-2 text-sm rounded-md bg-rose-50 text-rose-700 hover:bg-rose-100 transition">Delete Selected</button>
                    @endcan
                </div>
                <div class="card overflow-x-auto">
                <table class="min-w-full text-sm">
                    <thead class="bg-gray-50 text-gray-600">
                        <tr>
                            <th class="px-4 py-3 text-left"><input id="selectAllCases" type="checkbox" class="rounded"></th>
                            <th class="px-4 py-3 text-left">ID</th>
                            <th class="px-4 py-3 text-left">Client</th>
                            <th class="px-4 py-3 text-left">Label</th>
                            <th class="px-4 py-3 text-left">Sentiment</th>
                            <th class="px-4 py-3 text-left">Status</th>
                            <th class="px-4 py-3 text-left">Updated</th>
                            <th class="px-4 py-3"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($cases as $case)
                            @php
                                $isCritical = $case->sentiment === 'Critical';
                                $overdue = in_array($case->status, $not_closed_statuses, true)
                                    && $case->created_at <= now()->subHours($sla_threshold_hours);
                                $sentimentClass = match ($case->sentiment) {
                                    'Positive' => 'sentiment-positive',
                                    'Neutral' => 'sentiment-neutral',
                                    'Negative' => 'sentiment-negative',
                                    'Critical' => 'sentiment-critical',
                                    default => 'chip',
                                };
                            @endphp
                            <tr class="border-t hover:bg-blue-50/40 {{ $isCritical ? 'bg-rose-50' : '' }}">
                                <td class="px-4 py-3"><input type="checkbox" name="ids[]" value="{{ $case->id }}" class="case-checkbox rounded"></td>
                                <td class="px-4 py-3 font-medium">#{{ $case->id }}</td>
                                <td class="px-4 py-3">{{ $case->client->name ?? '—' }}</td>
                                <td class="px-4 py-3">{{ $case->label }}</td>
                                <td class="px-4 py-3">
                                    <span class="{{ $sentimentClass }}">
                                        {{ $case->sentiment }}
                                    </span>
                                </td>
                                <td class="px-4 py-3">
                                    <span class="badge-status">{{ $case->status }}</span>
                                    @if ($overdue)
                                        <span class="ml-1 chip" style="background: rgba(251,191,36,0.2); color: #b45309;">Overdue</span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 text-gray-500">{{ $case->updated_at?->diffForHumans() }}</td>
                                <td class="px-4 py-3 text-right">
                                    <div class="inline-flex items-center gap-2">
                                        <a href="{{ route('cases.show', $case) }}" class="inline-flex items-center px-2.5 py-1.5 text-xs rounded-md bg-sky-50 text-sky-700 hover:bg-sky-100 transition">View</a>
                                        @can('cases.edit')
                                            <a href="{{ route('cases.edit', $case) }}" class="inline-flex items-center px-2.5 py-1.5 text-xs rounded-md bg-indigo-50 text-indigo-700 hover:bg-indigo-100 transition">Edit</a>
                                            <form method="POST" action="{{ route('cases.destroy', $case) }}" class="inline" onsubmit="return confirm('Delete this case?');">
                                                @csrf
                                                @method('DELETE')
                                                <button class="inline-flex items-center px-2.5 py-1.5 text-xs rounded-md bg-rose-50 text-rose-700 hover:bg-rose-100 transition">Delete</button>
                                            </form>
                                        @endcan
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="px-4 py-8 text-center text-gray-500">No cases found.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
                </div>
            </form>

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

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                const selectAllCases = document.getElementById('selectAllCases');
                const caseCheckboxes = document.querySelectorAll('.case-checkbox');
                if (selectAllCases) {
                    selectAllCases.addEventListener('change', () => {
                        caseCheckboxes.forEach((cb) => cb.checked = selectAllCases.checked);
                    });
                }

                const labelMap = @json($labelMap ?? []);
                const clientSelect = document.getElementById('filterClient');
                const labelSelect = document.getElementById('filterLabel');
                if (!labelSelect) return;

                const rebuildLabels = (clientId) => {
                    const labels = clientId ? (labelMap[clientId] || []) : @json($options['label']);
                    const current = labelSelect.value;
                    labelSelect.innerHTML = '<option value="">All Labels</option>';
                    labels.forEach((value) => {
                        const opt = document.createElement('option');
                        opt.value = value;
                        opt.textContent = value;
                        if (value === current) opt.selected = true;
                        labelSelect.appendChild(opt);
                    });
                };

                if (clientSelect) {
                    rebuildLabels(clientSelect.value);
                    clientSelect.addEventListener('change', () => rebuildLabels(clientSelect.value));
                }
            });
        </script>
    @endpush
</x-app-layout>
