/**
 * BrewmyApp — OTP Login on WooCommerce My Account page
 * Handles the step-based OTP flow: method → send → verify → redirect.
 * Supports two modes:
 *   - "both": OTP form below the password form (prefix: "bma-otp-")
 *   - "otp_only": standalone OTP form replacing password form (prefix: "bma-otp-standalone-")
 */
(function () {
    'use strict';

    if (typeof bmaOtp === 'undefined') return;

    // ── Shared helpers ──

    function show(el) { if (el) el.style.display = ''; }
    function hide(el) { if (el) el.style.display = 'none'; }

    function showMsg(el, text, type) {
        if (!el) return;
        el.textContent = text;
        el.className = 'bma-otp-message bma-otp-' + type;
        show(el);
    }

    function ajax(action, data, onSuccess, onError) {
        var fd = new FormData();
        fd.append('action', action);
        fd.append('nonce', bmaOtp.nonce);
        for (var k in data) {
            if (data.hasOwnProperty(k)) fd.append(k, data[k]);
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', bmaOtp.ajaxUrl, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) return;
            var res;
            try { res = JSON.parse(xhr.responseText); } catch (e) { res = null; }
            if (xhr.status >= 200 && xhr.status < 300 && res && res.success) {
                onSuccess(res.data);
            } else {
                var msg = (res && res.data && res.data.message) ? res.data.message : 'Something went wrong.';
                onError(msg);
            }
        };
        xhr.send(fd);
    }

    /**
     * Initialise an OTP form instance.
     * @param {string} prefix  Element ID prefix, e.g. "bma-otp-" or "bma-otp-standalone-"
     */
    function initOtpForm(prefix) {
        var stepMethod = document.getElementById(prefix + 'step-method');
        var stepSend   = document.getElementById(prefix + 'step-send');
        var stepVerify = document.getElementById(prefix + 'step-verify');

        if (!stepMethod || !stepSend || !stepVerify) return;

        var state = { method: '', identifier: '', cooldown: 0, timer: null };

        // Method step
        var methodBtns = stepMethod.querySelectorAll('.bma-otp-btn');

        // Send step
        var sendLabel  = document.getElementById(prefix + 'send-label');
        var idLabel    = document.getElementById(prefix + 'identifier-label');
        var idInput    = document.getElementById(prefix + 'identifier');
        var sendBtn    = document.getElementById(prefix + 'send-btn');
        var sendMsg    = document.getElementById(prefix + 'send-msg');
        var backMethod = document.getElementById(prefix + 'back-method');

        // Verify step
        var verifyLabel = document.getElementById(prefix + 'verify-label');
        var codeInput   = document.getElementById(prefix + 'code');
        var verifyBtn   = document.getElementById(prefix + 'verify-btn');
        var verifyMsg   = document.getElementById(prefix + 'verify-msg');
        var timerEl     = document.getElementById(prefix + 'timer');
        var resendLink  = document.getElementById(prefix + 'resend-link');
        var backSend    = document.getElementById(prefix + 'back-send');

        function goToStep(step) {
            hide(stepMethod); hide(stepSend); hide(stepVerify);
            show(step);
        }

        function updateTimer() {
            if (timerEl) timerEl.textContent = bmaOtp.i18n.resendIn.replace('%d', state.cooldown);
        }

        function startCooldown() {
            state.cooldown = 60;
            hide(resendLink);
            updateTimer();
            state.timer = setInterval(function () {
                state.cooldown--;
                if (state.cooldown <= 0) {
                    clearInterval(state.timer);
                    state.timer = null;
                    if (timerEl) timerEl.textContent = '';
                    show(resendLink);
                } else {
                    updateTimer();
                }
            }, 1000);
        }

        // ── Step: Choose Method ──
        for (var i = 0; i < methodBtns.length; i++) {
            methodBtns[i].addEventListener('click', function () {
                state.method = this.getAttribute('data-method');
                hide(sendMsg);

                if (state.method === 'email') {
                    if (sendLabel) sendLabel.textContent = bmaOtp.i18n.emailSendDesc;
                    if (idLabel) idLabel.textContent = bmaOtp.i18n.emailLabel;
                    if (idInput) { idInput.type = 'email'; idInput.autocomplete = 'email'; idInput.placeholder = ''; }
                } else {
                    if (sendLabel) sendLabel.textContent = bmaOtp.i18n.whatsappSendDesc;
                    if (idLabel) idLabel.textContent = bmaOtp.i18n.phoneLabel;
                    if (idInput) { idInput.type = 'tel'; idInput.autocomplete = 'tel'; idInput.placeholder = '+91XXXXXXXXXX'; }
                }

                if (idInput) idInput.value = '';
                goToStep(stepSend);
                if (idInput) idInput.focus();
            });
        }

        // ── Step: Send OTP ──
        function sendOtp() {
            var val = idInput ? idInput.value.trim() : '';
            if (!val) { if (idInput) idInput.focus(); return; }

            state.identifier = val;
            if (sendBtn) { sendBtn.disabled = true; sendBtn.textContent = bmaOtp.i18n.sendingOtp; }
            hide(sendMsg);

            ajax(
                'bma_web_otp_request',
                { method: state.method, identifier: val },
                function () {
                    if (sendBtn) { sendBtn.disabled = false; sendBtn.textContent = bmaOtp.i18n.sendOtp; }

                    if (verifyLabel) {
                        verifyLabel.textContent = state.method === 'email'
                            ? bmaOtp.i18n.emailVerifyDesc
                            : bmaOtp.i18n.whatsappVerifyDesc;
                    }
                    if (codeInput) codeInput.value = '';
                    hide(verifyMsg);
                    goToStep(stepVerify);
                    if (codeInput) codeInput.focus();
                    startCooldown();
                },
                function (msg) {
                    if (sendBtn) { sendBtn.disabled = false; sendBtn.textContent = bmaOtp.i18n.sendOtp; }
                    showMsg(sendMsg, msg, 'error');
                }
            );
        }

        if (sendBtn) sendBtn.addEventListener('click', sendOtp);
        if (idInput) idInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); sendOtp(); }
        });
        if (backMethod) backMethod.addEventListener('click', function (e) {
            e.preventDefault();
            goToStep(stepMethod);
        });

        // ── Step: Verify OTP ──
        function verifyOtp() {
            var code = codeInput ? codeInput.value.trim() : '';
            if (!code || code.length < 6) { if (codeInput) codeInput.focus(); return; }

            if (verifyBtn) { verifyBtn.disabled = true; verifyBtn.textContent = bmaOtp.i18n.verifying; }
            hide(verifyMsg);

            ajax(
                'bma_web_otp_verify',
                { method: state.method, identifier: state.identifier, otp: code },
                function (data) {
                    showMsg(verifyMsg, data.message, 'success');
                    setTimeout(function () {
                        window.location.href = data.redirect || window.location.href;
                    }, 800);
                },
                function (msg) {
                    if (verifyBtn) { verifyBtn.disabled = false; verifyBtn.textContent = bmaOtp.i18n.verifyLogin; }
                    showMsg(verifyMsg, msg, 'error');
                    if (codeInput) { codeInput.value = ''; codeInput.focus(); }
                }
            );
        }

        if (verifyBtn) verifyBtn.addEventListener('click', verifyOtp);
        if (codeInput) codeInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); verifyOtp(); }
        });
        if (resendLink) resendLink.addEventListener('click', function (e) {
            e.preventDefault();
            sendOtp();
        });
        if (backSend) backSend.addEventListener('click', function (e) {
            e.preventDefault();
            if (state.timer) { clearInterval(state.timer); state.timer = null; }
            goToStep(stepSend);
            if (idInput) idInput.focus();
        });
    }

    // Initialise whichever form(s) are present on the page.
    // "both" mode renders #bma-otp-step-method (inline below password form).
    // "otp_only" mode renders #bma-otp-standalone-step-method (standalone at top).
    initOtpForm('bma-otp-');
    initOtpForm('bma-otp-standalone-');
})();
