<x-slot:title>Verify Otp</x-slot:title>

<!-- Form Section -->
<div class="px-8 space-y-6">
    <x-auth-header :title="__('Verify OTP')" :description="__('Enter the 6-digit code sent to your email')" />

    @php
        $email = session('auth_email');
        function maskEmail($email)
        {
            if (!$email || !str_contains($email, '@')) {
                return $email;
            }
            [$name, $domain] = explode('@', $email);
            $nameMasked = substr($name, 0, 1) . str_repeat('*', max(strlen($name) - 1, 1));
            $domainMasked = substr($domain, 0, 1) . str_repeat('*', max(strlen($domain) - 4, 1)) . substr($domain, -4);
            return $nameMasked . '@' . $domainMasked;
        }
    @endphp
    <div class="text-gray-800 dark:text-gray-200 text-center font-semibold mb-4">{{ maskEmail($email) }}
    </div>

    <form wire:submit.prevent="verifyOtp" class="flex flex-col gap-6" x-cloak x-data="{
        handleInput(e, i) {
                const val = e.target.value;
                if (!/^\d$/.test(val)) {
                    e.target.value = '';
                    return;
                }
                $wire.set('otp.' + i, val);
                if (i < 5) $refs['otp' + (i + 1)].focus();
                else if (i === 5) $el.requestSubmit();
            },
            handleBackspace(e, i) {
                if (e.key === 'Backspace' && e.target.value === '' && i > 0) {
                    $refs['otp' + (i - 1)].focus();
                }
            },
            handleArrowKeys(e, i) {
                if (e.key === 'ArrowLeft' && i > 0) $refs['otp' + (i - 1)].focus();
                if (e.key === 'ArrowRight' && i < 5) $refs['otp' + (i + 1)].focus();
            },
            handlePaste(e) {
                e.preventDefault();
                const paste = e.clipboardData.getData('text').trim();
                if (/^\d{6}$/.test(paste)) {
                    paste.split('').forEach((char, j) => {
                        this.$refs['otp' + j].value = char;
                        this.$wire.set('otp.' + j, char);
                    });
                    $refs['otp5'].focus();
                }
            }
    }"
        @paste.prevent="handlePaste($event)" x-init="$nextTick(() => { $refs.otp0.focus(); })">

        <div class="grid grid-cols-6 gap-3 justify-center">
            @for ($i = 0; $i < 6; $i++)
                <input x-ref="otp{{ $i }}" id="otp-{{ $i }}"
                    class="otp-input w-12 h-12 md:w-14 md:h-14 text-center text-lg font-semibold 
                           border rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none
                           @error('otp.' . $i) border-red-500 @else border-gray-300 @enderror"
                    maxlength="1" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]*" type="text"
                    wire:model.defer="otp.{{ $i }}" @input="handleInput($event, {{ $i }})"
                    @keydown="handleBackspace($event, {{ $i }}); handleArrowKeys($event, {{ $i }})" />
            @endfor
        </div>

        @if (
            $errors->has('otp') ||
                $errors->has('otp.0') ||
                $errors->has('otp.1') ||
                $errors->has('otp.2') ||
                $errors->has('otp.3') ||
                $errors->has('otp.4') ||
                $errors->has('otp.5')
        )
            <span class="text-red-500 text-sm text-center block mt-2">
                {{ $errors->first('otp') ?: 'Please enter your 6-digit OTP code.' }}
            </span>
        @endif

        @if (session('otp_action') === 'login')
            <div class="flex items-center justify-start gap-3 mt-2">
                <input id="trustDevice" type="checkbox" wire:model="trustDevice"
                    class="h-5 w-5 text-[#0E4D92] dark:text-[#F78F20] border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-[#0E4D92] dark:focus:ring-[#F78F20] transition">
                <label for="trustDevice"
                    class="text-sm text-gray-700 dark:text-gray-300 font-medium cursor-pointer select-none">
                    Trust this device for future logins
                </label>
            </div>
        @endif

        <flux:button type="submit" variant="primary" color="emerald" class="mt-4">Verify OTP</flux:button>

        <x-button type="button" wire:click="cancelVerification" class="bg-red-600 text-white w-full">
            Cancel & Restart
        </x-button>

        <!-- Countdown + Resend -->
        <div x-cloak x-data="{
            expiresIn: @entangle('expiresIn'),
            resendCooldown: @entangle('resendCooldown'),
            canResend: @entangle('canResend'),
            loading: false,
            startCountdown() {
                setInterval(() => {
                    if (this.expiresIn > 0) this.expiresIn--;
                    if (this.resendCooldown > 0) this.resendCooldown--;
                    this.canResend = this.resendCooldown <= 0;
                }, 1000);
            },
            resendOtp() {
                if (!this.canResend || this.loading) return;
                this.loading = true;
                this.$wire.resendOtp()
                    .then(() => { this.loading = false; })
                    .catch(() => { this.loading = false; });
            }
        }" x-init="startCountdown()" class="text-center mt-6 space-y-3">
            <p class="text-sm text-gray-700 dark:text-gray-300">
                ⏳ Time remaining:
                <span class="font-semibold text-blue-600"
                    x-text="new Date(expiresIn * 1000).toISOString().substr(14,5)"></span>
            </p>

            <div class="relative h-2 bg-gray-200 rounded-full overflow-hidden">
                <div class="bg-blue-500 h-full transition-all duration-500 ease-out"
                    :style="`width: ${Math.max(0, Math.min(100, (expiresIn / 600) * 100))}%`"></div>
            </div>

            <div class="flex justify-center items-center gap-2 text-sm">
                <span>Didn’t receive it?</span>
                <button type="button" :disabled="!canResend || loading" @click="resendOtp()"
                    class="underline disabled:opacity-50 text-blue-600 dark:text-yellow-400 flex items-center justify-center gap-2">
                    <template x-if="!loading">
                        <span>Re-send OTP</span>
                    </template>
                    <template x-if="loading">
                        <span class="flex items-center gap-2">
                            <svg class="w-4 h-4 animate-spin text-blue-600 dark:text-yellow-400"
                                xmlns="http://www.w3.org/2000/svg" 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-8v4a4 4 0 00-4 4H4z">
                                </path>
                            </svg>
                            Sending...
                        </span>
                    </template>
                </button>
            </div>
        </div>

    </form>

    <script>
        document.addEventListener('livewire:initialized', () => {
            Livewire.on('focusFirstInvalidOtp', () => {
                // Wait a tiny bit to let Livewire finish updating DOM
                setTimeout(() => {
                    const firstInvalid = document.querySelector('.otp-input.border-red-500');

                    if (firstInvalid) {
                        firstInvalid.focus();
                        // Optional: smooth scroll for mobile users
                        firstInvalid.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });
                    }
                }, 150); // slightly longer delay helps after Livewire validation
            });
        });
    </script>

</div>
