/**
 * modules/ui/registerWizard.js — Asistente de registro por pasos (correo → teléfono → …).
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.ui = g.modules.ui || {};

    var dom = g.modules.core.dom;
    var crypto = g.modules.core.crypto;
    var messages = g.modules.ui.messages;

    g.modules.ui.registerWizard = {
        /**
         * Construye el flujo dentro de host. Resuelve con el objeto para userCRUD.create + flags wantBio.
         */
        run: function (host, onComplete) {
            var state = { loginType: 'password', wantBio: false };

            function scrollStepToTop() {
                var modal = host.closest('.auth-modal');
                if (modal) {
                    modal.scrollTop = 0;
                }
                host.scrollTop = 0;
            }

            function mount(node) {
                host.innerHTML = '';
                host.appendChild(node);
                scrollStepToTop();
            }

            function stepEmail() {
                var wrap = dom.el('div', { className: 'auth-step' });
                wrap.innerHTML =
                    '<label class="auth-label">' +
                    messages.escape(messages.text('email')) +
                    '</label>' +
                    '<input type="email" class="auth-input" autocomplete="email" />';
                var inp = wrap.querySelector('input');
                inp.value = state.email || '';
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: messages.text('registerBtn'), onclick: function () {
                        state.email = inp.value.trim();
                        if (!state.email || state.email.indexOf('@') < 0) {
                            messages.alert(messages.text('errGeneric'));
                            return;
                        }
                        stepPhone();
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function stepPhone() {
                var wrap = dom.el('div', { className: 'auth-step' });
                wrap.innerHTML =
                    '<label class="auth-label">' +
                    messages.escape(messages.text('phone')) +
                    '</label>' +
                    '<input type="tel" class="auth-input" autocomplete="tel" />';
                var inp = wrap.querySelector('input');
                inp.value = state.phone || '';
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: messages.text('back'), onclick: stepEmail,
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: messages.text('registerBtn'), onclick: function () {
                        state.phone = inp.value.trim();
                        stepPassword();
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function stepPassword() {
                var wrap = dom.el('div', { className: 'auth-step' });
                wrap.innerHTML =
                    '<label class="auth-label">' +
                    messages.escape(messages.text('password')) +
                    '</label>' +
                    '<input type="password" class="auth-input" autocomplete="new-password" />';
                var inp = wrap.querySelector('input');
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: messages.text('back'), onclick: stepPhone,
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: messages.text('registerBtn'), onclick: function () {
                        var p = inp.value;
                        if (!p || p.length < 6) {
                            messages.alert(messages.text('errWeakPassword'));
                            return;
                        }
                        state.password = p;
                        stepPin();
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function stepPin() {
                var wrap = dom.el('div', { className: 'auth-step' });
                wrap.innerHTML =
                    '<label class="auth-label">' +
                    messages.escape(messages.text('pin')) +
                    '</label>' +
                    '<input type="password" inputmode="numeric" pattern="[0-9]*" class="auth-input" maxlength="8" />';
                var inp = wrap.querySelector('input');
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: messages.text('back'), onclick: stepPassword,
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: messages.text('registerBtn'), onclick: function () {
                        var p = inp.value.trim();
                        if (!/^\d{4,8}$/.test(p)) {
                            messages.alert(messages.text('errPin'));
                            return;
                        }
                        state.pin = p;
                        stepPattern();
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function stepPattern() {
                var wrap = dom.el('div', { className: 'auth-step auth-pattern-step' });
                wrap.innerHTML =
                    '<p class="auth-hint">Une al menos 4 puntos en la cuadrícula 3×3.</p>' +
                    '<div class="auth-pattern-grid" id="patGrid"></div>' +
                    '<p class="auth-pattern-seq" id="patSeq"></p>';
                var grid = wrap.querySelector('#patGrid');
                var seqEl = wrap.querySelector('#patSeq');
                var seq = [];
                for (var i = 1; i <= 9; i++) {
                    var cell = dom.el('button', { type: 'button', className: 'auth-pattern-dot', 'data-n': String(i) });
                    cell.textContent = String(i);
                    cell.addEventListener('click', function () {
                        var n = this.getAttribute('data-n');
                        if (seq.length === 0 || seq[seq.length - 1] !== n) seq.push(n);
                        seqEl.textContent = seq.join(' → ');
                    });
                    grid.appendChild(cell);
                }
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: messages.text('back'), onclick: stepPin,
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: 'Limpiar', onclick: function () {
                        seq = [];
                        seqEl.textContent = '';
                    },
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: messages.text('registerBtn'), onclick: function () {
                        if (seq.length < 4) {
                            messages.alert(messages.text('errPattern'));
                            return;
                        }
                        state.patternSeq = g.modules.auth.patternLogin.normalize(seq.join(''));
                        stepRecovery();
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function stepRecovery() {
                var wrap = dom.el('div', { className: 'auth-step' });
                var code = crypto.randomSaltB64().replace(/[^a-zA-Z0-9]/g, '').slice(0, 10);
                state.recoveryCode = code;
                wrap.innerHTML =
                    '<p class="auth-hint">' +
                    messages.escape(messages.text('recoveryHint')) +
                    '</p>' +
                    '<p class="auth-recovery-code"><strong>' +
                    messages.escape(code) +
                    '</strong></p>' +
                    '<p class="auth-hint">Guárdalo en un lugar seguro.</p>';
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: messages.text('back'), onclick: stepPattern,
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: messages.text('registerBtn'), onclick: function () {
                        g.modules.hardware.deviceDetector.showBiometricOption().then(function (showBio) {
                            if (showBio) {
                                stepBioOffer();
                            } else {
                                state.wantBio = false;
                                finish();
                            }
                        });
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function stepBioOffer() {
                var wrap = dom.el('div', { className: 'auth-step' });
                wrap.innerHTML = '<p class="auth-hint">¿Registrar huella o rostro en este dispositivo después de crear la cuenta?</p>';
                var actions = dom.el('div', { className: 'auth-modal-actions' });
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-secondary', text: 'No', onclick: function () {
                        state.wantBio = false;
                        finish();
                    },
                }));
                actions.appendChild(dom.el('button', {
                    type: 'button', className: 'auth-btn auth-btn-primary', text: 'Sí', onclick: function () {
                        state.wantBio = true;
                        finish();
                    },
                }));
                wrap.appendChild(actions);
                mount(wrap);
            }

            function finish() {
                onComplete(state);
            }

            stepEmail();
        },
    };
})(typeof window !== 'undefined' ? window : this);
