<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Edit Case #{{ $case->id }}</h2>
            <div class="text-sm text-gray-500">Last updated {{ $case->updated_at?->diffForHumans() }}</div>
        </div>
    </x-slot>

    <div class="py-8">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            <div class="card p-6">
                <form method="POST" action="{{ route('cases.update', $case) }}">
                    @csrf
                    @method('PUT')
                    @include('cases._form', [
                        'clients' => $clients,
                        'options' => $options,
                        'selected' => $case->toArray(),
                    ])

                    <div class="mt-6 flex justify-end gap-2">
                        <a href="{{ route('cases.show', $case) }}" class="btn-outline">Cancel</a>
                        <button class="btn-primary">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                const labelMap = @json($labelMap ?? []);
                const clientSelect = document.getElementById('clientSelect');
                const labelSelect = document.getElementById('labelSelect');
                if (!clientSelect || !labelSelect) return;

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

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