<div id="verifiedModal" class="rs-product-make-offer" style="display:none;">
    <div class="rs-product-make-offer-content">
        <button class="rs-product-make-offer-close" id="closeVerified"><i class="fal fa-times"></i></button>
        <h2 class="rs-product-make-offer-title">{{ __('Get Verified ') }}</h2>
        <p>{{ __('Choose verification method') }}</p>

        {{-- Step 0: Verification Method Selection --}}
        <div id="methodStep">
            <button type="button" class="verified-dropdown-item mb-2" id="selectPhoneVerify" data-verify-type="phone" style="width:100%; justify-content:center;">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right:8px;">
                    <path d="M13.3333 11.3333V13.3333C13.3333 13.7015 13.1313 14.0153 12.8252 14.1789C12.6974 14.252 12.5554 14.2947 12.4107 14.3051C12.266 14.3154 12.1235 14.2933 11.9949 14.241L9.66012 13.1707C9.32582 13.0437 8.96305 13 8.6 13H7.46667C5.89733 13 4.46667 11.9867 3.6 10.4L3.33333 9.73333C3.07378 9.27972 2.89932 8.75521 2.82872 8.181C2.75812 7.6068 2.79395 7.01138 2.93333 6.4C3.06667 5.80667 2.96667 5.19333 2.66667 4.66667C2.39003 4.20796 1.9624 3.8937 1.51968 3.81335C1.45428 3.80138 1.39002 3.78419 1.3275 3.762C1.16127 3.71275 1.00688 3.58533 0.916669 3.4C0.668987 2.94433 0.594181 2.37231 0.715691 1.74172C0.8372 1.11114 1.14533 0.47798 1.59333 0H4.6C5.1807 0 5.69483 0.324438 5.96 0.8L6.26667 1.46667C6.58333 2.14667 7.08 2.58667 7.73333 2.77333L8.98667 3.17333C9.16033 3.23057 9.32185 3.33812 9.41917 3.50075C9.5165 3.66337 9.55015 3.86743 9.51333 4.06667L7.87333 7.54667L9.12667 8.85333L12.6067 7.21333C12.8059 7.17651 13.01 7.21016 13.1726 7.30749C13.3352 7.40481 13.4428 7.56634 13.5 7.74L13.9267 9.00667C14.131 9.72037 14.1827 10.5599 14.0205 11.3765C13.8583 12.193 13.5668 12.8803 13.1933 13.3333H13.3267C13.2729 13.0934 13.3333 12.7931 13.3333 12.3333V11.3333Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                {{ __('Verify with Phone') }}
            </button>
            <button type="button" class="verified-dropdown-item" id="selectEmailVerify" data-verify-type="email" style="width:100%; justify-content:center;">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right:8px;">
                    <path d="M2 4L8 8.66667L14 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M2.66667 3.16667H13.3333C14 3.16667 14.3333 3.5 14.3333 4.16667V11.1667C14.3333 11.8333 14 12.1667 13.3333 12.1667H2.66667C2 12.1667 1.66667 11.8333 1.66667 11.1667V4.16667C1.66667 3.5 2 3.16667 2.66667 3.16667Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                {{ __('Verify with Email') }}
            </button>
        </div>

        {{-- Step 1: Contact --}}
        <form id="sendOtpForm">
            @csrf
            <input type="hidden" id="verifyTypeInput" name="verify_type" value="phone">
            <div id="phoneStep" style="display:none;">
                <label>{{ __('Phone or Email') }}</label>
                <input type="text" id="phoneInput" readonly name="contact" placeholder="Enter Phone or Email"
                    value="{{ optional(auth()->user())->email ?? (optional(auth()->user())->phone_no ?? '') }}">
                <button type="button" id="submitPhone">{{ __('Submit') }}</button>
            </div>
        </form>


        {{-- Step 2: OTP --}}
        <div id="otpStep" style="display:none;">
            <label>{{ __('Enter OTP') }}</label>
            <form id="verifyOtpForm">
                <div class="d-flex align-items-center justify-content-between gap-8">
                    @csrf
                    <input type="text" name="otp[]" maxlength="1" class="otp-box text-center" placeholder="--">
                    <input type="text" name="otp[]" maxlength="1" class="otp-box text-center" placeholder="--">
                    <input type="text" name="otp[]" maxlength="1" class="otp-box text-center" placeholder="--">
                    <input type="text" name="otp[]" maxlength="1" class="otp-box text-center" placeholder="--">
                </div>
                <p id="timer" class="text-center fns-16 fnw-400 m-0" data-color="#687387">
                    {{ __('Resend code in 00:59 sec ') }}
                </p>
                <button id="resendOTPBtn" class="d-none" type="button">
                    {{ __('Resend OTP') }}
                </button>
                <input type="hidden" name="email" id="hiddenEmail" value="{{ auth()->user()->email ?? '' }}">
                <input type="hidden" name="phone_no" id="hiddenPhone" value="{{ auth()->user()->phone_no ?? '' }}">
                <button type="submit">{{ __('Get Verified ') }}</button>
            </form>
        </div>
    </div>
</div>

@push('script')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const Toast = Swal.mixin({
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.onmouseenter = Swal.stopTimer;
                    toast.onmouseleave = Swal.resumeTimer;
                }
            });

            const sendOtpForm = document.getElementById('sendOtpForm');
            const submitPhone = document.getElementById('submitPhone');
            const resentOtpBtn = document.getElementById('resendOTPBtn');
            const verifyOtpForm = document.getElementById('verifyOtpForm');
            const phoneInput = document.getElementById('phoneInput');
            const phoneStep = document.getElementById('phoneStep');
            const otpStep = document.getElementById('otpStep');
            const methodStep = document.getElementById('methodStep');
            const closeBtn = document.getElementById('closeVerified');
            const selectPhoneVerify = document.getElementById('selectPhoneVerify');
            const selectEmailVerify = document.getElementById('selectEmailVerify');
            let enteredContact = '';

            // Close button - reset modal to initial state
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    document.getElementById('verifiedModal').style.display = 'none';
                    phoneStep.style.display = 'none';
                    otpStep.style.display = 'none';
                    methodStep.style.display = 'block';
                    document.querySelectorAll('.otp-box').forEach(box => box.value = '');
                });
            }

            // Select verification method
            if (selectPhoneVerify) {
                selectPhoneVerify.addEventListener('click', function() {
                    const contactValue = '{{ auth()->user()->phone_no ?? '' }}';
                    document.getElementById('verifyTypeInput').value = 'phone';
                    phoneInput.value = contactValue;
                    phoneInput.placeholder = '{{ __('Enter Phone Number') }}';
                    phoneInput.type = 'tel';
                    methodStep.style.display = 'none';
                    phoneStep.style.display = 'block';
                });
            }

            if (selectEmailVerify) {
                selectEmailVerify.addEventListener('click', function() {
                    const contactValue = '{{ auth()->user()->email ?? '' }}';
                    document.getElementById('verifyTypeInput').value = 'email';
                    phoneInput.value = contactValue;
                    phoneInput.placeholder = '{{ __('Enter Email Address') }}';
                    phoneInput.type = 'email';
                    methodStep.style.display = 'none';
                    phoneStep.style.display = 'block';
                });
            }

            // Submit phone or email
            if (submitPhone && phoneInput) {
                submitPhone.addEventListener('click', function(e) {
                    e.preventDefault();

                    const contact = phoneInput.value.trim();
                    if (contact === "") {
                        phoneInput.style.border = "1px solid #DD5454";
                        Toast.fire({
                            icon: 'error',
                            title: 'Please enter a valid phone or email.'
                        });
                        return;
                    }
                    enteredContact = contact;
                    phoneInput.style.border = "";

                    // Update hidden fields based on verification type
                    const verifyType = document.getElementById('verifyTypeInput').value;
                    document.getElementById('hiddenEmail').value = verifyType === 'email' ? contact : '{{ auth()->user()->email ?? '' }}';
                    document.getElementById('hiddenPhone').value = verifyType === 'phone' ? contact : '{{ auth()->user()->phone_no ?? '' }}';

                    const token = sendOtpForm.querySelector('input[name="_token"]').value;

                    axios.post("{{ route('user.verify.submit') }}", {
                            contact: contact,
                            _token: token
                        })
                        .then(function(response) {
                            Toast.fire({
                                icon: 'success',
                                title: response.data.success || 'OTP sent successfully!'
                            });
                            phoneStep.style.display = 'none';
                            otpStep.style.display = 'block';
                            window.startCountdown(
                                10); // Call startCountdown from min.js with 10 seconds
                        })
                        .catch(function(error) {
                            const msg = error.response?.data?.errors?.contact?.[0] ||
                                'Something went wrong!';
                            Toast.fire({
                                icon: 'error',
                                title: msg
                            });
                        });
                });
            }

            // Resend OTP
            if (resentOtpBtn) {
                resentOtpBtn.addEventListener('click', function() {
                    const contact = enteredContact;
                    const token = sendOtpForm.querySelector('input[name="_token"]').value;

                    axios.post("{{ route('user.resend.otp') }}", {
                            contact: contact,
                            _token: token,
                        })
                        .then(function(response) {
                            Toast.fire({
                                icon: 'success',
                                title: response.data.success || 'New OTP sent!'
                            });
                            resentOtpBtn.classList.add('d-none');
                            window.startCountdown(
                                10); // Call startCountdown from min.js with 10 seconds
                        })
                        .catch(function(error) {
                            const msg = error.response?.data?.errors?.contact?.[0] ||
                                'Failed to resend OTP';
                            Toast.fire({
                                icon: 'error',
                                title: msg
                            });
                        });
                });
            }

            // Verify OTP
            if (verifyOtpForm) {
                verifyOtpForm.addEventListener('submit', function(e) {
                    e.preventDefault();

                    let otp = [];
                    let allFilled = true;
                    const otpBoxes = document.querySelectorAll('.otp-box');

                    otpBoxes.forEach(box => {
                        if (box.value.trim() === "") {
                            box.style.border = "1px solid #DD5454";
                            allFilled = false;
                        } else {
                            box.style.border = "";
                            otp.push(box.value);
                        }
                    });

                    if (!allFilled) {
                        Toast.fire({
                            icon: 'error',
                            title: 'Please fill all OTP fields.'
                        });
                        return;
                    }

                    const token = verifyOtpForm.querySelector('input[name="_token"]').value;
                    const email = verifyOtpForm.querySelector('input[name="email"]').value;
                    const phone_no = verifyOtpForm.querySelector('input[name="phone_no"]').value;

                    axios.post("{{ route('user.verify.otp.submit') }}", {
                            otp: otp.join(''),
                            contact: enteredContact,
                            email: email,
                            phone_no: phone_no,
                            _token: token
                        })
                        .then(function(response) {
                            Toast.fire({
                                icon: 'success',
                                title: 'OTP verified successfully!'
                            }).then(() => {
                                document.getElementById('verifiedModal').style.display = 'none';
                                location.reload();
                            });
                        })
                        .catch(function(error) {
                            const msg = error.response?.data?.errors?.otp?.[0] ||
                                'Invalid OTP. Please try again.';
                            Toast.fire({
                                icon: 'error',
                                title: msg
                            });
                        });
                });
            }
        });
    </script>
@endpush

<style>
    #resendOTPBtn {
        border: none;
        background-color: white;
        color: var(--tp-red-color);
        font-size: 15px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s ease;
        width: 150px
    }

    #resendOTPBtn:hover {
        border: 1px solid #dd5454;
    }
</style>
