(function ($) {
    'use strict';

    $(function () {
        if (typeof wawpPhoneVerify === 'undefined') {
            return;
        }

        let cooldown = 5;
        let timer = null;
        let isNew = wawpPhoneVerify.is_new === 'true' || wawpPhoneVerify.is_new === true;
        let otpMethod = wawpPhoneVerify.otp_method || 'whatsapp';
        let confirmationResult = null;
        let firebaseLoading = false;
        let pollingInterval = null;

        // ─── REST helper ─────────────────────────────────────────────────
        async function wawpRest(op, data) {
            if (!wawpPhoneVerify.rest_url) {
                // Legacy AJAX fallback (should not be reached in normal operation)
                return $.post(wawpPhoneVerify.ajax, $.extend({
                    security: wawpPhoneVerify.nonce,
                    action: 'wawp_' + op.replace(/-/g, '_')
                }, data || {}));
            }

            const response = await fetch(wawpPhoneVerify.rest_url + '/' + op, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': wawpPhoneVerify.nonce
                },
                body: JSON.stringify(data || {})
            });

            return response.json();
        }

        async function ensureFirebase() {
            if (typeof firebase !== 'undefined' && firebase.auth) {
                if (!window.recaptchaVerifierPhoneBar) await initFirebaseVerifier();
                return true;
            }

            if (firebaseLoading) return new Promise(resolve => {
                const i = setInterval(() => { if (typeof firebase !== 'undefined' && firebase.auth) { clearInterval(i); resolve(true); } }, 100);
            });
            firebaseLoading = true;

            const scripts = [
                'https://www.gstatic.com/firebasejs/9.1.1/firebase-app-compat.js',
                'https://www.gstatic.com/firebasejs/9.1.1/firebase-auth-compat.js'
            ];

            for (const src of scripts) {
                await new Promise(resolve => {
                    const s = document.createElement('script');
                    s.src = src; s.onload = resolve; document.head.appendChild(s);
                });
            }

            await initFirebaseVerifier();
            return true;
        }

        async function initFirebaseVerifier() {
            if (!document.getElementById('wawp-firebase-recaptcha-phonebar')) return;

            const config = wawpPhoneVerify.firebase_config;
            if (!config) { console.error('Firebase config missing'); return; }

            if (!config.apiKey && config.api_key) config.apiKey = config.api_key;
            if (!config.apiKey) { console.error('Firebase API Key missing'); return; }

            let app = null;
            try {
                app = firebase.app('wawp_phonebar_app');
            } catch (e) {
                app = firebase.initializeApp(config, 'wawp_phonebar_app');
            }

            if (!window.recaptchaVerifierPhoneBar) {
                try {
                    window.recaptchaVerifierPhoneBar = new firebase.auth.RecaptchaVerifier('wawp-firebase-recaptcha-phonebar', {
                        'size': 'invisible',
                        'callback': (response) => { }
                    }, app);
                    window.recaptchaVerifierPhoneBar.render();
                } catch (e) { console.warn('Recaptcha init error', e); }
            }
        }

        if (wawpPhoneVerify.firebase_configured && otpMethod === 'firebase') {
            ensureFirebase();
        }

        function startCooldown(btn) {
            btn.prop('disabled', true).addClass('disabled');
            function tick() {
                btn.text(wawpPhoneVerify.resend_text + ' (' + cooldown + 's)');
                if (--cooldown < 0) {
                    clearInterval(timer);
                    btn.prop('disabled', false).removeClass('disabled').text(wawpPhoneVerify.resend_text);
                    cooldown = cooldown <= 0 ? 10 : cooldown * 2;
                }
            }
            tick();
            timer = setInterval(tick, 1000);
        }

        function hideIntl() {
            $('#wawp-new-phone').closest('.iti').addClass('wawp-hide');
            $('#wawp-new-phone').closest('.iti').next('.intl-tel-status').addClass('wawp-hide');
        }

        function showIntl() {
            $('#wawp-new-phone').closest('.iti').removeClass('wawp-hide');
            $('#wawp-new-phone').closest('.iti').next('.intl-tel-status').removeClass('wawp-hide');
        }

        if (!isNew) {
            hideIntl();
        }

        // ─── Update Phone ─────────────────────────────────────────────────
        $('#wawp-save-phone').on('click', async function () {
            try {
                const r = await wawpRest('update-phone', { phone: $('#wawp-new-phone').val() });
                if (r.success) {
                    $('#wawp-phone-display').text(r.data.phone).removeClass('wawp-hide');
                    $('#wawp-new-phone,#wawp-save-phone').addClass('wawp-hide');
                    $('#wawp-bar-text,#wawp-edit-phone,#wawp-send-otp').removeClass('wawp-hide');
                    hideIntl();
                    isNew = false;
                } else {
                    showMsg(r.message || r.data || 'Failed to save phone');
                }
            } catch (e) {
                showMsg('Connection error');
            }
        });

        $('#wawp-edit-phone').on('click', function () {
            $('#wawp-phone-display,#wawp-edit-phone').addClass('wawp-hide');
            $('#wawp-new-phone,#wawp-save-phone').removeClass('wawp-hide');
            $('#wawp-send-otp').addClass('wawp-hide');
            $('#wawp-otp-input,#wawp-confirm-otp').addClass('wawp-hide');
            showIntl();
            $('#wawp-new-phone').focus();
        });

        // ─── Send OTP ─────────────────────────────────────────────────────
        $('#wawp-send-otp').on('click', async function () {
            const b = $(this);
            const originalText = b.text();

            if (otpMethod === 'firebase') {
                b.prop('disabled', true).text('...');
                ensureFirebase().then(async () => {
                    let phone = $('#wawp-new-phone').val() || $('#wawp-phone-display').text();
                    if (!phone.startsWith('+')) phone = '+' + phone;

                    const app = firebase.app('wawp_phonebar_app');
                    app.auth().signInWithPhoneNumber(phone, window.recaptchaVerifierPhoneBar)
                        .then(async (result) => {
                            confirmationResult = result;
                            // Log to REST API
                            await wawpRest('firebase-log', { phone: phone });
                            $('#wawp-otp-input,#wawp-confirm-otp').removeClass('wawp-hide');
                            startCooldown(b);
                        }).catch((error) => {
                            showMsg(error.message);
                            b.prop('disabled', false).text(originalText);
                        });
                });
            } else {
                try {
                    const r = await wawpRest('send');
                    if (r.success) {
                        const authType = r.data.auth_type || 'otp';
                        if (authType === 'list') {
                            b.data('transient', r.data.otp_transient);
                            $('#wawp-otp-input,#wawp-confirm-otp').addClass('wawp-hide');
                            showMsg('Waiting for your approval on WhatsApp...', false);
                            startPolling(r.data.otp_transient);
                        } else {
                            b.data('transient', r.data.otp_transient);
                            $('#wawp-otp-input,#wawp-confirm-otp').removeClass('wawp-hide');
                            showMsg('Please enter the OTP code sent to your WhatsApp.', false);
                        }
                        if (!b.data('sent')) {
                            b.data('sent', 1).text(wawpPhoneVerify.resend_text);
                        }
                        startCooldown(b);
                    } else {
                        showMsg(r.message || r.data || 'Failed to send OTP');
                    }
                } catch (e) {
                    showMsg('Connection error');
                }
            }
        });

        // ─── Polling for list/auth ─────────────────────────────────────────
        function startPolling(transientKey) {
            if (pollingInterval) clearInterval(pollingInterval);
            pollingInterval = setInterval(async () => {
                try {
                    const r = await wawpRest('status', { otp_transient: transientKey });
                    if (r.success && r.data && r.data.verified) {
                        clearInterval(pollingInterval);
                        finishVerification();
                    } else if (r.success && r.data && r.data.status === 'rejected') {
                        clearInterval(pollingInterval);
                        showMsg('Verification was rejected on WhatsApp.', true);
                        $('#wawp-send-otp').prop('disabled', false).removeClass('disabled').text(wawpPhoneVerify.resend_text);
                    }
                } catch (e) { /* ignore polling errors */ }
            }, 1500);
        }

        function showMsg(msg, isError = true) {
            const el = $('#wawp-phone-bar-msg');
            if (el.length) {
                el.text(msg).css('color', isError ? '#d32f2f' : '#2e7d32').removeClass('wawp-hide');
            } else {
                alert(msg);
            }
        }

        // ─── Confirm OTP ──────────────────────────────────────────────────
        $('#wawp-confirm-otp').on('click', async function () {
            const b = $(this);
            const code = $('#wawp-otp-input').val();
            if (!code) return;

            const originalText = b.text();
            b.prop('disabled', true).text('...');
            $('#wawp-phone-bar-msg').addClass('wawp-hide');

            if (confirmationResult) {
                confirmationResult.confirm(code).then((result) => {
                    result.user.getIdToken().then(async idToken => {
                        try {
                            const r = await wawpRest('firebase-token', { idToken: idToken });
                            if (r.success) {
                                finishVerification();
                            } else {
                                showMsg(r.message || r.data || 'Verification failed');
                                b.prop('disabled', false).text(originalText);
                            }
                        } catch (e) {
                            showMsg('Connection error');
                            b.prop('disabled', false).text(originalText);
                        }
                    });
                }).catch(error => {
                    if (error.code === 'auth/invalid-verification-code') {
                        showMsg('OTP code is wrong. Please check and try again.');
                    } else {
                        showMsg(error.message);
                    }
                    b.prop('disabled', false).text(originalText);
                });
            } else {
                try {
                    const r = await wawpRest('verify', { code: code });
                    if (r.success) {
                        finishVerification();
                    } else {
                        showMsg(r.message || r.data || 'Invalid OTP');
                        b.prop('disabled', false).text(originalText);
                    }
                } catch (e) {
                    showMsg('Connection error');
                    b.prop('disabled', false).text(originalText);
                }
            }
        });

        function finishVerification() {
            $('#wawp-phone-bar').addClass('wawp-phone-bar-verified')
                .html('<button id="wawp-bar-close">&times;</button><span class="wawp-verified-text"><i class="ri-shield-check-line"></i> ' + (wawpPhoneVerify.verified_msg || 'Thank you, your number is verified now') + '</span>');

            $('#wawp-bar-close').on('click', function () {
                $('#wawp-phone-bar').slideUp(300);
            });

            setTimeout(function () {
                $('#wawp-phone-bar').slideUp(300);
            }, 10000);

            setTimeout(function () {
                window.location.reload();
            }, 1000);
        }

        // ─── Dismiss Bar ──────────────────────────────────────────────────
        $('#wawp-bar-close').on('click', async function () {
            $('#wawp-phone-bar').fadeOut();
            await wawpRest('dismiss');
        });
    });
})(jQuery);
