<div>
    {{-- Flash messages --}}
    @if (session('success'))
        <div
            x-data="{ show: true }"
            x-show="show"
            x-init="setTimeout(() => show = false, 4000)"
            class="mb-4 rounded-lg border border-green-200 bg-green-50 p-4 text-green-800"
        >
            {{ session('success') }}
        </div>
    @endif

    @if (session('error'))
        <div
            x-data="{ show: true }"
            x-show="show"
            x-init="setTimeout(() => show = false, 6000)"
            class="mb-4 rounded-lg border border-red-200 bg-red-50 p-4 text-red-800"
        >
            {{ session('error') }}
        </div>
    @endif

    {{-- Page header --}}
    <div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">{{ __('السلف والقروض') }}</h1>
            <p class="mt-1 text-sm text-gray-500">{{ __('إدارة سلف المدربين وجدول السداد') }}</p>
        </div>
        @can('payroll.manage')
            <button
                wire:click="openCreateModal"
                class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
            >
                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                </svg>
                {{ __('إضافة سلفة') }}
            </button>
        @endcan
    </div>

    {{-- Filters --}}
    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {{-- Search --}}
        <div class="relative">
            <div class="pointer-events-none absolute inset-y-0 end-0 flex items-center pe-3">
                <svg class="h-4 w-4 text-gray-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 0" />
                </svg>
            </div>
            <input
                wire:model.live.debounce.300ms="search"
                type="text"
                placeholder="{{ __('بحث باسم المدرب...') }}"
                class="block w-full rounded-lg border border-gray-300 bg-white py-2 pe-10 ps-4 text-sm text-gray-900 placeholder-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />
        </div>

        {{-- Status filter --}}
        <select
            wire:model.live="statusFilter"
            class="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
        >
            <option value="">{{ __('جميع الحالات') }}</option>
            @foreach ($statuses as $status)
                <option value="{{ $status->value }}">{{ __($status->label()) }}</option>
            @endforeach
        </select>
    </div>

    {{-- Table --}}
    <div class="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
        <div wire:loading.class="opacity-50 pointer-events-none">
            @if ($advances->isEmpty())
                {{-- Empty state --}}
                <div class="flex flex-col items-center justify-center px-6 py-16 text-center">
                    <svg class="mb-4 h-12 w-12 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                            d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                    </svg>
                    <h3 class="mb-1 text-sm font-semibold text-gray-900">{{ __('لا توجد سلف') }}</h3>
                    <p class="text-sm text-gray-500">{{ __('لم يتم تسجيل أي سلف حتى الآن') }}</p>
                </div>
            @else
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('المدرب') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('المبلغ الكلي') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('القسط الشهري') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('الأقساط') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('المتبقي') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('تاريخ الإصدار') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('الحالة') }}
                                </th>
                                <th class="px-4 py-3 text-start text-xs font-semibold uppercase tracking-wider text-gray-500">
                                    {{ __('نسبة السداد') }}
                                </th>
                                <th class="relative px-4 py-3">
                                    <span class="sr-only">{{ __('إجراءات') }}</span>
                                </th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 bg-white">
                            @foreach ($advances as $advance)
                                @php
                                    $trainerName = optional(optional(optional($advance->trainer)->employee)->person)->name_ar
                                        ?? optional(optional($advance->trainer)->person)->name_ar
                                        ?? __('—');

                                    $paidInstallments = $advance->installments_paid ?? 0;
                                    $totalInstallments = $advance->installments_count ?? 1;
                                    $paidPercent = $totalInstallments > 0
                                        ? min(100, round(($paidInstallments / $totalInstallments) * 100))
                                        : 0;
                                    $remaining = $advance->remaining_balance;
                                @endphp
                                <tr class="transition hover:bg-gray-50">
                                    <td class="px-4 py-3">
                                        <span class="text-sm font-medium text-gray-900">{{ $trainerName }}</span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="text-sm text-gray-700">
                                            {{ number_format($advance->amount / 100, 2) }} {{ __('ج.م') }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="text-sm text-gray-700">
                                            {{ number_format($advance->installment_amount / 100, 2) }} {{ __('ج.م') }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="text-sm text-gray-700">
                                            {{ $paidInstallments }} / {{ $totalInstallments }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="text-sm font-medium text-gray-900">
                                            {{ number_format($remaining / 100, 2) }} {{ __('ج.م') }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="text-sm text-gray-500">
                                            {{ \Carbon\Carbon::parse($advance->issued_date)->format('Y/m/d') }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        @php
                                            $statusValue = $advance->status instanceof \App\Domain\HR\Enums\AdvanceStatus
                                                ? $advance->status->value
                                                : (string) $advance->status;
                                            $statusClasses = match($statusValue) {
                                                'active'         => 'bg-green-100 text-green-800',
                                                'fully_deducted' => 'bg-blue-100 text-blue-800',
                                                'cancelled'      => 'bg-red-100 text-red-800',
                                                'paused'         => 'bg-amber-100 text-amber-800',
                                                default          => 'bg-gray-100 text-gray-700',
                                            };
                                            $statusLabel = $advance->status instanceof \App\Domain\HR\Enums\AdvanceStatus
                                                ? $advance->status->label()
                                                : $statusValue;
                                        @endphp
                                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {{ $statusClasses }}">
                                            {{ $statusLabel }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <div class="flex items-center gap-2">
                                            <div class="h-2 w-24 overflow-hidden rounded-full bg-gray-200">
                                                <div
                                                    class="h-full rounded-full {{ $paidPercent >= 100 ? 'bg-blue-500' : 'bg-indigo-500' }}"
                                                    style="width: {{ $paidPercent }}%"
                                                ></div>
                                            </div>
                                            <span class="text-xs text-gray-500">{{ $paidPercent }}%</span>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3">
                                        <div class="flex items-center gap-2">
                                            @if ($statusValue === 'active')
                                                <button
                                                    wire:click="pauseAdvance({{ $advance->id }})"
                                                    wire:confirm="{{ __('هل تريد إيقاف هذه السلفة مؤقتاً؟') }}"
                                                    class="rounded px-2 py-1 text-xs font-medium text-amber-700 hover:bg-amber-50 transition"
                                                    title="{{ __('إيقاف') }}"
                                                >
                                                    {{ __('إيقاف') }}
                                                </button>
                                                <button
                                                    wire:click="cancelAdvance({{ $advance->id }})"
                                                    wire:confirm="{{ __('هل أنت متأكد من إلغاء هذه السلفة؟') }}"
                                                    class="rounded px-2 py-1 text-xs font-medium text-red-700 hover:bg-red-50 transition"
                                                    title="{{ __('إلغاء') }}"
                                                >
                                                    {{ __('إلغاء') }}
                                                </button>
                                            @elseif ($statusValue === 'paused')
                                                <button
                                                    wire:click="resumeAdvance({{ $advance->id }})"
                                                    wire:confirm="{{ __('هل تريد استئناف خصم هذه السلفة؟') }}"
                                                    class="rounded px-2 py-1 text-xs font-medium text-green-700 hover:bg-green-50 transition"
                                                    title="{{ __('استئناف') }}"
                                                >
                                                    {{ __('استئناف') }}
                                                </button>
                                                <button
                                                    wire:click="cancelAdvance({{ $advance->id }})"
                                                    wire:confirm="{{ __('هل أنت متأكد من إلغاء هذه السلفة؟') }}"
                                                    class="rounded px-2 py-1 text-xs font-medium text-red-700 hover:bg-red-50 transition"
                                                    title="{{ __('إلغاء') }}"
                                                >
                                                    {{ __('إلغاء') }}
                                                </button>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                {{-- Pagination --}}
                @if ($advances->hasPages())
                    <div class="border-t border-gray-200 px-4 py-3">
                        {{ $advances->links() }}
                    </div>
                @endif
            @endif
        </div>
    </div>

    {{-- Create Modal --}}
    <div
        x-data="{ open: @entangle('showCreateModal') }"
        x-show="open"
        x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4"
        style="display: none;"
    >
        {{-- Backdrop --}}
        <div
            x-show="open"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0"
            x-transition:enter-end="opacity-100"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100"
            x-transition:leave-end="opacity-0"
            @click="open = false"
            class="absolute inset-0 bg-gray-900/50"
        ></div>

        {{-- Modal panel --}}
        <div
            x-show="open"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 scale-95"
            x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-95"
            class="relative z-10 w-full max-w-lg rounded-xl bg-white shadow-2xl"
        >
            {{-- Modal header --}}
            <div class="flex items-center justify-between border-b border-gray-200 px-6 py-4">
                <h2 class="text-lg font-semibold text-gray-900">{{ __('إضافة سلفة جديدة') }}</h2>
                <button
                    @click="open = false"
                    class="rounded-lg p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition"
                >
                    <svg class="h-5 w-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>

            {{-- Modal body --}}
            <form wire:submit="createAdvance" class="px-6 py-5 space-y-5">
                {{-- Trainer select --}}
                <div>
                    <label class="mb-1.5 block text-sm font-medium text-gray-700">
                        {{ __('المدرب') }}
                        <span class="text-red-500">*</span>
                    </label>
                    <select
                        wire:model="selectedTrainerId"
                        class="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 @error('selectedTrainerId') border-red-400 @enderror"
                    >
                        <option value="">{{ __('اختر مدرباً...') }}</option>
                        @foreach ($trainers as $trainer)
                            @php
                                $name = optional(optional($trainer->employee)->person)->name_ar
                                    ?? optional($trainer->person)->name_ar
                                    ?? __('مدرب #') . $trainer->id;
                            @endphp
                            <option value="{{ $trainer->id }}">{{ $name }}</option>
                        @endforeach
                    </select>
                    @error('selectedTrainerId')
                        <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Amount --}}
                <div>
                    <label class="mb-1.5 block text-sm font-medium text-gray-700">
                        {{ __('المبلغ (جنيه)') }}
                        <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <input
                            wire:model="amount"
                            type="number"
                            min="1"
                            step="0.01"
                            dir="ltr"
                            placeholder="0.00"
                            class="block w-full rounded-lg border border-gray-300 bg-white py-2 pe-10 ps-3 text-sm text-gray-900 placeholder-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 @error('amount') border-red-400 @enderror"
                        />
                        <div class="pointer-events-none absolute inset-y-0 end-0 flex items-center pe-3">
                            <span class="text-xs text-gray-400">{{ __('ج.م') }}</span>
                        </div>
                    </div>
                    @error('amount')
                        <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Installments count --}}
                <div>
                    <label class="mb-1.5 block text-sm font-medium text-gray-700">
                        {{ __('عدد الأقساط') }}
                        <span class="text-red-500">*</span>
                    </label>
                    <input
                        wire:model="installmentsCount"
                        type="number"
                        min="1"
                        max="24"
                        dir="ltr"
                        class="block w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 @error('installmentsCount') border-red-400 @enderror"
                    />
                    @error('installmentsCount')
                        <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                    @enderror
                    @if ($amount && $installmentsCount > 0)
                        <p class="mt-1.5 text-xs text-indigo-600">
                            {{ __('القسط الشهري:') }}
                            {{ number_format((float) $amount / max(1, (int) $installmentsCount), 2) }}
                            {{ __('ج.م') }}
                        </p>
                    @endif
                </div>

                {{-- Reason --}}
                <div>
                    <label class="mb-1.5 block text-sm font-medium text-gray-700">
                        {{ __('السبب / الملاحظات') }}
                    </label>
                    <textarea
                        wire:model="reason"
                        rows="3"
                        placeholder="{{ __('سبب السلفة أو أي ملاحظات إضافية...') }}"
                        class="block w-full resize-none rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                    ></textarea>
                </div>

                {{-- Modal footer --}}
                <div class="flex items-center justify-end gap-3 border-t border-gray-200 pt-4">
                    <button
                        type="button"
                        @click="open = false"
                        class="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
                    >
                        {{ __('إلغاء') }}
                    </button>
                    <button
                        type="submit"
                        wire:loading.attr="disabled"
                        wire:target="createAdvance"
                        class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-60"
                    >
                        <span wire:loading.remove wire:target="createAdvance">{{ __('حفظ السلفة') }}</span>
                        <span wire:loading wire:target="createAdvance" class="flex items-center gap-2">
                            <svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                            </svg>
                            {{ __('جارٍ الحفظ...') }}
                        </span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
