@once
@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', () => {
    const endpoint = @json(route('workflow.related-records'));
    document.querySelectorAll('.case-remote-group').forEach((group) => {
        const search = group.querySelector('.case-remote-search');
        const select = group.querySelector('.case-remote-select');
        const status = group.querySelector('.case-remote-status');
        let timer;
        let requestNumber = 0;

        const load = async (query = '', includeSelected = false) => {
            const current = select.value || select.dataset.selected || '';
            const request = ++requestNumber;
            status.textContent = 'Searching...';
            const params = new URLSearchParams({type: group.dataset.type, q: query});
            if (includeSelected && current) params.set('selected_id', current);
            try {
                const response = await fetch(`${endpoint}?${params}`, {headers: {'Accept': 'application/json'}});
                if (!response.ok) throw new Error('Search failed');
                const records = await response.json();
                if (request !== requestNumber) return;
                select.replaceChildren(new Option(select.name === 'assigned_to' ? 'Unassigned / All employees' : 'None', ''));
                records.forEach(record => select.add(new Option(record.text, record.id, false, String(record.id) === String(current))));
                select.value = current;
                status.textContent = `${records.length} result${records.length === 1 ? '' : 's'}`;
            } catch (error) {
                if (request === requestNumber) status.textContent = 'Unable to load results';
            }
        };

        search.addEventListener('input', () => {
            clearTimeout(timer);
            timer = setTimeout(() => load(search.value.trim()), 250);
        });
        load('', true);
    });
});
</script>
@endpush
@endonce
