@php
    use App\Domain\Attendance\Enums\AttendanceStatus;

    $chipClasses = [
        'gray'   => 'bg-gray-100 text-gray-700 ring-1 ring-gray-200',
        'green'  => 'bg-green-100 text-green-800 ring-1 ring-green-200',
        'amber'  => 'bg-amber-100 text-amber-800 ring-1 ring-amber-200',
        'red'    => 'bg-red-100 text-red-800 ring-1 ring-red-200',
        'blue'   => 'bg-blue-100 text-blue-800 ring-1 ring-blue-200',
        'orange' => 'bg-orange-100 text-orange-800 ring-1 ring-orange-200',
        'yellow' => 'bg-yellow-100 text-yellow-800 ring-1 ring-yellow-200',
        'purple' => 'bg-purple-100 text-purple-800 ring-1 ring-purple-200',
    ];

    $dotClasses = [
        'gray'   => 'bg-gray-400',
        'green'  => 'bg-green-500',
        'amber'  => 'bg-amber-500',
        'red'    => 'bg-red-500',
        'blue'   => 'bg-blue-500',
        'orange' => 'bg-orange-500',
        'yellow' => 'bg-yellow-500',
        'purple' => 'bg-purple-500',
    ];
@endphp

<div class="pb-28">
    <!-- Header -->
    <div class="mb-4">
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <h1 class="text-xl sm:text-2xl font-bold text-gray-900">{{ __('تسجيل الحضور') }}</h1>
                <p class="mt-1 text-sm text-gray-500">
                    {{ $session->group?->name_ar ?? '-' }} &mdash;
                    {{ $session->session_date->format('Y-m-d') }}
                    ({{ $session->start_time }} - {{ $session->end_time }})
                </p>
            </div>
            <a href="{{ route('attendance.list') }}"
               class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">
                <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="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
                {{ __('العودة') }}
            </a>
        </div>
    </div>

    <!-- Progress -->
    <div class="mb-4 rounded-2xl border border-gray-200 bg-white p-4 sm:p-5">
        <div class="flex items-end justify-between gap-4">
            <div>
                <p class="text-xs font-medium text-gray-500">{{ __('باقي عليك') }}</p>
                <p class="text-3xl font-bold {{ $progress['pending'] > 0 ? 'text-gray-900' : 'text-green-600' }}" dir="ltr">{{ $progress['pending'] }}</p>
                <p class="mt-0.5 text-xs text-gray-500">{{ __('من إجمالي') }} <span dir="ltr">{{ $progress['total'] }}</span> {{ __('لاعب') }}</p>
            </div>
            <div class="text-end">
                <p class="text-xs font-medium text-gray-500">{{ __('تم تسجيلهم') }}</p>
                <p class="text-3xl font-bold text-green-600" dir="ltr">{{ $progress['done'] }}</p>
            </div>
        </div>
        <div class="mt-3 h-2 w-full overflow-hidden rounded-full bg-gray-100"
             role="progressbar"
             aria-valuemin="0"
             aria-valuemax="{{ $progress['total'] }}"
             aria-valuenow="{{ $progress['done'] }}"
             aria-label="{{ __('نسبة التسجيل') }}">
            <div class="h-full rounded-full bg-green-500 transition-all duration-300" style="width: {{ $progress['percent'] }}%"></div>
        </div>
        <div class="mt-3 flex flex-wrap items-center gap-1.5">
            @foreach([
                AttendanceStatus::Present->value => $summary['present'],
                AttendanceStatus::Late->value => $summary['late'],
                AttendanceStatus::Absent->value => $summary['absent'],
                AttendanceStatus::Excused->value => $summary['excused'],
            ] as $statusValue => $count)
                @php $statusCase = AttendanceStatus::from($statusValue); @endphp
                <span class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium {{ $chipClasses[$statusCase->color()] }}">
                    {{ $statusCase->label() }}
                    <span dir="ltr" class="font-bold">{{ $count }}</span>
                </span>
            @endforeach
        </div>
    </div>

    @error('mark')
        <div class="mb-4 flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">
            <svg class="mt-0.5 h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M5 19h14a2 2 0 001.84-2.75L13.74 4a2 2 0 00-3.48 0l-7.1 12.25A2 2 0 004.99 19z"/></svg>
            <span>{{ $message }}</span>
        </div>
    @enderror

    <div wire:loading.class="opacity-60 pointer-events-none" wire:target="markAs, markPresent, markAllPresent">

    {{-- ========== TRAINERS ========== --}}
    @if($trainerRecords->isNotEmpty())
    <div class="mb-6">
        <div class="flex items-center gap-2 mb-2">
            <div class="flex h-7 w-7 items-center justify-center rounded-lg bg-purple-100">
                <svg class="h-4 w-4 text-purple-600" 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>
            <h2 class="text-sm font-bold text-gray-800">{{ __('المدربون') }}</h2>
            <span class="text-xs text-gray-500" dir="ltr">({{ $trainerRecords->count() }})</span>
        </div>

        <div class="space-y-2">
            @foreach($trainerRecords as $record)
                @php
                    $isOwnRecord = $record->subject_id === $currentUserId;
                    $canMark = $canManageTrainers || $isOwnRecord;
                @endphp
                <div wire:key="trainer-{{ $record->id }}"
                     class="rounded-xl border p-3 {{ $isOwnRecord ? 'border-purple-300 bg-purple-50' : 'border-gray-200 bg-white' }} {{ !$canMark ? 'opacity-60' : '' }}">
                    <div class="flex items-center justify-between gap-2">
                        <span class="min-w-0 truncate text-sm font-semibold text-gray-900">
                            {{ $record->subject?->name ?? '-' }}
                            @if($isOwnRecord)
                                <span class="ms-1 inline-flex items-center rounded bg-purple-600 px-1.5 py-0.5 text-[10px] font-bold text-white">{{ __('أنت') }}</span>
                            @endif
                        </span>
                        <span class="shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium {{ $chipClasses[$record->status->color()] }}">
                            {{ $record->status->label() }}
                        </span>
                    </div>
                    <div class="mt-2">
                        @include('livewire.attendance.partials.status-buttons', ['record' => $record, 'layout' => 'compact', 'canMark' => $canMark])
                    </div>
                </div>
            @endforeach
        </div>
    </div>
    @endif

    {{-- ========== PLAYERS — WORKING LIST ========== --}}
    @if($participantRecords->isNotEmpty())
    <div>
        <div class="mb-2 flex flex-wrap items-center justify-between gap-2">
            <div class="flex items-center gap-2">
                <div class="flex h-7 w-7 items-center justify-center rounded-lg bg-blue-100">
                    <svg class="h-4 w-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                </div>
                <h2 class="text-sm font-bold text-gray-800">{{ __('لم يتم تسجيلهم بعد') }}</h2>
                <span class="rounded-full bg-gray-100 px-2 py-0.5 text-xs font-bold text-gray-700" dir="ltr">{{ $pendingParticipants->count() }}</span>
            </div>

            @if($pendingParticipants->isNotEmpty())
                <button
                    type="button"
                    wire:click="markAllPresent"
                    wire:loading.attr="disabled"
                    wire:target="markAllPresent"
                    class="inline-flex items-center gap-1.5 rounded-lg bg-green-600 px-3 py-2 text-xs font-medium text-white hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-50">
                    <svg wire:loading.remove wire:target="markAllPresent" 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    <svg wire:loading wire:target="markAllPresent" 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"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                    <span wire:loading.remove wire:target="markAllPresent">{{ __('تحضير الجميع') }}</span>
                    <span wire:loading wire:target="markAllPresent">{{ __('جارٍ التحضير...') }}</span>
                </button>
            @endif
        </div>

        @if($pendingParticipants->isEmpty())
            <div class="rounded-2xl border border-green-200 bg-green-50 p-6 text-center">
                <svg class="mx-auto h-10 w-10 text-green-500" 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"/></svg>
                <p class="mt-2 text-sm font-bold text-green-800">{{ __('تم تسجيل كل اللاعبين') }}</p>
                <p class="mt-1 text-xs text-green-700">{{ __('افتح قائمة «تم تسجيلهم» بالأسفل لمراجعة أو تعديل أي لاعب.') }}</p>
            </div>
        @else
            <div class="space-y-2">
                @foreach($pendingParticipants as $record)
                    @php $isUnpaid = in_array($record->subject_id, $notPaidParticipantIds); @endphp
                    <div wire:key="pending-{{ $record->id }}"
                         class="rounded-xl border p-3 {{ $isUnpaid ? 'border-red-300 bg-red-50' : 'border-gray-200 bg-white' }}">
                        <div class="flex items-center justify-between gap-2">
                            <span class="min-w-0 truncate text-base font-semibold {{ $isUnpaid ? 'text-red-700' : 'text-gray-900' }}">
                                {{ $record->subject?->person?->name_ar ?? '-' }}
                            </span>
                            @if($record->subject?->is_free)
                                <x-ui.free-player-badge :small="true" />
                            @elseif($isUnpaid)
                                <span class="shrink-0 rounded bg-red-600 px-1.5 py-0.5 text-[10px] font-bold text-white">{{ __('غير مدفوع') }}</span>
                            @endif
                        </div>
                        <div class="mt-2.5">
                            @include('livewire.attendance.partials.status-buttons', ['record' => $record, 'layout' => 'primary', 'canMark' => true])
                        </div>
                        @include('livewire.attendance.partials.record-note', ['record' => $record])
                    </div>
                @endforeach
            </div>
        @endif

        {{-- ========== PLAYERS — ALREADY RECORDED (collapsed) ========== --}}
        @if($recordedParticipants->isNotEmpty())
        <div class="mt-4">
            <button
                type="button"
                wire:click="toggleRecorded"
                aria-expanded="{{ $showRecorded ? 'true' : 'false' }}"
                class="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 text-start hover:bg-gray-50">
                <div class="flex items-center justify-between gap-3">
                    <div class="flex min-w-0 items-center gap-2">
                        <svg class="h-5 w-5 shrink-0 text-green-600" 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"/></svg>
                        <span class="text-sm font-bold text-gray-900">{{ __('تم تسجيلهم') }}</span>
                        <span class="rounded-full bg-gray-100 px-2 py-0.5 text-xs font-bold text-gray-700" dir="ltr">{{ $recordedParticipants->count() }}</span>
                    </div>
                    <div class="flex shrink-0 items-center gap-2 text-xs font-medium text-gray-500">
                        <span>{{ $showRecorded ? __('إخفاء') : __('عرض / تعديل') }}</span>
                        <svg class="h-4 w-4 transition-transform {{ $showRecorded ? 'rotate-180' : '' }}" 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"/></svg>
                    </div>
                </div>
                <div class="mt-2 flex flex-wrap items-center gap-1.5">
                    @foreach($recordedGroups as $statusValue => $group)
                        @php $groupStatus = AttendanceStatus::from($statusValue); @endphp
                        <span class="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-medium {{ $chipClasses[$groupStatus->color()] }}">
                            {{ $groupStatus->label() }}
                            <span dir="ltr" class="font-bold">{{ $group->count() }}</span>
                        </span>
                    @endforeach
                </div>
            </button>

            @if($showRecorded)
                <div class="mt-2 rounded-xl border border-gray-200 bg-gray-50 p-3">
                    <p class="mb-3 text-xs text-gray-500">{{ __('اضغط على الحالة الجديدة لتعديل تسجيل أي لاعب.') }}</p>

                    @foreach($recordedGroups as $statusValue => $group)
                        @php $groupStatus = AttendanceStatus::from($statusValue); @endphp
                        <div class="{{ $loop->first ? '' : 'mt-4' }}">
                            <div class="mb-1.5 flex items-center gap-2 px-1">
                                <span class="h-2 w-2 rounded-full {{ $dotClasses[$groupStatus->color()] }}"></span>
                                <span class="text-xs font-bold text-gray-700">{{ $groupStatus->label() }}</span>
                                <span class="text-xs text-gray-400" dir="ltr">({{ $group->count() }})</span>
                            </div>
                            <div class="space-y-1.5">
                                @foreach($group as $record)
                                    @php $isUnpaidRecorded = in_array($record->subject_id, $notPaidParticipantIds); @endphp
                                    <div wire:key="recorded-{{ $record->id }}"
                                         class="rounded-lg border bg-white p-2.5 {{ $isUnpaidRecorded ? 'border-red-200' : 'border-gray-200' }}">
                                        <div class="flex items-center justify-between gap-2">
                                            <div class="min-w-0">
                                                <p class="truncate text-sm font-medium {{ $isUnpaidRecorded ? 'text-red-700' : 'text-gray-900' }}">
                                                    {{ $record->subject?->person?->name_ar ?? '-' }}
                                                    @if($record->subject?->is_free)
                                                        <x-ui.free-player-badge :small="true" />
                                                    @elseif($isUnpaidRecorded)
                                                        <span class="ms-1 rounded bg-red-600 px-1.5 py-0.5 text-[10px] font-bold text-white">{{ __('غير مدفوع') }}</span>
                                                    @endif
                                                </p>
                                                @if($record->check_in_at || $record->late_minutes)
                                                    <p class="mt-0.5 text-[11px] text-gray-400">
                                                        @if($record->check_in_at)
                                                            <span dir="ltr">{{ $record->check_in_at->format('H:i') }}</span>
                                                        @endif
                                                        @if($record->late_minutes)
                                                            <span dir="ltr">({{ $record->late_minutes }} {{ __('د') }})</span>
                                                        @endif
                                                    </p>
                                                @endif
                                            </div>
                                            <span class="shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium {{ $chipClasses[$record->status->color()] }}">
                                                {{ $record->status->label() }}
                                            </span>
                                        </div>
                                        <div class="mt-2">
                                            @include('livewire.attendance.partials.status-buttons', ['record' => $record, 'layout' => 'compact', 'canMark' => true])
                                        </div>
                                        @include('livewire.attendance.partials.record-note', ['record' => $record])
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>
        @endif
    </div>
    @endif

    </div>

    {{-- Empty state --}}
    @if($trainerRecords->isEmpty() && $participantRecords->isEmpty())
    <div class="rounded-lg border border-gray-200 bg-white p-12 text-center">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>
        <p class="mt-4 text-sm text-gray-500">{{ __('لا توجد سجلات حضور لهذه الجلسة') }}</p>
    </div>
    @endif

    <!-- Session Notes -->
    <div class="mt-6 rounded-xl border border-gray-200 bg-white p-4">
        <label for="sessionNotes" class="mb-2 block text-sm font-medium text-gray-700">{{ __('ملاحظات الجلسة') }}</label>
        <textarea
            id="sessionNotes"
            wire:model="sessionNotes"
            rows="3"
            class="block w-full rounded-lg border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            placeholder="{{ __('أضف ملاحظات أو تعليقات حول هذه الجلسة...') }}"
        ></textarea>
        <div class="mt-2 flex items-center gap-3">
            <button
                type="button"
                wire:click="saveNotes"
                wire:loading.attr="disabled"
                wire:target="saveNotes"
                class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-3 py-2.5 text-sm font-medium text-white hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50">
                <span wire:loading.remove wire:target="saveNotes">{{ __('حفظ الملاحظات') }}</span>
                <span wire:loading wire:target="saveNotes">{{ __('جارٍ الحفظ...') }}</span>
            </button>
            @if(session('notes_saved'))
                <span class="text-sm text-green-600">{{ session('notes_saved') }}</span>
            @endif
        </div>
    </div>

    {{-- Confirmation toast: proves the tap was recorded, and offers the way back to it --}}
    @if($lastMarked)
        <div wire:key="mark-toast-{{ $markSeq }}"
             x-data="{ shown: true }"
             x-init="setTimeout(() => shown = false, 5000)"
             x-show="shown"
             x-transition.opacity.duration.200ms
             role="status"
             aria-live="polite"
             class="fixed bottom-4 start-4 end-4 z-40 mx-auto max-w-md rounded-xl border {{ $chipClasses[$lastMarked['color']] }} px-4 py-3 shadow-lg">
            <div class="flex items-center justify-between gap-3">
                <div class="flex min-w-0 items-center gap-2">
                    <svg class="h-5 w-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                    <p class="min-w-0 truncate text-sm font-bold">
                        {{ $lastMarked['name'] }} — {{ $lastMarked['label'] }}
                    </p>
                </div>
                <button
                    type="button"
                    wire:click="$set('showRecorded', true)"
                    class="shrink-0 rounded-lg bg-white/70 px-2.5 py-1 text-xs font-medium hover:bg-white">
                    {{ __('تعديل') }}
                </button>
            </div>
        </div>
    @endif
</div>
