@php use Illuminate\Support\Carbon; @endphp
<div x-data="scheduleBuilder()" class="flex flex-col lg:flex-row h-[calc(100vh-4rem)]">
    {{-- Sidebar: Groups & Trainers --}}
    <aside class="w-full lg:w-72 bg-white border-b lg:border-b-0 lg:border-e border-gray-200 flex flex-col shrink-0 overflow-hidden max-h-[40vh] lg:max-h-none">
        {{-- Facility Selector --}}
        <div class="p-3 sm:p-4 border-b border-gray-100">
            <label class="block text-xs font-medium text-gray-500 mb-1">{{ __('المنشأة') }}</label>
            <select wire:model.live="facility_id" class="w-full text-sm border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 py-2.5">
                <option value="">{{ __('اختر المنشأة...') }}</option>
                @foreach($facilities as $f)
                    <option value="{{ $f->id }}">{{ $f->name_ar }} ({{ $f->branch?->name_ar }})</option>
                @endforeach
            </select>
        </div>

        {{-- Tabs: Groups / Trainers --}}
        <div class="flex border-b border-gray-100">
            <button @click="sidebarTab = 'groups'" :class="sidebarTab === 'groups' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'"
                    class="flex-1 py-2.5 text-xs font-medium border-b-2 transition-colors">{{ __('المجموعات') }}</button>
            <button @click="sidebarTab = 'trainers'" :class="sidebarTab === 'trainers' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500'"
                    class="flex-1 py-2.5 text-xs font-medium border-b-2 transition-colors">{{ __('المدربين') }}</button>
        </div>

        {{-- Search --}}
        <div class="p-3">
            <input type="text" x-model="sidebarSearch" placeholder="{{ __('بحث...') }}"
                   class="w-full text-sm border-gray-300 rounded-lg px-3 py-2.5 focus:ring-blue-500 focus:border-blue-500">
        </div>

        {{-- Groups List --}}
        <div x-show="sidebarTab === 'groups'" class="flex-1 overflow-y-auto px-3 pb-3 space-y-1.5">
            @foreach($groups as $group)
            <div draggable="{{ $group['available'] ? 'true' : 'false' }}"
                 @if($group['available'])
                 @dragstart="startDrag($event, 'group', {{ json_encode($group) }})"
                 @dragend="endDrag()"
                 @endif
                 x-show="!sidebarSearch || '{{ $group['name'] }}'.includes(sidebarSearch) || '{{ $group['program'] }}'.includes(sidebarSearch)"
                 class="border rounded-lg p-2.5 transition-colors
                    {{ $group['available'] ? 'border-gray-200 cursor-grab active:cursor-grabbing hover:border-blue-300 hover:bg-blue-50/50' : 'border-red-200 bg-red-50/30 cursor-not-allowed opacity-70' }}"
                 :class="draggingItem?.id === {{ $group['id'] }} && draggingItem?.type === 'group' ? 'ring-2 ring-blue-400 bg-blue-50' : ''">
                <div class="flex items-center gap-2">
                    <div class="w-3 h-3 rounded-full shrink-0" style="background-color: {{ $group['color'] }}"></div>
                    <span class="text-sm font-medium text-gray-800 truncate">{{ $group['name'] }}</span>
                    @if(!$group['available'])
                        <span class="ms-auto shrink-0 w-4 h-4 text-red-500" title="{{ $group['conflict_reason'] }}">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"/></svg>
                        </span>
                    @endif
                </div>
                <div class="flex items-center gap-2 mt-1 text-xs text-gray-500">
                    <span>{{ $group['program'] }}</span>
                    <span class="text-gray-300">|</span>
                    <span dir="ltr">{{ $group['count'] }}/{{ $group['max'] }}</span>
                    <span class="text-gray-300">|</span>
                    @php
                        $sessionsTarget = $group['sessions_per_week'];
                        $sessionsCurrent = $group['scheduled_sessions'];
                        $sessionsColor = $sessionsCurrent >= $sessionsTarget ? 'text-amber-600 bg-amber-50' : 'text-blue-600 bg-blue-50';
                    @endphp
                    <span class="px-1.5 py-0.5 rounded text-[10px] font-medium {{ $sessionsColor }}" dir="ltr" title="{{ __('حصص مجدولة / مطلوبة أسبوعياً') }}">
                        {{ $sessionsCurrent }}/{{ $sessionsTarget }} {{ __('حصص') }}
                    </span>
                </div>
                @if($group['trainer'])
                <div class="mt-1 text-xs text-gray-400 truncate">
                    <svg class="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                    {{ $group['trainer'] }}
                </div>
                @endif
                @if(!$group['available'] && $group['conflict_reason'])
                <p class="mt-1 text-[10px] text-red-500 truncate">{{ $group['conflict_reason'] }}</p>
                @endif
            </div>
            @endforeach

            @if(empty($groups))
            <p class="text-center text-xs text-gray-400 py-4">{{ __('لا توجد مجموعات نشطة') }}</p>
            @endif
        </div>

        {{-- Trainers List --}}
        <div x-show="sidebarTab === 'trainers'" class="flex-1 overflow-y-auto px-3 pb-3 space-y-1.5">
            @foreach($trainers as $trainer)
            <div draggable="{{ $trainer['available'] ? 'true' : 'false' }}"
                 @if($trainer['available'])
                 @dragstart="startDrag($event, 'trainer', {{ json_encode($trainer) }})"
                 @dragend="endDrag()"
                 @endif
                 x-show="!sidebarSearch || '{{ $trainer['name'] }}'.includes(sidebarSearch)"
                 class="border rounded-lg p-2.5 transition-colors
                    {{ $trainer['available'] ? 'border-gray-200 cursor-grab active:cursor-grabbing hover:border-purple-300 hover:bg-purple-50/50' : 'border-orange-200 bg-orange-50/30 cursor-not-allowed opacity-70' }}">
                <div class="flex items-center gap-2">
                    <div class="w-6 h-6 rounded-full flex items-center justify-center shrink-0 {{ $trainer['available'] ? 'bg-purple-100 text-purple-600' : 'bg-orange-100 text-orange-600' }}">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                    </div>
                    <span class="text-sm font-medium text-gray-800">{{ $trainer['name'] }}</span>
                    @if(!$trainer['available'])
                        <span class="ms-auto text-[10px] text-orange-600 font-medium">{{ __('مشغول') }}</span>
                    @else
                        <span class="ms-auto w-2 h-2 rounded-full bg-green-500"></span>
                    @endif
                </div>
                @if($trainer['workload'])
                @php
                    $wl = $trainer['workload'];
                    $barColor = match($wl['load_level']) {
                        'high' => 'bg-red-500',
                        'medium' => 'bg-amber-500',
                        default => 'bg-green-500',
                    };
                @endphp
                <div class="mt-1.5 ms-8">
                    <div class="flex items-center justify-between text-[10px] text-gray-500 mb-0.5">
                        <span dir="ltr">{{ $wl['weekly_hours'] }}/{{ $wl['max_weekly_hours'] }} {{ __('س') }}</span>
                        <span>{{ $wl['groups_count'] }} {{ __('مجموعات') }}</span>
                    </div>
                    <div class="h-1.5 bg-gray-200 rounded-full overflow-hidden">
                        <div class="h-full rounded-full {{ $barColor }}" style="width: {{ $wl['load_percent'] }}%"></div>
                    </div>
                </div>
                @endif
                @if(!$trainer['available'] && $trainer['conflict_reason'])
                <p class="mt-1 text-[10px] text-orange-600 truncate ms-8">{{ $trainer['conflict_reason'] }}</p>
                @endif
            </div>
            @endforeach
        </div>
    </aside>

    {{-- Main Content --}}
    <main class="flex-1 flex flex-col overflow-hidden bg-gray-50">
        {{-- Top bar: Date Navigation --}}
        <div class="bg-white border-b border-gray-200 px-3 sm:px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 shrink-0">
            <div class="flex items-center gap-2">
                <button wire:click="selectDay('{{ Carbon::parse($selectedDay)->subDay()->toDateString() }}')"
                        class="p-1.5 rounded-lg hover:bg-gray-100 text-gray-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                </button>
                <div class="flex items-center gap-2 sm:gap-3 flex-wrap">
                    <input type="date" wire:model.live="selectedDay" class="border-gray-300 rounded-lg text-sm focus:ring-blue-500 focus:border-blue-500 py-2.5" dir="ltr">
                    <span class="text-xs sm:text-sm font-medium text-gray-700 hidden sm:inline">
                        {{ Carbon::parse($selectedDay)->translatedFormat('l j F Y') }}
                    </span>
                </div>
                <button wire:click="selectDay('{{ Carbon::parse($selectedDay)->addDay()->toDateString() }}')"
                        class="p-1.5 rounded-lg hover:bg-gray-100 text-gray-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
                </button>
            </div>

            {{-- Week quick-nav --}}
            <div class="flex items-center gap-1 overflow-x-auto">
                @for($d = 0; $d < 7; $d++)
                    @php $date = Carbon::parse($selectedDay)->startOfWeek()->addDays($d); @endphp
                    <button wire:click="selectDay('{{ $date->toDateString() }}')"
                            class="w-9 h-9 rounded-lg text-xs font-medium shrink-0 {{ $date->toDateString() === $selectedDay ? 'bg-blue-600 text-white' : 'hover:bg-gray-100 text-gray-600' }}">
                        {{ $date->translatedFormat('D') }}
                    </button>
                @endfor
            </div>

            <button wire:click="selectDay('{{ now()->toDateString() }}')" class="px-3 py-2.5 text-xs font-medium text-blue-600 hover:bg-blue-50 rounded-lg shrink-0">
                {{ __('اليوم') }}
            </button>
        </div>

        {{-- Alerts --}}
        <div class="shrink-0">
            @if(session('success'))
            <div class="mx-3 sm:mx-4 mt-3 p-3 bg-green-50 border border-green-200 text-green-700 rounded-lg text-sm flex items-center justify-between">
                <span>{{ session('success') }}</span>
            </div>
            @endif

            @if(!empty($conflicts))
            <div class="mx-3 sm:mx-4 mt-3 p-3 bg-red-50 border border-red-200 rounded-lg">
                <div class="flex items-center justify-between mb-1">
                    <span class="text-sm font-bold text-red-700">{{ __('تعارض — لا يمكن التعيين') }}</span>
                    <button wire:click="dismissConflicts" class="text-red-400 hover:text-red-600 text-xs">✕</button>
                </div>
                @foreach($conflicts as $c)
                <p class="text-xs text-red-600 mt-1">
                    <span class="font-medium">{{ $c['title'] ?? $c['message'] ?? __('تعارض') }}</span>
                    @if(isset($c['time'])) <span class="text-red-400" dir="ltr">({{ $c['time'] }})</span> @endif
                    @if(isset($c['message'])) — {{ $c['message'] }} @endif
                </p>
                @endforeach
            </div>
            @endif

            @if(!empty($warnings))
            <div class="mx-3 sm:mx-4 mt-3 p-3 bg-amber-50 border border-amber-200 rounded-lg">
                <div class="flex items-center justify-between mb-1">
                    <span class="text-sm font-bold text-amber-700">{{ __('تحذيرات (غير مانعة)') }}</span>
                    <button wire:click="dismissWarnings" class="text-amber-400 hover:text-amber-600 text-xs">✕</button>
                </div>
                @foreach($warnings as $w)
                <p class="text-xs text-amber-600 mt-1">
                    @if(isset($w['implied_trainer']))
                        <svg class="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                    @endif
                    {{ $w['message'] ?? '' }}
                </p>
                @endforeach
            </div>
            @endif

            @error('time')
            <div class="mx-3 sm:mx-4 mt-3 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">{{ $message }}</div>
            @enderror
            @error('save')
            <div class="mx-3 sm:mx-4 mt-3 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">{{ $message }}</div>
            @enderror
            @error('assignment')
            <div class="mx-3 sm:mx-4 mt-3 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">{{ $message }}</div>
            @enderror
        </div>

        {{-- Content Area --}}
        @if(!$facility)
            <div class="flex-1 flex items-center justify-center p-4">
                <div class="text-center">
                    <svg class="w-12 h-12 sm:w-16 sm:h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
                    <p class="text-gray-500 font-medium text-sm">{{ __('اختر منشأة من القائمة الجانبية') }}</p>
                    <p class="text-gray-400 text-xs sm:text-sm mt-1">{{ __('لبدء جدولة المجموعات والمدربين') }}</p>
                </div>
            </div>
        @elseif(!$selectedSlotStart)
            {{-- Time Slots Grid + Custom Time Picker --}}
            <div class="flex-1 overflow-y-auto p-3 sm:p-4">
                {{-- Custom time picker --}}
                <div class="mb-4 bg-white border border-gray-200 rounded-xl p-3 sm:p-4">
                    <div class="flex flex-col sm:flex-row sm:items-center gap-3 flex-wrap">
                        <span class="text-sm font-medium text-gray-700">{{ __('وقت مخصص:') }}</span>
                        <div class="flex items-center gap-2">
                            <input type="time" wire:model="customStartTime" class="border-gray-300 rounded-lg text-sm px-3 py-2.5 focus:ring-blue-500 focus:border-blue-500 w-28" dir="ltr" step="300">
                            <span class="text-gray-400">—</span>
                            <input type="time" wire:model="customEndTime" class="border-gray-300 rounded-lg text-sm px-3 py-2.5 focus:ring-blue-500 focus:border-blue-500 w-28" dir="ltr" step="300">
                        </div>
                        <button wire:click="openCustomTime" class="px-4 py-2.5 text-xs font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
                                wire:loading.attr="disabled" wire:target="openCustomTime">
                            {{ __('فتح') }}
                        </button>
                        <span class="text-xs text-gray-400">{{ __('أو اختر من الأوقات أدناه') }}</span>
                    </div>
                </div>

                {{-- Hourly slots --}}
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 gap-3">
                    @foreach($timeSlots as $slot)
                        @php
                            $slotReservations = collect($existingReservations)->filter(fn($r) => $r['start'] < $slot['end'] && $r['end'] > $slot['start']);
                            $isBusy = $slotReservations->isNotEmpty();
                        @endphp
                        <button wire:click="openSlot('{{ $slot['start'] }}', '{{ $slot['end'] }}')"
                                class="relative border rounded-xl p-3 sm:p-4 text-start transition-all hover:shadow-md {{ $isBusy ? 'border-blue-200 bg-blue-50/50 hover:border-blue-400' : 'border-gray-200 bg-white hover:border-blue-300' }}">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm sm:text-lg font-bold text-gray-800" dir="ltr">{{ $slot['label'] }}</span>
                                @if($isBusy)
                                    <span class="w-2.5 h-2.5 bg-blue-500 rounded-full animate-pulse"></span>
                                @endif
                            </div>
                            @if($isBusy)
                                <div class="space-y-1">
                                    @foreach($slotReservations->take(3) as $sr)
                                        <p class="text-xs text-blue-700 truncate">{{ $sr['title'] }}</p>
                                    @endforeach
                                    @if($slotReservations->count() > 3)
                                        <p class="text-xs text-blue-400">+{{ $slotReservations->count() - 3 }} {{ __('أخرى') }}</p>
                                    @endif
                                </div>
                            @else
                                <p class="text-xs text-gray-400">{{ __('متاح') }}</p>
                            @endif
                        </button>
                    @endforeach
                </div>

                @if(empty($timeSlots))
                    <div class="text-center py-12">
                        <p class="text-gray-500 text-sm">{{ __('لم يتم تحديد ساعات العمل لهذه المنشأة') }}</p>
                        <a href="{{ route('facilities.list') }}" wire:navigate class="text-sm text-blue-600 hover:text-blue-700 mt-2 inline-block">{{ __('تعديل المنشأة') }}</a>
                    </div>
                @endif
            </div>
        @else
            {{-- Grid View: Segments + Assignments --}}
            <div class="flex-1 flex flex-col overflow-hidden">
                {{-- Slot Header --}}
                <div class="bg-white border-b border-gray-200 px-3 sm:px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 shrink-0">
                    <div class="flex items-center gap-3">
                        <button wire:click="closeSlot" class="p-1.5 rounded-lg hover:bg-gray-100 text-gray-600">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                        <div class="min-w-0">
                            <span class="text-sm font-bold text-gray-800" dir="ltr">{{ $selectedSlotStart }} — {{ $selectedSlotEnd }}</span>
                            <span class="text-xs text-gray-500 ms-2 hidden sm:inline">{{ $facility->name_ar }}</span>
                            @if($useCustomTime)
                                <span class="text-[10px] bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded ms-2">{{ __('وقت مخصص') }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="flex items-center gap-2 flex-wrap">
                        @php $newCount = collect($assignments)->filter(fn($a) => ($a['type'] ?? '') !== 'existing')->count(); @endphp
                        @if($newCount > 0)
                            <span class="text-xs text-gray-500">{{ $newCount }} {{ __('جديد') }}</span>
                        @endif
                        <button @click="$wire.set('showRecurring', true)" class="px-3 py-2.5 text-xs font-medium text-purple-600 border border-purple-200 rounded-lg hover:bg-purple-50"
                                @if($newCount === 0) disabled title="{{ __('أضف مجموعات أولاً') }}" @endif>
                            <svg class="w-4 h-4 inline me-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                            <span class="hidden sm:inline">{{ __('تكرار أسبوعي') }}</span>
                        </button>
                        <button wire:click="saveAssignments" class="px-4 py-2.5 text-xs font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50"
                                wire:loading.attr="disabled" wire:target="saveAssignments"
                                @if($newCount === 0) disabled @endif>
                            <span wire:loading.remove wire:target="saveAssignments">{{ __('حفظ') }}</span>
                            <span wire:loading wire:target="saveAssignments">{{ __('جارٍ الحفظ...') }}</span>
                        </button>
                    </div>
                </div>

                {{-- Grid Area --}}
                <div class="flex-1 overflow-auto p-3 sm:p-4">
                    @if(!empty($gridSegments))
                        @php
                            $minRow = collect($gridSegments)->min('row') ?? 0;
                            $maxRow = collect($gridSegments)->max('row') ?? 0;
                            $minCol = collect($gridSegments)->min('col') ?? 0;
                            $maxCol = collect($gridSegments)->max('col') ?? 0;
                            $isGrid = $maxRow > 0 || $maxCol > 0;
                            $cols = $isGrid ? ($maxCol - $minCol + 1) : count($gridSegments);
                            $rows = $isGrid ? ($maxRow - $minRow + 1) : 1;
                            $surfaceType = $facility->type->value ?? 'other';
                        @endphp

                        {{-- Spreadsheet-style grid with row/column selectors --}}
                        <div class="grid h-full" style="grid-template-columns: 36px repeat({{ $cols }}, 1fr); grid-template-rows: 36px repeat({{ $rows }}, 1fr);">

                            {{-- Corner: Select All --}}
                            <button @click="selectAll()" type="button"
                                class="flex items-center justify-center rounded-ss-lg bg-gray-100 hover:bg-blue-100 border-e border-b border-gray-200 transition-colors group"
                                title="{{ __('تحديد الكل') }}">
                                <svg class="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/></svg>
                            </button>

                            {{-- Column headers --}}
                            @for($c = $minCol; $c <= $maxCol; $c++)
                                <button @click="selectColByIndex({{ $c }})" type="button"
                                    class="flex items-center justify-center bg-gray-50 hover:bg-blue-50 border-e border-b border-gray-200 text-[11px] font-semibold text-gray-500 hover:text-blue-700 transition-colors {{ $c === $maxCol ? 'rounded-se-lg' : '' }}"
                                    title="{{ __('تحديد العمود') }} {{ $c }}">
                                    C{{ $c }}
                                </button>
                            @endfor

                            {{-- Rows with row headers --}}
                            @for($r = $minRow; $r <= $maxRow; $r++)
                                {{-- Row header --}}
                                <button @click="selectRowByIndex({{ $r }})" type="button"
                                    class="flex items-center justify-center bg-gray-50 hover:bg-blue-50 border-e border-b border-gray-200 text-[11px] font-semibold text-gray-500 hover:text-blue-700 transition-colors {{ $r === $maxRow ? 'rounded-es-lg' : '' }}"
                                    title="{{ __('تحديد الصف') }} {{ $r }}">
                                    R{{ $r }}
                                </button>

                                {{-- Row cells --}}
                                @for($c = $minCol; $c <= $maxCol; $c++)
                                    @php
                                        $seg = collect($gridSegments)->first(fn($s) => ($s['row'] ?? 0) === $r && ($s['col'] ?? 0) === $c);
                                    @endphp
                                    @if($seg)
                                        @php
                                            $segAssignment = collect($assignments)->first(fn($a) => in_array($seg['id'], $a['segment_ids'] ?? []));
                                            $isOccupied = $segAssignment !== null;
                                            $isExisting = $isOccupied && ($segAssignment['type'] ?? '') === 'existing';
                                            $isNewGroup = $isOccupied && ($segAssignment['type'] ?? '') === 'group';
                                            $isNewTrainer = $isOccupied && ($segAssignment['type'] ?? '') === 'trainer';
                                            $isLastCol = $c === $maxCol;
                                            $isLastRow = $r === $maxRow;
                                        @endphp
                                        <div
                                            @dragover.prevent="highlightSegment({{ $seg['id'] }})"
                                            @dragleave="unhighlightSegment({{ $seg['id'] }})"
                                            @drop.prevent="dropOnSegment({{ $seg['id'] }})"
                                            @click="toggleSegmentSelection({{ $seg['id'] }})"
                                            :class="{
                                                'facility-cell--selected': selectedSegments.includes({{ $seg['id'] }}),
                                                'facility-cell--drop-target': highlightedSegment === {{ $seg['id'] }},
                                            }"
                                            class="relative flex flex-col p-3 transition-all duration-100 cursor-pointer
                                                {{ !$isLastCol ? 'border-e' : '' }}
                                                {{ !$isLastRow ? 'border-b' : '' }}
                                                border-gray-200
                                                {{ !$seg['available'] ? 'facility-cell--unavailable cursor-not-allowed opacity-50' : '' }}
                                                {{ $isExisting ? 'bg-blue-500/10' : '' }}
                                                {{ $isNewGroup ? 'bg-emerald-500/10' : '' }}
                                                {{ $isNewTrainer ? 'bg-purple-500/10' : '' }}
                                                {{ !$isOccupied && $seg['available'] ? 'hover:bg-gray-100/80' : '' }}
                                                {{ $isLastCol && $isLastRow ? 'rounded-ee-lg' : '' }}"
                                        >
                                            {{-- Cell code label --}}
                                            <span class="text-[10px] font-mono text-gray-400 absolute top-1.5 end-2">{{ $seg['code'] }}</span>

                                            {{-- Existing reservation --}}
                                            @if($isExisting)
                                                <div class="flex-1 flex flex-col justify-center items-center text-center">
                                                    <p class="text-sm font-semibold text-blue-900 truncate max-w-full">{{ $segAssignment['title'] ?? '' }}</p>
                                                    @if($segAssignment['trainer_name'] ?? null)
                                                    <p class="text-[10px] text-blue-700 mt-0.5 truncate max-w-full">
                                                        <svg class="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                                                        {{ $segAssignment['trainer_name'] }}
                                                    </p>
                                                    @endif
                                                    @if($segAssignment['is_recurring'] ?? false)
                                                        <span class="inline-flex items-center gap-1 mt-1 text-[10px] text-purple-700">
                                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                                                            {{ __('متكرر') }}
                                                        </span>
                                                    @endif
                                                </div>
                                                <div class="flex gap-1 justify-center mt-1">
                                                    <button wire:click="cancelReservation({{ $segAssignment['reservation_id'] }})"
                                                            wire:confirm="{{ __('إلغاء هذا الحجز؟') }}"
                                                            class="text-[10px] text-red-600 hover:text-red-800 hover:underline">{{ __('إلغاء') }}</button>
                                                    @if($segAssignment['is_recurring'] ?? false)
                                                    <button wire:click="cancelSeries({{ $segAssignment['reservation_id'] }})"
                                                            wire:confirm="{{ __('إلغاء كل حجوزات هذه السلسلة المستقبلية؟') }}"
                                                            class="text-[10px] text-red-500 hover:text-red-700 hover:underline">{{ __('السلسلة') }}</button>
                                                    @endif
                                                </div>

                                            {{-- New group --}}
                                            @elseif($isNewGroup)
                                                <div class="flex-1 flex flex-col justify-center items-center text-center">
                                                    <p class="text-sm font-semibold text-emerald-900 truncate max-w-full">{{ $segAssignment['group_name'] ?? '' }}</p>
                                                    @if($segAssignment['implied_trainer'] ?? null)
                                                    <p class="text-[10px] text-emerald-700 mt-0.5 truncate max-w-full">{{ $segAssignment['implied_trainer'] }}</p>
                                                    @endif
                                                    <span class="text-[9px] text-emerald-500 mt-1">{{ __('جديد') }}</span>
                                                </div>
                                                @php $assignIdx = collect($assignments)->search(fn($a) => ($a['type'] ?? '') === 'group' && ($a['group_id'] ?? null) === ($segAssignment['group_id'] ?? -1)); @endphp
                                                @if($assignIdx !== false)
                                                <button wire:click="removeAssignment({{ $assignIdx }})" class="text-[10px] text-red-500 hover:text-red-700 hover:underline mt-1 text-center">{{ __('إزالة') }}</button>
                                                @endif

                                            {{-- New trainer --}}
                                            @elseif($isNewTrainer)
                                                <div class="flex-1 flex flex-col justify-center items-center text-center">
                                                    <p class="text-sm font-semibold text-purple-900 truncate max-w-full">{{ $segAssignment['trainer_name'] ?? '' }}</p>
                                                    <span class="text-[9px] text-purple-500 mt-1">{{ __('مدرب') }}</span>
                                                </div>
                                                @php $assignIdx = collect($assignments)->search(fn($a) => ($a['type'] ?? '') === 'trainer' && ($a['trainer_id'] ?? null) === ($segAssignment['trainer_id'] ?? -1)); @endphp
                                                @if($assignIdx !== false)
                                                <button wire:click="removeAssignment({{ $assignIdx }})" class="text-[10px] text-red-500 hover:text-red-700 hover:underline mt-1 text-center">{{ __('إزالة') }}</button>
                                                @endif

                                            {{-- Unavailable --}}
                                            @elseif(!$seg['available'])
                                                <div class="flex-1 flex items-center justify-center">
                                                    <span class="text-xs text-gray-400">{{ __('غير متاح') }}</span>
                                                </div>

                                            {{-- Empty / available --}}
                                            @else
                                                <div class="flex-1 flex items-center justify-center">
                                                    <span class="text-xs text-gray-400" x-show="!selectedSegments.includes({{ $seg['id'] }})">{{ __('اسحب هنا') }}</span>
                                                    <span class="text-xs text-blue-600 font-medium" x-show="selectedSegments.includes({{ $seg['id'] }})">✓ {{ __('محدد') }}</span>
                                                </div>
                                            @endif
                                        </div>
                                    @else
                                        {{-- Empty grid cell (no segment) --}}
                                        <div class="bg-gray-50/50 {{ $c < $maxCol ? 'border-e' : '' }} {{ $r < $maxRow ? 'border-b' : '' }} border-gray-200"></div>
                                    @endif
                                @endfor
                            @endfor
                        </div>

                        {{-- Legend + selection info --}}
                        <div class="mt-3 flex flex-wrap items-center justify-between gap-3">
                            <div class="flex flex-wrap items-center gap-3 text-[11px] text-gray-500">
                                <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-sm bg-white border border-gray-200"></span> {{ __('متاح') }}</span>
                                <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-sm bg-blue-500/15 border border-blue-300/50"></span> {{ __('محجوز') }}</span>
                                <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-sm bg-emerald-500/15 border border-emerald-300/50"></span> {{ __('جديد') }}</span>
                                <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-sm bg-purple-500/15 border border-purple-300/50"></span> {{ __('مدرب') }}</span>
                                <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-sm facility-cell--selected"></span> {{ __('محدد') }}</span>
                            </div>
                            <div x-show="selectedSegments.length > 0" x-transition class="flex items-center gap-2">
                                <span class="text-xs font-medium text-blue-700">
                                    <span x-text="selectedSegments.length"></span> {{ __('محدد') }}
                                </span>
                                <button @click="selectedSegments = []" type="button" class="text-[11px] text-gray-500 hover:text-red-600 underline">{{ __('مسح') }}</button>
                            </div>
                        </div>

                    @else
                        <div class="text-center py-12">
                            <svg class="w-12 h-12 sm:w-16 sm:h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z"/></svg>
                            <p class="text-gray-500 font-medium text-sm">{{ __('لا يوجد تخطيط لهذه المنشأة') }}</p>
                            <p class="text-gray-400 text-xs sm:text-sm mt-1">{{ __('أنشئ تخطيطاً أولاً من صفحة إدارة المنشآت') }}</p>
                            @if($facility)
                            <a href="{{ route('facilities.layouts', $facility) }}" wire:navigate class="inline-block mt-3 text-sm text-blue-600 hover:text-blue-700 font-medium">
                                {{ __('إنشاء تخطيط') }}
                            </a>
                            @endif
                        </div>
                    @endif
                </div>
            </div>
        @endif
    </main>

    {{-- Recurring Booking Modal --}}
    @if($showRecurring)
    <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" @click.self="$wire.set('showRecurring', false)">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-4 sm:p-6 max-h-[90vh] overflow-y-auto">
            <h3 class="text-base sm:text-lg font-bold text-gray-800 mb-4">{{ __('تكرار الحجز أسبوعياً') }}</h3>

            <div class="space-y-4">
                {{-- Duration --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">{{ __('عدد الأسابيع') }}</label>
                    <div class="flex items-center gap-3">
                        <input type="range" wire:model.live="recurringWeeks" min="1" max="52" class="flex-1">
                        <span class="text-sm font-bold text-blue-600 w-12 text-center" dir="ltr">{{ $recurringWeeks }}</span>
                    </div>
                    <p class="text-xs text-gray-400 mt-1">
                        {{ __('من') }} {{ Carbon::parse($selectedDay)->translatedFormat('j M') }}
                        {{ __('إلى') }} {{ Carbon::parse($selectedDay)->addWeeks($recurringWeeks)->translatedFormat('j M Y') }}
                    </p>
                </div>

                {{-- Days of week --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">{{ __('أيام التكرار') }}</label>
                    <div class="flex flex-wrap gap-2">
                        @php $dayNames = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت']; @endphp
                        @for($d = 0; $d < 7; $d++)
                        <label class="inline-flex items-center gap-1.5 px-3 py-2.5 border rounded-lg cursor-pointer text-xs
                            {{ $d === $dayOfWeek ? 'border-blue-300 bg-blue-50 text-blue-700' : 'border-gray-200 hover:border-blue-200' }}">
                            <input type="checkbox" wire:model="recurringDays" value="{{ $d }}" class="w-3.5 h-3.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                            {{ $dayNames[$d] }}
                        </label>
                        @endfor
                    </div>
                    <p class="text-xs text-gray-400 mt-1">{{ __('اترك فارغاً للتكرار في نفس اليوم فقط') }}</p>
                </div>

                {{-- Conflict handling --}}
                <div class="flex items-center gap-2">
                    <input type="checkbox" wire:model="skipConflicts" id="skipConflicts" class="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                    <label for="skipConflicts" class="text-sm text-gray-700">{{ __('تخطي التواريخ المتعارضة تلقائياً') }}</label>
                </div>

                {{-- Summary --}}
                <div class="bg-gray-50 rounded-lg p-3 text-sm">
                    @php $newCount = collect($assignments)->filter(fn($a) => ($a['type'] ?? '') !== 'existing')->count(); @endphp
                    <p class="text-gray-600">
                        {{ __('سيتم حجز') }}
                        <span class="font-bold">{{ $newCount }}</span> {{ __('تعيين') }}
                        {{ __('لمدة') }}
                        <span class="font-bold">{{ $recurringWeeks }}</span> {{ __('أسبوع') }}
                        = {{ __('حتى') }}
                        <span class="font-bold">{{ $newCount * $recurringWeeks }}</span> {{ __('حجز') }}
                    </p>
                    <p class="text-xs text-gray-400 mt-1">{{ __('سيتم فحص التعارضات للمدربين والمجموعات والمساحات') }}</p>
                </div>
            </div>

            <div class="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3 mt-6">
                <button @click="$wire.set('showRecurring', false)" class="w-full sm:w-auto px-4 py-2.5 text-sm text-gray-600 hover:text-gray-800 rounded-lg hover:bg-gray-100">{{ __('إلغاء') }}</button>
                <button wire:click="saveRecurring" class="w-full sm:w-auto px-6 py-2.5 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700"
                        wire:loading.attr="disabled" wire:target="saveRecurring">
                    <span wire:loading.remove wire:target="saveRecurring">{{ __('حجز متكرر') }}</span>
                    <span wire:loading wire:target="saveRecurring">{{ __('جارٍ الحجز...') }}</span>
                </button>
            </div>
        </div>
    </div>
    @endif
</div>

@script
<script>
Alpine.data('scheduleBuilder', () => ({
    sidebarTab: 'groups',
    sidebarSearch: '',
    draggingItem: null,
    selectedSegments: [],
    highlightedSegment: null,

    startDrag(event, type, item) {
        if (!item.available && item.available !== undefined) {
            event.preventDefault();
            return;
        }
        this.draggingItem = { type, ...item };
        event.dataTransfer.effectAllowed = 'move';
        event.dataTransfer.setData('text/plain', JSON.stringify({ type, id: item.id }));
    },

    endDrag() {
        this.draggingItem = null;
        this.highlightedSegment = null;
    },

    highlightSegment(segId) {
        this.highlightedSegment = segId;
    },

    unhighlightSegment(segId) {
        if (this.highlightedSegment === segId) {
            this.highlightedSegment = null;
        }
    },

    dropOnSegment(segId) {
        this.highlightedSegment = null;

        if (!this.draggingItem) return;

        const targetSegments = this.selectedSegments.length > 0 && this.selectedSegments.includes(segId)
            ? [...this.selectedSegments]
            : [segId];

        if (this.draggingItem.type === 'group') {
            this.$wire.assignGroupToSegments(this.draggingItem.id, targetSegments);
        } else if (this.draggingItem.type === 'trainer') {
            this.$wire.assignTrainerToSegments(this.draggingItem.id, targetSegments);
        }

        this.selectedSegments = [];
        this.draggingItem = null;
    },

    toggleSegmentSelection(segId) {
        const idx = this.selectedSegments.indexOf(segId);
        if (idx > -1) {
            this.selectedSegments.splice(idx, 1);
        } else {
            this.selectedSegments.push(segId);
        }
    },

    getSegments() {
        return this.$wire.gridSegments || [];
    },

    selectRowByIndex(rowIndex) {
        const segments = this.getSegments();
        const rowSegs = segments.filter(s => s.row === rowIndex && s.available).map(s => s.id);
        if (rowSegs.length === 0) return;
        const allSelected = rowSegs.every(id => this.selectedSegments.includes(id));
        if (allSelected) {
            this.selectedSegments = this.selectedSegments.filter(id => !rowSegs.includes(id));
        } else {
            this.selectedSegments = [...new Set([...this.selectedSegments, ...rowSegs])];
        }
    },

    selectColByIndex(colIndex) {
        const segments = this.getSegments();
        const colSegs = segments.filter(s => s.col === colIndex && s.available).map(s => s.id);
        if (colSegs.length === 0) return;
        const allSelected = colSegs.every(id => this.selectedSegments.includes(id));
        if (allSelected) {
            this.selectedSegments = this.selectedSegments.filter(id => !colSegs.includes(id));
        } else {
            this.selectedSegments = [...new Set([...this.selectedSegments, ...colSegs])];
        }
    },

    selectAll() {
        const segments = this.getSegments();
        const allAvailable = segments.filter(s => s.available).map(s => s.id);
        if (allAvailable.length === 0) return;
        const allSelected = allAvailable.every(id => this.selectedSegments.includes(id));
        if (allSelected) {
            this.selectedSegments = [];
        } else {
            this.selectedSegments = allAvailable;
        }
    },

    selectRow() {
        if (this.selectedSegments.length === 0) return;
        const segments = this.getSegments();
        const firstSelected = segments.find(s => s.id === this.selectedSegments[0]);
        if (!firstSelected) return;
        this.selectRowByIndex(firstSelected.row);
    },

    selectCol() {
        if (this.selectedSegments.length === 0) return;
        const segments = this.getSegments();
        const firstSelected = segments.find(s => s.id === this.selectedSegments[0]);
        if (!firstSelected) return;
        this.selectColByIndex(firstSelected.col);
    },
}));
</script>
@endscript
