jQuery(function ($) {
    const i18n = window.VulnTitanLoginSecurityProfile || {};
    const $setups = $('.vulntitan-2fa-profile-setup');
    if (!$setups.length || typeof $.fn.qrcode !== 'function') {
        return;
    }

    $setups.each(function () {
        const $setup = $(this);
        const otpUri = String($setup.data('vulntitanOtpUri') || '');
        const $qrTarget = $setup.find('[data-vulntitan-2fa-qr]');
        const isAlreadyEnabled = String($setup.data('vulntitan2faEnabled') || '') === '1';
        const hasSetupError = String($setup.data('vulntitan2faError') || '') === '1';
        const $toggle = $('#vulntitan-2fa-enabled');
        const $code = $('#vulntitan-2fa-verification-code');
        const $verifyHelp = $('[data-vulntitan-2fa-verify-help]');
        const $stepScan = $setup.find('[data-vulntitan-step="scan"]');
        const $stepToggle = $setup.find('[data-vulntitan-step="toggle"]');
        const $stepVerify = $setup.find('[data-vulntitan-step="verify"]');
        const $stepSave = $setup.find('[data-vulntitan-step="save"]');
        const $inlineNotice = $setup.find('[data-vulntitan-2fa-inline-notice]');

        if (!otpUri || !$qrTarget.length) {
            return;
        }

        $qrTarget.empty().qrcode({
            text: otpUri,
            width: window.innerWidth <= 782 ? 176 : 220,
            height: window.innerWidth <= 782 ? 176 : 220,
            background: '#ffffff',
            foreground: '#0f172a',
            correctLevel: 2
        });

        function syncWizardState() {
            if (isAlreadyEnabled || !$stepScan.length) {
                return;
            }

            const wantsEnable = $toggle.is(':checked');
            const codeValue = String($code.val() || '').replace(/\s+/g, '');
            const hasCode = codeValue.length >= 6;

            $stepScan.removeClass('is-muted').addClass('is-active');
            $stepToggle.toggleClass('is-active', !wantsEnable).toggleClass('is-complete', wantsEnable);
            $stepVerify
                .toggleClass('is-muted', !wantsEnable)
                .toggleClass('is-active', wantsEnable && !hasCode)
                .toggleClass('is-complete', wantsEnable && hasCode);
            $stepSave
                .toggleClass('is-muted', !(wantsEnable && hasCode))
                .toggleClass('is-active', wantsEnable && hasCode);

            $code.prop('disabled', !wantsEnable).toggleClass('vulntitan-2fa-verify-disabled', !wantsEnable);

            if (!wantsEnable) {
                $verifyHelp.text(i18n.step_enable_first || 'Turn on Step 2 first, then enter the current code from your authenticator app here.');
            } else if (!hasCode) {
                $verifyHelp.text(i18n.step_enter_code || 'Enter the current 6-digit code from your authenticator app, then click Update Profile.');
            } else {
                $verifyHelp.text(i18n.step_ready || 'Ready. Click Update Profile to finish setup and generate recovery codes.');
            }
        }

        syncWizardState();

        if (hasSetupError && $code.length) {
            window.setTimeout(function () {
                const scrollTarget = $inlineNotice.length ? $inlineNotice.get(0) : ($stepVerify.length ? $stepVerify.get(0) : $code.get(0));

                if (scrollTarget && typeof scrollTarget.scrollIntoView === 'function') {
                    scrollTarget.scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }

                $code.trigger('focus');
            }, 120);
        }

        $toggle.off('.vulntitan2fa').on('change.vulntitan2fa', function () {
            syncWizardState();

            if ($(this).is(':checked') && $code.length) {
                $code.trigger('focus');
            }
        });

        $code.off('.vulntitan2fa').on('input.vulntitan2fa', function () {
            syncWizardState();
        });
    });
});
