<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <h1 class="text-2xl font-black text-slate-900 tracking-tight mb-1">إدارة الفروع</h1>
            <p class="text-sm text-slate-500 font-medium">التحكم في الفروع التابعة للكيانات.</p>
        </div>
        @can('create records')
        <button wire:click="openModal" class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2.5 rounded-lg font-bold shadow-sm flex items-center gap-2 transition-colors shrink-0">
            <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="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
            فرع جديد
        </button>
        @endcan
    </div>

    @if (session()->has('message'))
        <div class="mb-6 p-4 bg-emerald-50 text-emerald-800 rounded-2xl flex items-center gap-3 border border-emerald-200 shadow-sm">
            <div class="bg-emerald-100 rounded-full p-1 shrink-0">
                <svg class="w-5 h-5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
            </div>
            <span class="font-bold text-sm">{{ session('message') }}</span>
        </div>
    @endif

    <!-- Card -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100">
        
        <!-- Search & Filter Bar -->
        <div class="p-4 border-b border-slate-100 bg-slate-50/50 relative z-20 flex flex-col md:flex-row items-center gap-4 rounded-t-2xl relative z-20">
            <!-- Search -->
            <div class="relative w-full max-w-md">
                <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                    <svg class="w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                </div>
                <input wire:model.live.debounce.300ms="search" type="text" placeholder="البحث برمز أو اسم الفرع أو السجل..." class="block w-full bg-white border-slate-200 rounded-xl pr-10 pl-4 py-2.5 text-sm focus:ring-indigo-500 focus:border-indigo-500 shadow-sm">
            </div>
            
            <!-- Entity Filter -->
            <div class="w-full md:w-64" x-data="{
                open: false,
                search: '',
                selected: @entangle('filter_entity_id').live,
                options: {{ Js::from($entities->map(fn($e) => ['id' => $e->id, 'name' => $e->name])) }},
                get filteredOptions() {
                    return this.search === '' ? this.options : this.options.filter(o => o.name.includes(this.search));
                },
                get selectedName() {
                    let opt = this.options.find(o => o.id == this.selected);
                    return opt ? opt.name : 'جميع الكيانات';
                }
            }" @click.away="open = false">
                <div class="relative">
                    <button @click="open = !open" type="button" class="w-full text-right bg-white border border-slate-200 rounded-xl px-4 py-2.5 text-sm focus:ring-indigo-500 focus:border-indigo-500 shadow-sm flex items-center justify-between">
                        <span x-text="selectedName" class="font-bold text-slate-700"></span>
                        <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                    </button>

                    <div x-show="open" x-cloak class="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-xl shadow-xl overflow-hidden">
                        <div class="p-2 border-b border-slate-100 bg-slate-50">
                            <input type="text" x-model="search" placeholder="ابحث عن كيان..." class="w-full border-slate-200 rounded-lg text-sm py-1.5 px-3 focus:ring-indigo-500 focus:border-indigo-500">
                        </div>
                        <ul class="max-h-48 overflow-y-auto py-1">
                            <li @click="selected = ''; open = false; search = ''" 
                                class="px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 transition-colors"
                                :class="selected == '' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                جميع الكيانات
                            </li>
                            <template x-for="option in filteredOptions" :key="option.id">
                                <li @click="selected = option.id; open = false; search = ''" 
                                    class="px-4 py-2 text-sm cursor-pointer hover:bg-slate-50 transition-colors"
                                    :class="selected == option.id ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                    <span x-text="option.name"></span>
                                </li>
                            </template>
                            <li x-show="filteredOptions.length === 0" class="px-4 py-3 text-sm text-slate-500 text-center">لا توجد نتائج</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Status Filter -->
            <div class="w-full sm:w-auto shrink-0 flex items-center gap-2">
                <label class="text-sm font-bold text-slate-600 hidden sm:block">الحالة:</label>
                <select wire:model.live="statusFilter" class="block w-full sm:w-48 bg-white border-slate-200 rounded-xl py-2.5 text-sm focus:ring-indigo-500 focus:border-indigo-500 shadow-sm font-bold text-slate-700">
                    <option value="all">الكل</option>
                    <option value="active">الفروع النشطة فقط</option>
                    <option value="inactive">الفروع الموقوفة فقط</option>
                </select>
            </div>
        </div>

        <!-- Table -->
        <div class="overflow-x-auto">
            <table class="w-full text-right whitespace-nowrap">
                <thead>
                    <tr class="bg-slate-50 border-b border-slate-100 text-slate-500 text-xs font-bold">
                        <th class="px-6 py-4 w-12 text-center">#</th>
                        <th class="px-6 py-4">رمز الفرع</th>
                        <th class="px-6 py-4">بيانات الفرع</th>
                        <th class="px-6 py-4">الكيان التابع له</th>
                        <th class="px-6 py-4">السجل التجاري</th>
                        <th class="px-6 py-4">الرقم الضريبي</th>
                        <th class="px-6 py-4">الحالة</th>
                        <th class="px-6 py-4 text-left">إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($branches as $branch)
                        <tr class="hover:bg-slate-50/50 transition-colors border-b border-slate-100 last:border-0">
                            <td class="px-6 py-4 text-center">
                                <span class="text-xs font-bold text-slate-400">{{ ($branches->currentPage() - 1) * $branches->perPage() + $loop->iteration }}</span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-bold bg-slate-100 text-slate-700 border border-slate-200" dir="ltr">
                                    {{ $branch->code }}
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <div class="font-bold text-slate-800 text-sm">{{ $branch->name }}</div>
                                @if($branch->short_name)
                                    <div class="text-xs text-slate-500">{{ $branch->short_name }}</div>
                                @endif
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm font-bold text-indigo-700 bg-indigo-50 px-2 py-1 rounded-md border border-indigo-100">
                                    {{ $branch->entity->name ?? '—' }}
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm text-slate-600" dir="ltr">{{ $branch->commercial_record ?? '—' }}</span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm text-slate-600" dir="ltr">{{ $branch->tax_number ?? '—' }}</span>
                            </td>
                            <td class="px-6 py-4">
                                @if($branch->is_active)
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-100">
                                        <span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span> نشط
                                    </span>
                                @else
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-bold bg-red-50 text-red-700 border border-red-100">
                                        <span class="w-1.5 h-1.5 rounded-full bg-red-500"></span> موقوف
                                    </span>
                                @endif
                            </td>
                            <td class="px-6 py-4 text-left">
                                <div class="flex items-center justify-end gap-2">
                                    @can('update records')
                                    <button wire:click="toggleStatus({{ $branch->id }})" class="p-2 {{ $branch->is_active ? 'text-rose-400 hover:text-rose-600 hover:bg-rose-50' : 'text-emerald-400 hover:text-emerald-600 hover:bg-emerald-50' }} rounded-lg transition" title="{{ $branch->is_active ? 'إيقاف الفرع' : 'تنشيط الفرع' }}">
                                        @if($branch->is_active)
                                        <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="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        @else
                                        <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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        @endif
                                    </button>
                                    
                                    <button wire:click="edit({{ $branch->id }})" class="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition" title="تعديل">
                                        <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                    </button>
                                    @endcan
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="px-6 py-12 text-center text-slate-500">
                                <div class="flex flex-col items-center justify-center">
                                    <svg class="w-12 h-12 text-slate-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"></path></svg>
                                    <span class="text-sm font-medium">لا توجد فروع مسجلة.</span>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        @if($branches->hasPages())
        <div class="p-4 border-t border-slate-100 bg-slate-50/50">
            {{ $branches->links() }}
        </div>
        @endif
    </div>

    <!-- Modal -->
    <div x-data="{ open: @entangle('isModalOpen') }" 
         x-show="open" 
         x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-0" 
         aria-labelledby="modal-title" 
         role="dialog" 
         aria-modal="true">
        
        <!-- Backdrop -->
        <div x-show="open" 
             x-transition.opacity 
             class="fixed inset-0 bg-slate-900/60 transition-opacity" 
             @click="open = false" 
             aria-hidden="true"></div>

        <!-- Modal Panel -->
        <div x-show="open" 
             x-transition.opacity.translate.scale 
             class="relative bg-white rounded-2xl text-right overflow-hidden shadow-2xl transform transition-all w-full max-w-lg border border-slate-100 flex flex-col max-h-[90vh]">
                
                <!-- Modal Header -->
                <div class="px-6 py-4 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
                    <h3 class="text-lg font-bold text-slate-800" id="modal-title">
                        {{ $branch_id ? 'تعديل بيانات الفرع' : 'إضافة فرع جديد' }}
                    </h3>
                    <button @click="open = false" type="button" class="text-slate-400 hover:text-slate-600 transition p-1 rounded-lg hover:bg-slate-200/50">
                        <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"></path></svg>
                    </button>
                </div>

                <!-- Form -->
                <form wire:submit.prevent="save" class="flex flex-col text-right">
                    <div class="p-6 overflow-y-auto max-h-[70vh] space-y-4">
                        
                        <div class="bg-indigo-50 p-4 rounded-xl border border-indigo-100">
                            <label class="block text-xs font-bold text-indigo-900 mb-1.5">الكيان التابع له الفرع <span class="text-red-500">*</span></label>
                            <div class="flex gap-2">
                                <!-- Searchable Select -->
                                <div x-data="{
                                    open: false,
                                    search: '',
                                    selected: @entangle('entity_id'),
                                    options: {{ Js::from($entities->map(fn($e) => ['id' => $e->id, 'name' => $e->name])) }},
                                    get filteredOptions() {
                                        return this.search === '' ? this.options : this.options.filter(o => o.name.includes(this.search));
                                    },
                                    get selectedName() {
                                        let opt = this.options.find(o => o.id == this.selected);
                                        return opt ? opt.name : 'اختر الكيان...';
                                    }
                                }" class="relative flex-1" @click.away="open = false">
                                    <button @click="open = !open" type="button" class="w-full text-right bg-white border border-indigo-200 rounded-lg shadow-sm px-4 h-10 text-sm focus:ring-indigo-500 focus:border-indigo-500 flex items-center justify-between">
                                        <span x-text="selectedName" :class="!selected ? 'text-slate-500' : 'text-slate-900 font-bold'"></span>
                                        <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                                    </button>
                                    <div x-show="open" x-cloak class="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-xl overflow-hidden">
                                        <div class="p-2 border-b border-slate-100 bg-slate-50">
                                            <input type="text" x-model="search" placeholder="ابحث عن كيان..." class="w-full border-slate-200 rounded-md text-sm py-1.5 px-3 focus:ring-indigo-500 focus:border-indigo-500">
                                        </div>
                                        <ul class="max-h-40 overflow-y-auto py-1">
                                            <template x-for="option in filteredOptions" :key="option.id">
                                                <li @click="selected = option.id; open = false; search = ''" 
                                                    class="px-4 py-2 text-sm cursor-pointer hover:bg-indigo-50 hover:text-indigo-700 transition-colors"
                                                    :class="selected == option.id ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-slate-700'">
                                                    <span x-text="option.name"></span>
                                                </li>
                                            </template>
                                            <li x-show="filteredOptions.length === 0" class="px-4 py-3 text-sm text-slate-500 text-center">لا توجد نتائج</li>
                                        </ul>
                                    </div>
                                </div>
                                <button type="button" wire:click="fetchEntityData" class="px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow-sm transition-colors flex items-center gap-1.5 whitespace-nowrap">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path></svg>
                                    سحب البيانات
                                </button>
                            </div>
                            @error('entity_id') <span class="text-[10px] text-red-500 mt-1 block font-bold">{{ $message }}</span> @enderror
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1.5">رمز الفرع <span class="text-red-500">*</span></label>
                            <input type="text" wire:model.live.debounce.300ms="code" placeholder="مثال: BR-001" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10 text-left" dir="ltr" required>
                            @error('code') <span class="text-[10px] text-red-500 mt-1 block font-bold">{{ $message }}</span> @enderror
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1.5">اسم الفرع <span class="text-red-500">*</span></label>
                            <input type="text" wire:model.live.debounce.300ms="name" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10" required>
                            @error('name') <span class="text-[10px] text-red-500 mt-1 block font-bold">{{ $message }}</span> @enderror
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-bold text-slate-700 mb-1.5">الاسم المختصر</label>
                                <input type="text" wire:model="short_name" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10">
                                @error('short_name') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-700 mb-1.5">رقم الهاتف / الجوال</label>
                                <input type="text" wire:model="phone" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10 text-left" dir="ltr">
                                @error('phone') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-bold text-slate-700 mb-1.5">السجل التجاري</label>
                                <input type="text" wire:model.live.debounce.300ms="commercial_record" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10 text-left" dir="ltr">
                                @error('commercial_record') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-700 mb-1.5">الرقم الضريبي</label>
                                <input type="text" wire:model.live.debounce.300ms="tax_number" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10 text-left" dir="ltr">
                                @error('tax_number') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                            </div>
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1.5">العنوان</label>
                            <input type="text" wire:model="address" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10">
                            @error('address') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1.5">حالة الفرع <span class="text-red-500">*</span></label>
                            <select wire:model="is_active" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm h-10 bg-white" required>
                                <option value="1">نشط ومفعل</option>
                                <option value="0">موقوف</option>
                            </select>
                            @error('is_active') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1.5">ملاحظات</label>
                            <textarea wire:model="notes" rows="2" class="w-full border-slate-200 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm"></textarea>
                            @error('notes') <span class="text-[10px] text-red-500 mt-1 block">{{ $message }}</span> @enderror
                        </div>

                    </div>
                    
                    <!-- Form Footer -->
                    <div class="px-6 py-4 bg-slate-50 border-t border-slate-100 flex items-center justify-end gap-3 shrink-0 text-right">
                        <button type="button" @click="open = false" class="px-5 py-2.5 bg-white border border-slate-300 hover:bg-slate-50 hover:border-slate-400 text-slate-700 text-sm font-bold rounded-lg shadow-sm transition-all">
                            إلغاء
                        </button>
                        <button type="submit" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-bold rounded-lg shadow-sm transition-all flex items-center gap-2">
                            <span wire:loading.remove wire:target="save">حفظ الفرع</span>
                            <span wire:loading wire:target="save">جاري الحفظ...</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
