<x-layouts.app>
    @sortableWidgets($headerInstance, 'header')

    <!-- step : auth / register / enter_password / set_password / one_time_password / reset_password -->
    <div x-data="{
                    step: $wire.entangle('step').live,
                    showPasswordField: true,
                    passwordScore: 0,
                    password: '',
                    checkStrength: function() {
                        if (!this.password) return this.passwordScore = 0;
                        this.passwordScore = zxcvbn(this.password).score + 1;
                    }
                }" class="relative min-h-screen pt-10 overflow-visible flex justify-center items-center">

        <style>
            input::-webkit-outer-spin-button,
            input::-webkit-inner-spin-button {
                -webkit-appearance: none;
                margin: 0;
            }

            /* Firefox */
            input[type=number] {
                -moz-appearance: textfield;
            }

            input:-webkit-autofill,
            input:-webkit-autofill:hover,
            input:-webkit-autofill:focus,
            input:-webkit-autofill:active{
                -webkit-box-shadow: 0 0 0 30px #37383e inset !important;
            }

            /*Change text in autofill textbox*/
            input:-webkit-autofill{
                -webkit-text-fill-color: #cbd5e1 !important;
            }

            .cursor-wait {
                cursor:wait;
            }
            input.error {
                border-color: red;
            }

            .error {
                color:red;
            }

            .error-box {
                background-color: #d84c4c;
                padding: 10px;
                border-radius: 5px;
                color: white;
            }

            .loading {
                background-color: rgba(10, 18, 29, 0.8);
                left: 0;
            }

            .loader {
                left:0;
                width: 48px;
                height: 48px;
                border: 5px solid #28c1f5;
                border-bottom-color: transparent;
                border-radius: 50%;
                display: inline-block;
                box-sizing: border-box;
                animation: rotation 1s linear infinite;
                margin: auto;
            }

            @keyframes rotation {
                0% {
                    transform: rotate(0deg);
                }
                100% {
                    transform: rotate(360deg);
                }
            }
        </style>

        <!-- for password difficulty -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.4.2/zxcvbn.js"></script>

        <!-- form -->
        <div
            class="w-full sm:max-w-xl rounded-2xl m-10 p-5 z-10 shadow-[0_4px_30px_rgba(0,0,0,0.1)] backdrop-blur [-webkit-backdrop-filter:_blur(8px)]  bg-[#222327]">
            <form x-show="step == 'verify_mobile'" x-cloak class="text-slate-200" wire:submit="validateCodeWithMobile">
                <div class="flex flex-col gap-5" id="otp-form_for_reset">
                    <button type="button"
                            class="hover:bg-white/5 text-slate-300 rounded-lg py-2 px-4 text-center font-medium cursor-pointer transition-all flex items-center justify-center gap-2">
                        <p>{{$this->mobile}}</p>
                    </button>

                    @if (session()->has('code_error'))
                        <div class="error-box">
                            <span>{{ session('code_error') }}</span>
                        </div>
                    @endif

                    <div>
                        <label class="block text-sm font-normal">کد تایید ارسال شده به شماره همراه خود را در کادر زیر وارد کنید:</label>
                        <div class="mt-3 grid tm-grid-cols-6 items-center justify-center gap-2 p-4 relative" dir="ltr">
                            <input type="number" wire:model="code.0"
                                   class="pass_box size-12 appearance-none block text-center text-lg font-semibold bg-transparent text-slate-300 rounded-lg py-3 px-4 border border-slate-600 transition-colors duration-300 focus:outline-none focus:bg-transparent focus:border-brand-2"
                                   pattern="\d*" maxlength="1" />
                            <input type="number" wire:model="code.1"
                                   class="pass_box size-12 appearance-none block text-center text-lg font-semibold bg-transparent text-slate-300 rounded-lg py-3 px-4 border border-slate-600 transition-colors duration-300 focus:outline-none focus:bg-transparent focus:border-brand-2"
                                   maxlength="1" />
                            <input type="number" wire:model="code.2"
                                   class="pass_box size-12 appearance-none block text-center text-lg font-semibold bg-transparent text-slate-300 rounded-lg py-3 px-4 border border-slate-600 transition-colors duration-300 focus:outline-none focus:bg-transparent focus:border-brand-2"
                                   maxlength="1" />
                            <input type="number" wire:model="code.3"
                                   class="pass_box size-12 appearance-none block text-center text-lg font-semibold bg-transparent text-slate-300 rounded-lg py-3 px-4 border border-slate-600 transition-colors duration-300 focus:outline-none focus:bg-transparent focus:border-brand-2"
                                   maxlength="1" />
                            <input type="number" wire:model="code.4"
                                   class="pass_box size-12 appearance-none block text-center text-lg font-semibold bg-transparent text-slate-300 rounded-lg py-3 px-4 border border-slate-600 transition-colors duration-300 focus:outline-none focus:bg-transparent focus:border-brand-2"
                                   maxlength="1" />
                            <input type="number" wire:model="code.5"
                                   class="pass_box size-12 appearance-none block text-center text-lg font-semibold bg-transparent text-slate-300 rounded-lg py-3 px-4 border border-slate-600 transition-colors duration-300 focus:outline-none focus:bg-transparent focus:border-brand-2"
                                   maxlength="1" />
                        </div>
                    </div>

                    <div class="flex justify-end w-full">
                        <button type="button" @click="resendMobile()" x-data="timer(120)"
                                :class="(remaining <= 0) ? 'hover:bg-white/10 bg-white/5' : 'cursor-wait'"
                                class=" text-slate-200 rounded-lg py-2 px-4 text-center font-normal transition-all flex items-center gap-2 w-fit ">
                            <div class="flex gap-1 text-sm">
                                <p>دریافت مجدد</p>
                                <span x-init="init();" class="flex flex-row-reverse gap-[1px]">
                                        )<p x-text="timer"></p>(
                                    </span>
                            </div>
                        </button>
                    </div>

                    <button type="submit" id="otp_submit_btn_for_reset"
                            class="w-full bg-blue-500 text-white rounded-lg py-2 px-4 text-center font-semibold disabled:bg-slate-800 disabled:text-slate-500">تأیید</button>
                </div>
                <div x-cloak wire:loading class="loading absolute right-0 left-0 top-0 bottom-0 rounded-2xl"><span class="loader absolute right-0 left-0 top-0 bottom-0"></span></div>
            </form>
        </div>

        <script>
            // otp form for reset
            document.addEventListener('DOMContentLoaded', () => {
                const form = document.getElementById('otp-form_for_reset')
                const inputs = [...form.querySelectorAll('.pass_box')]
                const submit = form.querySelector('#otp_submit_btn_for_reset')

                const handleKeyDown = (e) => {
                    // if (
                    //     !/^[0-9]{1}$/.test(e.key) &&
                    //     e.key !== 'Backspace' &&
                    //     e.key !== 'Delete' &&
                    //     e.key !== 'Tab' &&
                    //     !e.metaKey
                    // ) {
                    //     e.preventDefault()
                    // }
                    if(e.target.length===2 && event.keyCode!==8) return false;
                    if (e.key === 'Delete' || e.key === 'Backspace') {
                        const index = inputs.indexOf(e.target);
                        if (index > 0) {
                            inputs[index].value = '';
                            inputs[index - 1].focus();
                        }
                    }
                }

                const handleInput = (e) => {
                    const {
                        target
                    } = e
                    const index = inputs.indexOf(target)
                    if (target.value) {
                        if (index < inputs.length - 1) {
                            inputs[index + 1].focus()
                        } else {
                            Livewire.dispatch('validate-code');
                            //submit.focus()
                            // form.submit()
                        }
                    }
                }

                const handleFocus = (e) => {
                    // e.target.select()
                }

                const handlePaste = (e) => {
                    e.preventDefault()
                    const text = e.clipboardData.getData('text')
                    if (!new RegExp(`^ [0 - 9]{ ${inputs.length}$`).test(text)) {
                        return
                    }
                    const digits = text.split('')
                    inputs.forEach((input, index) => input.value = digits[index])
                    submit.focus()
                }

                inputs.forEach((input) => {
                    input.addEventListener('input', handleInput)
                    input.addEventListener('keydown', handleKeyDown)
                    input.addEventListener('focus', handleFocus)
                    input.addEventListener('paste', handlePaste)
                })
            });
        </script>
        <script>
            function timer(expiry) {
                return {
                    remaining: expiry,
                    timerOn: true,
                    timer: '',
                    resend() {
                        if(!this.timerOn) {
                            this.timerOn = true;
                            this.remaining = 120;
                            this.$wire.resendCode();
                        }
                    },
                    resendMobile() {
                        if(!this.timerOn) {
                            this.timerOn = true;
                            this.remaining = 120;
                            this.$wire.resendCodeWithMobile();
                        }
                    },
                    init() {
                        this.setRemaining();  // نمایش اولیه تایمر
                        this.interval = setInterval(() => {
                            if (this.timerOn && this.remaining >= 0) {
                                this.setRemaining();
                                this.remaining -= 1;
                            } else {
                                clearInterval(this.interval);  // متوقف کردن تایمر وقتی زمان به پایان می‌رسد
                            }
                        }, 1000);
                    },
                    setRemaining() {
                        var m = Math.floor(this.remaining / 60);
                        var s = this.remaining % 60;

                        m = m < 10 ? '0' + m : m;
                        s = s < 10 ? '0' + s : s;
                        this.timer = m + ':' + s;

                        if (this.remaining <= 0) {
                            this.timerOn = false;
                        }
                    }
                };
            }
        </script>
    </div>
    @sortableWidgets($footerInstance, 'footer')
</x-layouts.app>

