@props([
    'room',
    'events' => [],
    'expectedType' => 'town_hall',
    'submitLabel' => 'Link event',
    'submitClass' => 'btn-primary btn-primary-lg w-full',
])

@if ($events === [])
    <div class="text-sm text-slate-600">
        <p>No virtual or hybrid events found in your Ladill Events account.</p>
        <a href="{{ \App\Support\EventsSourceLink::createEventUrl($room) }}" target="_blank" rel="noopener" class="mt-4 inline-flex btn-primary btn-primary-sm">Create event in Events</a>
    </div>
@else
    <form method="POST" action="{{ route('meet.events.link.store', $room) }}" class="space-y-5">
        @csrf

        <div>
            <label class="block text-sm font-medium text-slate-700">Event</label>
            <select name="event_id" required class="mt-2 w-full rounded-lg border-slate-300 text-sm">
                <option value="">Select an event…</option>
                @foreach ($events as $event)
                    <option value="{{ $event['id'] }}" @selected(old('event_id') == $event['id'])>
                        {{ $event['title'] }} ({{ ucfirst($event['format']) }})
                    </option>
                @endforeach
            </select>
        </div>

        <div>
            <label class="block text-sm font-medium text-slate-700">Virtual session slot (optional)</label>
            <p class="mt-1 text-xs text-slate-500">Pick an empty session matching this {{ $room->isConference() ? 'conference' : 'webinar' }}, or leave blank to attach to the first available {{ $expectedType === 'town_hall' ? 'conference' : 'webinar' }} slot.</p>
            <select name="virtual_session_id" class="mt-2 w-full rounded-lg border-slate-300 text-sm">
                <option value="">Auto-assign slot</option>
                @foreach ($events as $event)
                    @foreach ($event['virtual_sessions'] ?? [] as $session)
                        @php
                            $typeMatch = ($session['meet_room_type'] ?? '') === $expectedType;
                            $available = empty($session['meet_room_uuid']);
                        @endphp
                        @if ($typeMatch)
                            <option value="{{ $session['id'] }}" data-event="{{ $event['id'] }}" @selected(old('virtual_session_id') === $session['id'])>
                                [{{ $event['title'] }}] {{ $session['title'] ?: 'Untitled session' }}{{ $available ? '' : ' (linked)' }}
                            </option>
                        @endif
                    @endforeach
                @endforeach
            </select>
        </div>

        <button type="submit" @class([$submitClass])>{{ $submitLabel }}</button>
    </form>
@endif
