@php
    $attendancePopupUser = \Illuminate\Support\Facades\Auth::user();
    $attendancePopupEmployee = null;
    $attendancePopupToday = today();
    $attendancePopupRecord = null;
    $attendancePopupSetting = null;
    $attendancePopupShouldShow = false;
    $attendancePopupIsAutoAttendance = false;
    $attendancePopupCanUseAttendance = false;
    $attendancePopupStatusText = 'Belum absen masuk';
    $attendancePopupAction = 'check-in';
    $attendancePopupAllowedCheckoutTime = null;
    $attendancePopupHiddenRoles = ['developer', 'owner'];
    $attendancePopupUserRoles = [];
    $attendancePopupIsHiddenRole = false;

    if ($attendancePopupUser) {
        if (method_exists($attendancePopupUser, 'getRoleNames')) {
            $attendancePopupUserRoles = array_merge(
                $attendancePopupUserRoles,
                $attendancePopupUser->getRoleNames()->map(fn ($role) => strtolower((string) $role))->toArray()
            );
        }

        if (method_exists($attendancePopupUser, 'hasAnyRole')) {
            try {
                $attendancePopupIsHiddenRole = $attendancePopupUser->hasAnyRole($attendancePopupHiddenRoles);
            } catch (\Throwable $e) {
                $attendancePopupIsHiddenRole = false;
            }
        }

        foreach (['role', 'role_name'] as $roleColumn) {
            if (!empty($attendancePopupUser->{$roleColumn}) && is_string($attendancePopupUser->{$roleColumn})) {
                $attendancePopupUserRoles[] = strtolower((string) $attendancePopupUser->{$roleColumn});
            }
        }

        if (!empty($attendancePopupUser->role) && is_object($attendancePopupUser->role) && !empty($attendancePopupUser->role->name)) {
            $attendancePopupUserRoles[] = strtolower((string) $attendancePopupUser->role->name);
        }

        $attendancePopupIsHiddenRole = $attendancePopupIsHiddenRole
            || count(array_intersect($attendancePopupHiddenRoles, array_unique($attendancePopupUserRoles))) > 0;
    }

    if (
        $attendancePopupUser
        && !$attendancePopupIsHiddenRole
        && \Illuminate\Support\Facades\Route::has('attendance.index')
        && \Illuminate\Support\Facades\Route::has('attendance.check-in')
        && \Illuminate\Support\Facades\Route::has('attendance.check-out')
    ) {
        if (\Illuminate\Support\Facades\Schema::hasTable('employees')) {
            if (\Illuminate\Support\Facades\Schema::hasColumn('employees', 'user_id')) {
                $attendancePopupEmployee = \App\Models\Employee::where('user_id', $attendancePopupUser->id)->first();
            }

            if (
                !$attendancePopupEmployee
                && \Illuminate\Support\Facades\Schema::hasColumn('employees', 'email')
                && !empty($attendancePopupUser->email)
            ) {
                $attendancePopupEmployee = \App\Models\Employee::where('email', $attendancePopupUser->email)->first();
            }

            if (
                !$attendancePopupEmployee
                && \Illuminate\Support\Facades\Schema::hasColumn('employees', 'name')
                && !empty($attendancePopupUser->name)
            ) {
                $attendancePopupEmployee = \App\Models\Employee::where('name', $attendancePopupUser->name)->first();
            }
        }

        if ($attendancePopupEmployee) {
            if (\Illuminate\Support\Facades\Schema::hasTable('attendances')) {
                $attendancePopupRecord = \App\Models\Attendance::where('employee_id', $attendancePopupEmployee->id)
                    ->whereDate('attendance_date', $attendancePopupToday)
                    ->first();
            }

            if (\Illuminate\Support\Facades\Schema::hasColumn('employees', 'is_auto_attendance')) {
                $attendancePopupIsAutoAttendance = (bool) ($attendancePopupEmployee->is_auto_attendance ?? false);
            }

            if (\Illuminate\Support\Facades\Schema::hasTable('attendance_settings')) {
                $attendancePopupSetting = \App\Models\AttendanceSetting::where('is_active', true)->first();
            }

            if (!$attendancePopupIsAutoAttendance && $attendancePopupSetting) {
                /*
                 * Belum absen masuk:
                 * Popup dan tombol Absensi muncul.
                 */
                if (!$attendancePopupRecord || !$attendancePopupRecord->check_in_at) {
                    $attendancePopupShouldShow = true;
                    $attendancePopupCanUseAttendance = true;
                    $attendancePopupStatusText = 'Belum absen masuk';
                    $attendancePopupAction = 'check-in';
                }

                /*
                 * Sudah absen masuk, belum absen pulang:
                 * Popup dan tombol Absensi hilang sampai sudah masuk jam pulang.
                 */
                elseif ($attendancePopupRecord->check_in_at && !$attendancePopupRecord->check_out_at) {
                    $canCheckoutNow = false;

                    if (!empty($attendancePopupSetting->work_end_time)) {
                        $scheduledEnd = \Carbon\Carbon::parse(now()->toDateString() . ' ' . $attendancePopupSetting->work_end_time);
                        $tolerance = (int) ($attendancePopupSetting->early_leave_tolerance_minutes ?? 0);
                        $attendancePopupAllowedCheckoutTime = $scheduledEnd->copy()->subMinutes($tolerance);

                        $canCheckoutNow = now()->greaterThanOrEqualTo($attendancePopupAllowedCheckoutTime);
                    } else {
                        /*
                         * Kalau jam pulang belum diatur, fallback: tombol pulang tetap muncul
                         * setelah sudah absen masuk agar user masih bisa absen pulang.
                         */
                        $canCheckoutNow = true;
                    }

                    if ($canCheckoutNow) {
                        $attendancePopupShouldShow = true;
                        $attendancePopupCanUseAttendance = true;
                        $attendancePopupStatusText = 'Sudah waktunya absen pulang';
                        $attendancePopupAction = 'check-out';
                    } else {
                        $attendancePopupShouldShow = false;
                        $attendancePopupCanUseAttendance = false;
                        $attendancePopupStatusText = 'Sudah absen masuk, belum waktunya absen pulang';
                        $attendancePopupAction = 'waiting-checkout';
                    }
                }

                /*
                 * Sudah absen masuk dan pulang:
                 * Popup dan tombol Absensi hilang.
                 */
                elseif ($attendancePopupRecord->check_in_at && $attendancePopupRecord->check_out_at) {
                    $attendancePopupShouldShow = false;
                    $attendancePopupCanUseAttendance = false;
                    $attendancePopupStatusText = 'Absensi hari ini sudah lengkap';
                    $attendancePopupAction = 'done';
                }
            }
        }
    }
@endphp

@if($attendancePopupShouldShow)
    <div
        x-data="attendanceGlobalPopup()"
        x-init="init()"
        x-show="open"
        x-cloak
        class="fixed inset-0 z-[99999] flex items-center justify-center bg-gray-900/60 px-4 py-6"
    >
        <div
            x-show="open"
            x-transition
            class="w-full max-w-md rounded-2xl border border-gray-200 bg-white shadow-xl dark:border-gray-800 dark:bg-gray-900"
        >
            <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">
                            Pengingat Absensi
                        </h3>
                        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            {{ $attendancePopupStatusText }}
                        </p>
                    </div>

                    <button
                        type="button"
                        @click="closeForNow()"
                        class="rounded-lg p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/10 dark:hover:text-white"
                        title="Tutup sementara"
                    >
                        <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
            </div>

            <div class="space-y-4 p-5">
                <div class="rounded-2xl bg-brand-50 p-4 text-sm text-brand-700 dark:bg-brand-500/15 dark:text-brand-300">
                    <div class="font-medium">
                        {{ $attendancePopupEmployee->name ?? 'Karyawan' }}
                    </div>

                    <div class="mt-1 text-xs">
                        Lokasi harus berada dalam radius
                        {{ $attendancePopupSetting->radius_meters ?? 0 }} meter
                        dari {{ $attendancePopupSetting->location_name ?? 'lokasi absensi' }}.
                    </div>

                    @if($attendancePopupAction === 'check-out' && $attendancePopupAllowedCheckoutTime)
                        <div class="mt-2 text-xs">
                            Absen pulang tersedia mulai pukul
                            <strong>{{ $attendancePopupAllowedCheckoutTime->format('H:i') }}</strong>.
                        </div>
                    @endif
                </div>

                @if($attendancePopupRecord?->check_in_at)
                    <div class="grid grid-cols-2 gap-3 text-sm">
                        <div class="rounded-xl border border-gray-200 p-3 dark:border-gray-800">
                            <div class="text-xs text-gray-500 dark:text-gray-400">Masuk</div>
                            <div class="mt-1 font-semibold text-gray-800 dark:text-white/90">
                                {{ $attendancePopupRecord->check_in_at->format('H:i') }}
                            </div>
                        </div>

                        <div class="rounded-xl border border-gray-200 p-3 dark:border-gray-800">
                            <div class="text-xs text-gray-500 dark:text-gray-400">Pulang</div>
                            <div class="mt-1 font-semibold text-gray-800 dark:text-white/90">
                                {{ $attendancePopupRecord->check_out_at?->format('H:i') ?? '-' }}
                            </div>
                        </div>
                    </div>
                @endif

                <p id="attendanceGlobalPopupStatus" class="text-sm text-gray-500 dark:text-gray-400"></p>

                @if($attendancePopupAction === 'check-in')
                    <form id="attendanceGlobalCheckInForm" action="{{ route('attendance.check-in') }}" method="POST">
                        @csrf
                        <input type="hidden" name="latitude" id="attendanceGlobalCheckInLatitude">
                        <input type="hidden" name="longitude" id="attendanceGlobalCheckInLongitude">

                        <button
                            type="button"
                            onclick="submitGlobalAttendance('attendanceGlobalCheckInForm', 'attendanceGlobalCheckInLatitude', 'attendanceGlobalCheckInLongitude')"
                            class="flex h-11 w-full items-center justify-center rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600"
                        >
                            Absen Masuk Sekarang
                        </button>
                    </form>
                @elseif($attendancePopupAction === 'check-out')
                    <form id="attendanceGlobalCheckOutForm" action="{{ route('attendance.check-out') }}" method="POST">
                        @csrf
                        <input type="hidden" name="latitude" id="attendanceGlobalCheckOutLatitude">
                        <input type="hidden" name="longitude" id="attendanceGlobalCheckOutLongitude">

                        <button
                            type="button"
                            onclick="submitGlobalAttendance('attendanceGlobalCheckOutForm', 'attendanceGlobalCheckOutLatitude', 'attendanceGlobalCheckOutLongitude')"
                            class="flex h-11 w-full items-center justify-center rounded-lg bg-gray-800 px-4 py-2 text-sm font-medium text-white hover:bg-gray-900 dark:bg-gray-700 dark:hover:bg-gray-600"
                        >
                            Absen Pulang Sekarang
                        </button>
                    </form>
                @endif

                <button
                    type="button"
                    @click="closeForNow()"
                    class="h-11 w-full rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
                >
                    Tutup Sementara
                </button>

                <a
                    href="{{ route('attendance.index') }}"
                    class="block text-center text-sm font-medium text-brand-500 hover:text-brand-600"
                >
                    Buka halaman Absensi
                </a>
            </div>
        </div>
    </div>
@endif

@if($attendancePopupShouldShow && \Illuminate\Support\Facades\Route::has('attendance.index'))
    <a
        href="{{ route('attendance.index') }}"
        class="fixed bottom-6 right-6 z-[99998] inline-flex items-center gap-2 rounded-full bg-brand-500 px-5 py-3 text-sm font-semibold text-white shadow-lg hover:bg-brand-600 dark:bg-brand-500 dark:hover:bg-brand-600"
        title="Buka Absensi"
    >
        <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3M5 11h14M7 21h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
        <span>Absensi</span>
    </a>
@endif

@if($attendancePopupShouldShow)
    <script>
        if (typeof window.attendanceGlobalPopup !== 'function') {
            window.attendanceGlobalPopup = function () {
                return {
                    open: false,

                    init() {
                        this.open = true;
                    },

                    closeForNow() {
                        this.open = false;
                    }
                }
            }
        }

        if (typeof window.submitGlobalAttendance !== 'function') {
            window.submitGlobalAttendance = function (formId, latitudeInputId, longitudeInputId) {
                const status = document.getElementById('attendanceGlobalPopupStatus');

                if (!navigator.geolocation) {
                    if (status) status.innerText = 'Browser tidak mendukung GPS / geolocation.';
                    return;
                }

                if (status) status.innerText = 'Mengambil lokasi kamu...';

                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        document.getElementById(latitudeInputId).value = position.coords.latitude;
                        document.getElementById(longitudeInputId).value = position.coords.longitude;

                        if (status) status.innerText = 'Lokasi berhasil didapat. Memproses absensi...';

                        document.getElementById(formId).submit();
                    },
                    function(error) {
                        if (status) status.innerText = 'Gagal mengambil lokasi. Pastikan izin lokasi diaktifkan.';
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 15000,
                        maximumAge: 0
                    }
                );
            }
        }
    </script>
@endif