(function () {
    'use strict';

    var wrap = document.getElementById('securwp-2fa-profile');
    if (!wrap) return;

    var nonce   = wrap.dataset.nonce;
    var apiRoot = wrap.dataset.apiRoot;

    // Row references from server-rendered HTML.
    var statusRow  = document.getElementById('sp2fa-status-row');
    var actionsRow = document.getElementById('sp2fa-actions-row');
    var setupRow   = document.getElementById('sp2fa-setup-row');
    var confirmRow = document.getElementById('sp2fa-confirm-row');
    var codesRow   = document.getElementById('sp2fa-codes-row');
    var regenRow   = document.getElementById('sp2fa-regen-row');
    var disableRow = document.getElementById('sp2fa-disable-row');

    /* ── API helper ─────────────────────────────────────────────── */

    function api(method, endpoint, body) {
        var opts = {
            method: method,
            headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' },
        };
        if (body) opts.body = JSON.stringify(body);
        return fetch(apiRoot + 'securwp/v1' + endpoint, opts).then(function (r) {
            if (!r.ok) return r.json().then(function (d) { throw d; });
            return r.json();
        });
    }

    /* ── DOM helpers ─────────────────────────────────────────────── */

    function show(el) { if (el) el.style.display = ''; }
    function hide(el) { if (el) el.style.display = 'none'; }
    function esc(s) {
        var d = document.createElement('div');
        d.appendChild(document.createTextNode(s));
        return d.innerHTML;
    }
    function setMsg(id, text, type) {
        var el = document.getElementById(id);
        if (!el) return;
        el.textContent = text;
        el.className = 'sp2fa-msg ' + (type || '');
        show(el);
    }
    function hideMsg(id) {
        var el = document.getElementById(id);
        if (!el) return;
        el.textContent = '';
        hide(el);
    }
    function getApiMessage(err, fallback) {
        if (err && typeof err.message === 'string' && err.message) {
            return err.message;
        }
        return fallback;
    }
    function updateRecoveryCount(count) {
        if (!statusRow || !count) return;

        var label = count === 1 ? '1 recovery code remaining' : count + ' recovery codes remaining';
        var countEl = statusRow.querySelector('.sp2fa-recovery-count');
        if (countEl) {
            countEl.textContent = label;
            return;
        }

        var methodLabel = statusRow.querySelector('.sp2fa-method-label');
        var td = statusRow.querySelector('td');
        if (!td) return;

        countEl = document.createElement('span');
        countEl.className = 'sp2fa-recovery-count';
        countEl.textContent = label;

        if (methodLabel && methodLabel.nextSibling) {
            td.insertBefore(countEl, methodLabel.nextSibling);
        } else {
            td.appendChild(countEl);
        }
    }

    /* ── Format secret key in 4-char groups ──────────────────────── */

    function formatSecret(secret) {
        return secret.replace(/(.{4})/g, '$1 ').trim();
    }

    /* ── Recovery codes block (reusable) ─────────────────────────── */

    function renderRecoveryCodes(codes, isNew) {
        var title = isNew ? 'New Recovery Codes' : 'Save Your Recovery Codes';
        var h = '';
        h += '<div class="sp2fa-card sp2fa-card-warn">';
        h += '<div class="sp2fa-card-header">';
        h += '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" style="flex-shrink:0;"><path d="M10 2L1.5 17h17L10 2z" stroke="#92400e" stroke-width="1.5" fill="#fef3c7"/><path d="M10 8v3M10 13.5v.5" stroke="#92400e" stroke-width="1.5" stroke-linecap="round"/></svg>';
        h += '<strong>' + esc(title) + '</strong>';
        h += '</div>';
        h += '<p class="sp2fa-card-desc">Store these codes in a safe place. Each code can only be used once.</p>';
        h += '<div class="sp2fa-codes-grid">';
        codes.forEach(function (c) {
            h += '<code class="sp2fa-code-item">' + esc(c) + '</code>';
        });
        h += '</div>';
        h += '<button type="button" class="button sp2fa-copy-codes" data-codes="' + esc(codes.join('\n')) + '">Copy codes</button>';
        h += '</div>';
        return h;
    }

    /* ================================================================
       SETUP FLOW
       ================================================================ */

    var btnSetup  = document.getElementById('sp2fa-btn-setup');
    var btnTotp   = document.getElementById('sp2fa-choose-totp');
    var btnEmail  = document.getElementById('sp2fa-choose-email');
    var btnCancel = document.getElementById('sp2fa-btn-cancel');

    if (btnSetup) {
        btnSetup.addEventListener('click', function () {
            hide(actionsRow);
            show(setupRow);
            hideMsg('sp2fa-setup-msg');
            var setupPw = document.getElementById('sp2fa-setup-pw');
            if (setupPw) setupPw.focus();
        });
    }

    if (btnCancel) {
        btnCancel.addEventListener('click', function () {
            hide(setupRow); hide(confirmRow); hide(codesRow);
            hideMsg('sp2fa-setup-msg');
            var setupPw = document.getElementById('sp2fa-setup-pw');
            if (setupPw) setupPw.value = '';
            show(actionsRow);
        });
    }

    function startSetup(method) {
        var setupPwInput = document.getElementById('sp2fa-setup-pw');
        var setupPassword = setupPwInput ? setupPwInput.value : '';
        if (!setupPassword) {
            setMsg('sp2fa-setup-msg', 'Please enter your password to continue.', 'error');
            return;
        }

        hideMsg('sp2fa-setup-msg');
        hide(setupRow);
        show(confirmRow);

        var content = document.getElementById('sp2fa-confirm-content');
        content.innerHTML = '<div class="sp2fa-loading"><span class="spinner is-active" style="float:none;margin:0 8px 0 0;"></span>Preparing setup...</div>';

        api('POST', '/2fa/setup', { method: method, password: setupPassword }).then(function (data) {
            if (setupPwInput) setupPwInput.value = '';
            var h = '';

            if (method === 'totp' && data.secret) {
                /* ── TOTP: QR code + manual key ───────────────────── */
                h += '<div class="sp2fa-setup-totp">';

                h += '<p class="sp2fa-step-label">Step 1: Scan with your authenticator app</p>';
                h += '<p class="sp2fa-step-desc">Open Google Authenticator, Authy, 1Password, or any TOTP app and scan this QR code:</p>';

                h += '<div class="sp2fa-qr-wrapper">';
                if (data.qr_svg) {
                    h += '<img src="' + data.qr_svg + '" alt="QR Code" width="200" height="200" class="sp2fa-qr-img" />';
                }
                h += '</div>';

                h += '<details class="sp2fa-manual-toggle">';
                h += '<summary>Can\'t scan? Enter key manually</summary>';
                h += '<div class="sp2fa-manual-key">';
                h += '<code id="sp2fa-secret-display">' + esc(formatSecret(data.secret)) + '</code>';
                h += '<button type="button" class="sp2fa-copy-btn" id="sp2fa-copy-secret" title="Copy to clipboard">';
                h += '<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><rect x="5" y="5" width="9" height="9" rx="1.5" stroke="currentColor" stroke-width="1.3"/><path d="M3.5 10.5h-1a1 1 0 01-1-1v-7a1 1 0 011-1h7a1 1 0 011 1v1" stroke="currentColor" stroke-width="1.3"/></svg>';
                h += '</button>';
                h += '</div>';
                h += '<p class="description">Enter this key in your authenticator app. Spaces are for readability only.</p>';
                h += '</details>';

                h += '<div class="sp2fa-divider"></div>';

                h += '<p class="sp2fa-step-label">Step 2: Verify your setup</p>';
                h += '<div class="sp2fa-verify-input">';
                h += '<label for="sp2fa-code">Verification Code</label>';
                h += '<input type="text" id="sp2fa-code" maxlength="6" size="8" inputmode="numeric" pattern="[0-9]{6}" autocomplete="one-time-code" placeholder="000000" class="regular-text" />';
                h += '<p class="description">Enter the 6-digit code shown in your authenticator app.</p>';
                h += '</div>';

                h += '</div>';

            } else {
                /* ── Email: show loading, then send OTP ──────────── */
                h += '<div class="sp2fa-setup-email">';
                h += '<div id="sp2fa-email-status" class="sp2fa-card sp2fa-card-info">';
                h += '<div class="sp2fa-card-header">';
                h += '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" style="flex-shrink:0;"><rect x="2" y="4" width="16" height="12" rx="2" stroke="#1e40af" stroke-width="1.5" fill="#dbeafe"/><path d="M2 6l8 5 8-5" stroke="#1e40af" stroke-width="1.5"/></svg>';
                h += '<strong>Sending verification code...</strong>';
                h += '</div>';
                h += '<p class="sp2fa-card-desc">We are sending a 6-digit code to your email address.</p>';
                h += '</div>';
                h += '<div id="sp2fa-email-form" style="display:none;">';
                h += '<div class="sp2fa-verify-input">';
                h += '<label for="sp2fa-code">Email Verification Code</label>';
                h += '<input type="text" id="sp2fa-code" maxlength="6" size="8" inputmode="numeric" pattern="[0-9]{6}" autocomplete="one-time-code" placeholder="000000" class="regular-text" />';
                h += '<p class="description">Enter the 6-digit code from the email we sent.</p>';
                h += '<p style="margin-top:6px;"><a href="#" id="sp2fa-resend" class="sp2fa-link-subtle">Resend code</a></p>';
                h += '</div>';
                h += '</div>';
                h += '</div>';
            }

            h += '<div id="sp2fa-confirm-msg" class="sp2fa-msg" style="display:none;"></div>';
            h += '<div class="sp2fa-actions-bar">';
            if (method === 'email') {
                h += '<button type="button" class="button button-primary" id="sp2fa-btn-verify" style="display:none;">Verify &amp; Activate</button>';
            } else {
                h += '<button type="button" class="button button-primary" id="sp2fa-btn-verify">Verify &amp; Activate</button>';
            }
            h += '<button type="button" class="button" id="sp2fa-btn-back">Cancel</button>';
            h += '</div>';

            content.innerHTML = h;

            /* Email method: send OTP and show/hide form based on result */
            var emailForm = document.getElementById('sp2fa-email-form');
            var verifyBtn = document.getElementById('sp2fa-btn-verify');
            if (emailForm) {
                api('POST', '/2fa/send-email-otp', { context: 'setup' }).then(function () {
                    var banner = document.getElementById('sp2fa-email-status');
                    if (banner) {
                        banner.className = 'sp2fa-card sp2fa-card-info';
                        banner.innerHTML = '<div class="sp2fa-card-header">'
                            + '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" style="flex-shrink:0;"><rect x="2" y="4" width="16" height="12" rx="2" stroke="#1e40af" stroke-width="1.5" fill="#dbeafe"/><path d="M2 6l8 5 8-5" stroke="#1e40af" stroke-width="1.5"/></svg>'
                            + '<strong>Verification code sent</strong>'
                            + '</div>'
                            + '<p class="sp2fa-card-desc">We sent a 6-digit code to your email address. It expires in 10 minutes.</p>';
                    }
                    show(emailForm);
                    if (verifyBtn) verifyBtn.style.display = '';
                    var ci = document.getElementById('sp2fa-code');
                    if (ci) ci.focus();
                }).catch(function (err) {
                    var banner = document.getElementById('sp2fa-email-status');
                    if (banner) {
                        var msg = (err && err.message) ? err.message : 'Email delivery failed. Please check your site\'s email configuration (SMTP settings) and try again.';
                        banner.className = 'sp2fa-card sp2fa-card-error';
                        banner.innerHTML = '<div class="sp2fa-card-header">'
                            + '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" style="flex-shrink:0;"><circle cx="10" cy="10" r="8" stroke="#dc2626" stroke-width="1.5" fill="#fef2f2"/><path d="M10 6v5M10 13.5v.5" stroke="#dc2626" stroke-width="1.5" stroke-linecap="round"/></svg>'
                            + '<strong>Email delivery failed</strong>'
                            + '</div>'
                            + '<p class="sp2fa-card-desc">' + esc(msg) + '</p>';
                    }
                    if (verifyBtn) verifyBtn.style.display = 'none';
                });
            }

            /* Focus code input (TOTP) */
            var codeInput = document.getElementById('sp2fa-code');
            if (codeInput && !emailForm) codeInput.focus();

            /* Copy secret button */
            var copyBtn = document.getElementById('sp2fa-copy-secret');
            if (copyBtn) {
                copyBtn.addEventListener('click', function () {
                    navigator.clipboard.writeText(data.secret).then(function () {
                        copyBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 8.5l3 3 7-7" stroke="#059669" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
                        setTimeout(function () {
                            copyBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><rect x="5" y="5" width="9" height="9" rx="1.5" stroke="currentColor" stroke-width="1.3"/><path d="M3.5 10.5h-1a1 1 0 01-1-1v-7a1 1 0 011-1h7a1 1 0 011 1v1" stroke="currentColor" stroke-width="1.3"/></svg>';
                        }, 2000);
                    });
                });
            }

            /* Resend link (email only) */
            var resendLink = document.getElementById('sp2fa-resend');
            if (resendLink) {
                resendLink.addEventListener('click', function (e) {
                    e.preventDefault();
                    resendLink.textContent = 'Sending...';
                    api('POST', '/2fa/send-email-otp', { context: 'setup' }).then(function () {
                        setMsg('sp2fa-confirm-msg', 'A new verification code has been sent to your email.', 'success');
                        resendLink.textContent = 'Resend code';
                    }).catch(function (err) {
                        var msg = (err && err.message) ? err.message : 'Email delivery failed. Please check your site\'s email configuration.';
                        setMsg('sp2fa-confirm-msg', msg, 'error');
                        resendLink.textContent = 'Resend code';
                    });
                });
            }

            /* Verify button */
            document.getElementById('sp2fa-btn-verify').addEventListener('click', function () {
                var code = document.getElementById('sp2fa-code').value.trim();
                if (!code || code.length !== 6) {
                    setMsg('sp2fa-confirm-msg', 'Please enter a valid 6-digit code.', 'error');
                    return;
                }
                this.disabled = true;
                this.textContent = 'Verifying...';
                api('POST', '/2fa/confirm', { code: code }).then(function () {
                    hide(confirmRow);
                    show(codesRow);
                    var codesContent = document.getElementById('sp2fa-codes-content');
                    var ch = '';
                    ch += '<div class="sp2fa-success-banner">';
                    ch += '<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" fill="#d1fae5" stroke="#059669" stroke-width="1.5"/><path d="M8 12.5l2.5 2.5 5-5" stroke="#059669" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
                    ch += '<div>';
                    ch += '<strong>Two-factor authentication enabled</strong>';
                    ch += '<p>Your account is now protected with an additional layer of security.</p>';
                    ch += '</div>';
                    ch += '</div>';
                    if (data.recovery_codes && data.recovery_codes.length) {
                        ch += renderRecoveryCodes(data.recovery_codes, false);
                    }
                    ch += '<div class="sp2fa-actions-bar"><button type="button" class="button button-primary" id="sp2fa-btn-done">Done</button></div>';
                    codesContent.innerHTML = ch;

                    bindCopyCodes();
                    document.getElementById('sp2fa-btn-done').addEventListener('click', function () {
                        location.reload();
                    });
                }).catch(function (err) {
                    setMsg('sp2fa-confirm-msg', getApiMessage(err, 'Invalid code. Please try again.'), 'error');
                    var btn = document.getElementById('sp2fa-btn-verify');
                    btn.disabled = false;
                    btn.textContent = 'Verify & Activate';
                });
            });

            /* Cancel */
            document.getElementById('sp2fa-btn-back').addEventListener('click', function () {
                hide(confirmRow);
                show(actionsRow);
            });

        }).catch(function (err) {
            hide(confirmRow);
            show(setupRow);
            setMsg('sp2fa-setup-msg', getApiMessage(err, 'Failed to start two-factor setup.'), 'error');
        });
    }

    if (btnTotp) btnTotp.addEventListener('click', function () { startSetup('totp'); });
    if (btnEmail) btnEmail.addEventListener('click', function () { startSetup('email'); });

    /* ================================================================
       DISABLE 2FA
       ================================================================ */

    var btnShowDisable = document.getElementById('sp2fa-btn-show-disable');
    var btnDisable     = document.getElementById('sp2fa-btn-disable');
    var btnCancelDis   = document.getElementById('sp2fa-btn-cancel-disable');

    if (btnShowDisable) {
        btnShowDisable.addEventListener('click', function () {
            hide(regenRow);
            hide(actionsRow);
            show(disableRow);
            var pw = document.getElementById('sp2fa-disable-pw');
            if (pw) pw.focus();
        });
    }
    if (btnCancelDis) {
        btnCancelDis.addEventListener('click', function () {
            hideMsg('sp2fa-disable-msg');
            hide(disableRow);
            show(actionsRow);
        });
    }
    if (btnDisable) {
        btnDisable.addEventListener('click', function () {
            var pw = document.getElementById('sp2fa-disable-pw').value;
            if (!pw) {
                setMsg('sp2fa-disable-msg', 'Please enter your password.', 'error');
                return;
            }
            btnDisable.disabled = true;
            btnDisable.textContent = 'Disabling...';
            api('POST', '/2fa/disable', { password: pw }).then(function () {
                location.reload();
            }).catch(function (err) {
                setMsg('sp2fa-disable-msg', getApiMessage(err, 'Incorrect password.'), 'error');
                btnDisable.disabled = false;
                btnDisable.textContent = 'Disable 2FA';
            });
        });
    }

    /* ================================================================
       REGENERATE RECOVERY CODES
       ================================================================ */

    var btnShowRegen    = document.getElementById('sp2fa-btn-regen');
    var btnConfirmRegen = document.getElementById('sp2fa-btn-confirm-regen');
    var btnCancelRegen  = document.getElementById('sp2fa-btn-cancel-regen');

    if (btnShowRegen) {
        btnShowRegen.addEventListener('click', function () {
            hide(disableRow);
            hide(actionsRow);
            show(regenRow);
            hideMsg('sp2fa-regen-msg');
            var pw = document.getElementById('sp2fa-regen-pw');
            if (pw) pw.focus();
        });
    }

    if (btnCancelRegen) {
        btnCancelRegen.addEventListener('click', function () {
            hideMsg('sp2fa-regen-msg');
            var pw = document.getElementById('sp2fa-regen-pw');
            if (pw) pw.value = '';
            hide(regenRow);
            show(actionsRow);
        });
    }

    if (btnConfirmRegen) {
        btnConfirmRegen.addEventListener('click', function () {
            var pw = document.getElementById('sp2fa-regen-pw').value;
            if (!pw) {
                setMsg('sp2fa-regen-msg', 'Please enter your password.', 'error');
                return;
            }

            btnConfirmRegen.disabled = true;
            btnConfirmRegen.textContent = 'Generating...';

            api('POST', '/2fa/regenerate-codes', { password: pw }).then(function (data) {
                if (data.recovery_codes) {
                    var container = document.getElementById('sp2fa-new-codes');
                    container.innerHTML = renderRecoveryCodes(data.recovery_codes, true);
                    show(container);
                    bindCopyCodes();
                    updateRecoveryCount(data.recovery_codes.length);
                }

                hideMsg('sp2fa-regen-msg');
                var pwInput = document.getElementById('sp2fa-regen-pw');
                if (pwInput) pwInput.value = '';
                hide(regenRow);
                show(actionsRow);
                btnConfirmRegen.disabled = false;
                btnConfirmRegen.textContent = 'Generate New Recovery Codes';
            }).catch(function (err) {
                setMsg('sp2fa-regen-msg', getApiMessage(err, 'Unable to regenerate recovery codes.'), 'error');
                btnConfirmRegen.disabled = false;
                btnConfirmRegen.textContent = 'Generate New Recovery Codes';
            });
        });
    }

    /* ── Copy codes helper ───────────────────────────────────────── */

    function bindCopyCodes() {
        var btns = document.querySelectorAll('.sp2fa-copy-codes');
        btns.forEach(function (btn) {
            btn.addEventListener('click', function () {
                var codes = btn.getAttribute('data-codes');
                navigator.clipboard.writeText(codes).then(function () {
                    btn.textContent = 'Copied!';
                    setTimeout(function () { btn.textContent = 'Copy codes'; }, 2000);
                });
            });
        });
    }
})();
