<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">Create Case</h2>
    </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.store') }}">
                    @csrf
                    @include('cases._form', [
                        'clients' => $clients,
                        'options' => $options,
                        'selected' => [],
                    ])

                    <div class="mt-6 flex justify-end gap-2">
                        <a href="{{ route('cases.index') }}" class="btn-outline">Cancel</a>
                        <button class="btn-primary">Save</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>
