@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>
                </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['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
                            $maxRow = collect($gridSegments)->max('row') ?? 0;
                            $maxCol = collect($gridSegments)->max('col') ?? 0;
                            $isGrid = $maxRow > 0 || $maxCol > 0;
                            $cols = $isGrid ? $maxCol + 1 : count($gridSegments);
                            $rows = $isGrid ? $maxRow + 1 : 1;
                        @endphp

                        <div class="overflow-x-auto">
                            <div class="{{ $isGrid ? 'grid gap-3' : 'flex flex-wrap gap-3' }} min-w-[400px]"
                                 style="{{ $isGrid ? 'grid-template-columns: repeat(' . $cols . ', minmax(0, 1fr)); grid-template-rows: repeat(' . $rows . ', minmax(120px, 1fr))' : '' }}">
                                @foreach($gridSegments as $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';
                                    @endphp
                                    <div
                                        @dragover.prevent="highlightSegment({{ $seg['id'] }})"
                                        @dragleave="unhighlightSegment({{ $seg['id'] }})"
                                        @drop.prevent="dropOnSegment({{ $seg['id'] }})"
                                        @click="toggleSegmentSelection({{ $seg['id'] }})"
                                        :class="{
                                            'ring-2 ring-blue-400 bg-blue-50': selectedSegments.includes({{ $seg['id'] }}),
                                            'ring-2 ring-green-400 bg-green-50': highlightedSegment === {{ $seg['id'] }},
                                        }"
                                        class="relative border-2 rounded-xl p-3 min-h-[120px] flex flex-col transition-all cursor-pointer
                                            {{ !$seg['available'] ? 'border-gray-300 bg-gray-100 cursor-not-allowed opacity-60' : '' }}
                                            {{ $isExisting ? 'border-blue-300 bg-blue-50' : '' }}
                                            {{ $isNewGroup ? 'border-green-300 bg-green-50' : '' }}
                                            {{ $isNewTrainer ? 'border-purple-300 bg-purple-50' : '' }}
                                            {{ !$isOccupied && $seg['available'] ? 'border-dashed border-gray-300 hover:border-blue-300 hover:bg-blue-50/30' : '' }}"
                                        @if($isGrid) style="grid-row: {{ ($seg['row'] ?? 0) + 1 }}; grid-column: {{ ($seg['col'] ?? 0) + 1 }}" @endif
                                    >
                                        {{-- Cell header --}}
                                        <div class="flex items-center justify-between mb-1">
                                            <span class="text-xs font-mono text-gray-400">{{ $seg['code'] }}</span>
                                            @if($seg['capacity'])
                                                <span class="text-[10px] text-gray-400" dir="ltr">{{ $seg['capacity'] }}p</span>
                                            @endif
                                        </div>

                                        {{-- Existing reservation --}}
                                        @if($isExisting)
                                            <div class="flex-1 flex flex-col justify-center">
                                                <p class="text-sm font-semibold text-blue-800 truncate">{{ $segAssignment['title'] ?? '' }}</p>
                                                @if($segAssignment['trainer_name'] ?? null)
                                                <p class="text-[10px] text-blue-600 mt-0.5 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>
                                                    {{ $segAssignment['trainer_name'] }}
                                                </p>
                                                @endif
                                                @if($segAssignment['is_recurring'] ?? false)
                                                    <span class="inline-flex items-center gap-1 mt-1 text-[10px] text-purple-600">
                                                        <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 mt-2">
                                                <button wire:click="cancelReservation({{ $segAssignment['reservation_id'] }})"
                                                        wire:confirm="{{ __('إلغاء هذا الحجز؟') }}"
                                                        class="text-[10px] text-red-500 hover:text-red-700 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 assignment (unsaved) --}}
                                        @elseif($isNewGroup)
                                            <div class="flex-1 flex flex-col justify-center">
                                                <p class="text-sm font-semibold text-green-800 truncate">{{ $segAssignment['group_name'] ?? '' }}</p>
                                                @if($segAssignment['implied_trainer'] ?? null)
                                                <p class="text-[10px] text-green-600 mt-0.5 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>
                                                    {{ $segAssignment['implied_trainer'] }} ({{ __('تلقائي') }})
                                                </p>
                                                @endif
                                                <span class="inline-flex items-center mt-1 text-[10px] text-green-600">{{ __('جديد — لم يُحفظ بعد') }}</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">{{ __('إزالة') }}</button>
                                            @endif

                                        {{-- New trainer assignment (unsaved) --}}
                                        @elseif($isNewTrainer)
                                            <div class="flex-1 flex flex-col justify-center">
                                                <p class="text-sm font-semibold text-purple-800 truncate">{{ $segAssignment['trainer_name'] ?? '' }}</p>
                                                <span class="inline-flex items-center mt-1 text-[10px] text-purple-600">{{ __('مدرب — لم يُحفظ بعد') }}</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">{{ __('إزالة') }}</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>
                                @endforeach
                            </div>
                        </div>

                        {{-- Legend --}}
                        <div class="mt-4 flex flex-wrap items-center gap-3 sm:gap-4 text-xs text-gray-500">
                            <span class="flex items-center gap-1"><span class="w-3 h-3 border-2 border-dashed border-gray-300 rounded"></span> {{ __('متاح') }}</span>
                            <span class="flex items-center gap-1"><span class="w-3 h-3 bg-blue-100 border border-blue-300 rounded"></span> {{ __('محجوز') }}</span>
                            <span class="flex items-center gap-1"><span class="w-3 h-3 bg-green-100 border border-green-300 rounded"></span> {{ __('جديد (لم يُحفظ)') }}</span>
                            <span class="flex items-center gap-1"><span class="w-3 h-3 bg-purple-100 border border-purple-300 rounded"></span> {{ __('مدرب') }}</span>
                            <span class="flex items-center gap-1"><span class="w-3 h-3 bg-gray-100 border border-gray-300 rounded"></span> {{ __('غير متاح') }}</span>
                            <span class="flex items-center gap-1"><span class="w-3 h-3 border-2 border-blue-400 rounded ring-2 ring-blue-400/30"></span> {{ __('محدد') }}</span>
                        </div>

                        {{-- Multi-select helper --}}
                        <div x-show="selectedSegments.length > 0" x-transition class="mt-4 bg-blue-50 border border-blue-200 rounded-xl p-3 sm:p-4">
                            <p class="text-sm font-medium text-blue-800 mb-2">
                                {{ __('تم تحديد') }} <span x-text="selectedSegments.length" class="font-bold"></span> {{ __('خلية') }}
                            </p>
                            <p class="text-xs text-blue-600 mb-3">{{ __('اسحب مجموعة أو مدرب على أي خلية محددة لتعيينهم جميعاً') }}</p>
                            <div class="flex flex-wrap gap-2">
                                <button @click="selectedSegments = []" class="text-xs text-gray-500 hover:text-gray-700 border border-gray-300 px-2 py-1.5 rounded">{{ __('إلغاء التحديد') }}</button>
                                <button @click="selectRow()" class="text-xs text-blue-600 hover:text-blue-700 border border-blue-300 px-2 py-1.5 rounded">{{ __('تحديد الصف') }}</button>
                                <button @click="selectCol()" class="text-xs text-blue-600 hover:text-blue-700 border border-blue-300 px-2 py-1.5 rounded">{{ __('تحديد العمود') }}</button>
                                <button @click="selectAll()" class="text-xs text-blue-600 hover:text-blue-700 border border-blue-300 px-2 py-1.5 rounded">{{ __('تحديد الكل') }}</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);
        }
    },

    selectRow() {
        if (this.selectedSegments.length === 0) return;
        const segments = @json($gridSegments);
        const firstSelected = segments.find(s => s.id === this.selectedSegments[0]);
        if (!firstSelected) return;
        const rowSegs = segments.filter(s => s.row === firstSelected.row && s.available).map(s => s.id);
        this.selectedSegments = [...new Set([...this.selectedSegments, ...rowSegs])];
    },

    selectCol() {
        if (this.selectedSegments.length === 0) return;
        const segments = @json($gridSegments);
        const firstSelected = segments.find(s => s.id === this.selectedSegments[0]);
        if (!firstSelected) return;
        const colSegs = segments.filter(s => s.col === firstSelected.col && s.available).map(s => s.id);
        this.selectedSegments = [...new Set([...this.selectedSegments, ...colSegs])];
    },

    selectAll() {
        const segments = @json($gridSegments);
        this.selectedSegments = segments.filter(s => s.available).map(s => s.id);
    },
}));
</script>
@endscript
