/* Pagina /register — cadastro publico de cliente B2B.
   Form com validacao CPF/CNPJ + politica de senha em real-time.
   Pos-cadastro: redireciona pra /login com mensagem de sucesso. */

const { useState: r_useState } = React;


function pwd_policy_issues(pw) {
    const i = [];
    if (pw.length < 8) i.push('mínimo 8 caracteres');
    if (!/[A-Z]/.test(pw)) i.push('1 letra maiúscula');
    if (!/\d/.test(pw)) i.push('1 número');
    if (!/[^A-Za-z0-9]/.test(pw)) i.push('1 caractere especial');
    return i;
}


window.C7_RegisterPage = function RegisterPage() {
    const [nome, setNome]         = r_useState('');
    const [email, setEmail]       = r_useState('');
    const [doc, setDoc]           = r_useState('');
    const [telefone, setTelefone] = r_useState('');
    const [password, setPassword] = r_useState('');
    const [password2, setPassword2] = r_useState('');
    const [accept, setAccept]     = r_useState(false);
    const [loading, setLoading]   = r_useState(false);
    const [err, setErr]           = r_useState(null);
    const [success, setSuccess]   = r_useState(false);
    const [tsToken, setTsToken]   = r_useState(null);
    const [tsReset, setTsReset]   = r_useState(0);

    function on_doc_change(raw) {
        // mascara CPF/CNPJ enquanto digita
        setDoc(window.C7_Doc.maskCpfCnpj(raw));
    }

    const doc_digits  = window.C7_Doc ? window.C7_Doc.normalize(doc) : doc;
    const doc_type    = window.C7_Doc ? window.C7_Doc.detectType(doc) : null;
    const doc_valid   = window.C7_Doc ? window.C7_Doc.isValid(doc) : false;
    const pw_issues   = pwd_policy_issues(password);
    const pw_ok       = pw_issues.length === 0;
    const pw_match    = password && password === password2;
    const email_ok    = /^\S+@\S+\.\S+$/.test(email);
    const phone_ok    = telefone.replace(/\D/g, '').length >= 10;
    const can_submit  = nome.trim().length >= 3 && email_ok && doc_valid
                        && phone_ok && pw_ok && pw_match && accept
                        && !!tsToken && !loading;

    async function submit(e) {
        e.preventDefault();
        if (!can_submit) return;
        setErr(null);
        setLoading(true);
        try {
            await window.C7_API.post('/auth/register', {
                nome:            nome.trim(),
                email:           email.trim(),
                doc:             doc_digits,
                doc_type:        doc_type,
                telefone:        telefone.trim(),
                password:        password,
                turnstile_token: tsToken,
            });
            setSuccess(true);
        } catch (e) {
            setErr(e.message || 'falha no cadastro');
            setTsToken(null);
            setTsReset(n => n + 1);
            setLoading(false);
        }
    }

    const Turnstile = (window.C7_Forms && window.C7_Forms.Turnstile) || null;

    const AppFooter = (window.C7_Layout && window.C7_Layout.AppFooter) || null;

    if (success) {
        return (
            <div className="standalone-shell">
                <div className="standalone-center">
                    <div className="register-card">
                        <h1>✓ Cadastro realizado</h1>
                        <p>
                            Sua conta foi criada com sucesso. Enviamos um email
                            de boas-vindas pra <strong>{email}</strong>.
                        </p>
                        <p>
                            Agora faça login pra configurar 2FA, aceitar os
                            termos e iniciar o processo de KYC.
                        </p>
                        <a href="#/login" className="register-btn">Ir pro login</a>
                    </div>
                </div>
                {AppFooter && <AppFooter />}
            </div>
        );
    }

    return (
        <div className="standalone-shell">
            <div className="standalone-center">
                <div className="register-card">
                    <h1>Criar conta</h1>
                    <p className="register-intro">
                        Cadastro inicial. Após criar a conta você passará por
                        verificação de identidade (KYC) antes de operar.
                    </p>

                    <form onSubmit={submit}>
                        <label>
                            <span>Nome completo / Razão social</span>
                            <input type="text" value={nome}
                                   onChange={(e) => setNome(e.target.value)}
                                   autoComplete="name" required minLength={3} />
                        </label>

                        <label>
                            <span>E-mail</span>
                            <input type="email" value={email}
                                   onChange={(e) => setEmail(e.target.value)}
                                   autoComplete="email" required />
                            {email && !email_ok && (
                                <small className="reg-hint reg-hint-err">e-mail inválido</small>
                            )}
                        </label>

                        <label>
                            <span>CPF ou CNPJ</span>
                            <input type="text" value={doc}
                                   onChange={(e) => on_doc_change(e.target.value)}
                                   autoComplete="off" required
                                   placeholder="000.000.000-00 ou 00.000.000/0000-00" />
                            {doc && doc_type && (
                                doc_valid
                                    ? <small className="reg-hint reg-hint-ok">✓ {doc_type} válido</small>
                                    : <small className="reg-hint reg-hint-err">{doc_type} inválido</small>
                            )}
                            {doc && !doc_type && (
                                <small className="reg-hint">continua digitando…</small>
                            )}
                        </label>

                        <label>
                            <span>Telefone (com DDD)</span>
                            <input type="tel" value={telefone}
                                   onChange={(e) => setTelefone(e.target.value)}
                                   autoComplete="tel" required
                                   placeholder="(27) 99999-9999" />
                        </label>

                        <label>
                            <span>Senha</span>
                            <input type="password" value={password}
                                   onChange={(e) => setPassword(e.target.value)}
                                   autoComplete="new-password" required minLength={8} />
                        </label>

                        {password && (
                            <ul className="change-password-checklist">
                                <li className={password.length >= 8 ? 'ok' : ''}>
                                    {password.length >= 8 ? '✓' : '○'} mínimo 8 caracteres
                                </li>
                                <li className={/[A-Z]/.test(password) ? 'ok' : ''}>
                                    {/[A-Z]/.test(password) ? '✓' : '○'} 1 letra maiúscula
                                </li>
                                <li className={/\d/.test(password) ? 'ok' : ''}>
                                    {/\d/.test(password) ? '✓' : '○'} 1 número
                                </li>
                                <li className={/[^A-Za-z0-9]/.test(password) ? 'ok' : ''}>
                                    {/[^A-Za-z0-9]/.test(password) ? '✓' : '○'} 1 caractere especial
                                </li>
                            </ul>
                        )}

                        <label>
                            <span>Confirme a senha</span>
                            <input type="password" value={password2}
                                   onChange={(e) => setPassword2(e.target.value)}
                                   autoComplete="new-password" required minLength={8} />
                            {password2 && !pw_match && (
                                <small className="reg-hint reg-hint-err">senhas não batem</small>
                            )}
                        </label>

                        <label className="register-checkbox">
                            <input type="checkbox" checked={accept}
                                   onChange={(e) => setAccept(e.target.checked)} />
                            <span>
                                Li e concordo com os{' '}
                                <a href="#/termos" target="_blank">Termos de Uso</a>
                                {' '}e a{' '}
                                <a href="#/privacidade" target="_blank">Política de Privacidade</a>.
                            </span>
                        </label>

                        {err && <div className="register-error">{err}</div>}

                        {Turnstile && <Turnstile on_token={setTsToken} reset_signal={tsReset} />}

                        <button type="submit" className="register-btn"
                                disabled={!can_submit}>
                            {loading ? 'criando conta…' : 'Criar conta'}
                        </button>

                        <div className="register-foot">
                            Já tem conta? <a href="#/login">Entrar</a>
                        </div>
                    </form>
                </div>
            </div>
            {AppFooter && <AppFooter />}
        </div>
    );
};
