<main class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-9">
            <div class="card border-0 shadow-soft rounded-4 overflow-hidden">
                <div class="row g-0">
                    <div class="col-lg-5 bg-warning-subtle p-4 p-md-5 d-flex flex-column justify-content-center">
                        <span class="feature-icon mb-3"><i class="bi bi-mortarboard"></i></span>
                        <h1 class="h3 fw-bold text-cfc-dark">Formação para Instrutores</h1>
                        <p class="mb-0">Cadastre-se para solicitar e-books, livros, manuais e videoaulas sobre como ensinar um aluno desde o início.</p>
                    </div>
                    <div class="col-lg-7 p-4 p-md-5">
                        <h2 class="h4 fw-bold mb-3">Cadastro</h2>
                        <form method="post" action="<?= e(url('beginner/register/post')) ?>" class="row g-3">
                            <?= CSRF::input() ?>
                            <div class="col-12"><label class="form-label">Nome completo</label><input name="name" class="form-control" required></div>
                            <div class="col-md-6">
                                <label class="form-label" for="beginnerCpf">CPF</label>
                                <input id="beginnerCpf" name="cpf" class="form-control" inputmode="numeric" autocomplete="off" maxlength="14" placeholder="000.000.000-00" required>
                                <div class="form-text">Digite os 11 números. A separação é colocada automaticamente.</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label" for="beginnerWhatsapp">WhatsApp</label>
                                <input id="beginnerWhatsapp" name="whatsapp" class="form-control" inputmode="tel" autocomplete="tel" maxlength="15" placeholder="(00) 90000-0000" required>
                                <div class="form-text">Informe DDD e celular. Sequências numéricas inválidas serão bloqueadas.</div>
                            </div>
                            <div class="col-md-6"><label class="form-label">E-mail</label><input type="email" name="email" class="form-control" required></div>
                            <div class="col-md-6"><label class="form-label">Senha</label><input type="password" name="password" class="form-control" minlength="6" required></div>
                            <div class="col-12 d-flex flex-wrap gap-2"><button class="btn btn-success rounded-pill px-4"><i class="bi bi-person-plus"></i> Cadastrar</button><a class="btn btn-outline-primary rounded-pill px-4" href="<?= e(url('beginner/login')) ?>">Já tenho cadastro</a></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
(function () {
    const form = document.querySelector('form[action*="beginner%2Fregister%2Fpost"], form[action*="beginner/register/post"]');
    const cpfInput = document.getElementById('beginnerCpf');
    const whatsappInput = document.getElementById('beginnerWhatsapp');
    if (!form || !cpfInput || !whatsappInput) return;

    const digitsOnly = value => String(value || '').replace(/\D+/g, '');

    function hasForbiddenSequence(value, minimumRun = 6) {
        const digits = digitsOnly(value);
        if (!digits) return false;
        if (/^(\d)\1+$/.test(digits)) return true;
        if (new RegExp('(\\d)\\1{' + (minimumRun - 1) + ',}').test(digits)) return true;
        for (let start = 0; start <= digits.length - minimumRun; start++) {
            let ascending = true;
            let descending = true;
            for (let offset = 1; offset < minimumRun; offset++) {
                const previous = Number(digits[start + offset - 1]);
                const current = Number(digits[start + offset]);
                if (current !== ((previous + 1) % 10)) ascending = false;
                if (current !== ((previous + 9) % 10)) descending = false;
            }
            if (ascending || descending) return true;
        }
        return false;
    }

    function isValidCpf(value) {
        const cpf = digitsOnly(value);
        if (cpf.length !== 11 || hasForbiddenSequence(cpf)) return false;
        for (let position = 9; position <= 10; position++) {
            let sum = 0;
            for (let i = 0; i < position; i++) {
                sum += Number(cpf[i]) * ((position + 1) - i);
            }
            let digit = (10 * sum) % 11;
            if (digit === 10) digit = 0;
            if (digit !== Number(cpf[position])) return false;
        }
        return true;
    }

    function isValidWhatsapp(value) {
        let phone = digitsOnly(value);
        if (phone.length === 13 && phone.startsWith('55')) phone = phone.slice(2);
        if (phone.length !== 11 || hasForbiddenSequence(phone)) return false;
        const ddd = Number(phone.slice(0, 2));
        return ddd >= 11 && ddd <= 99 && phone[2] === '9';
    }

    function maskCpf(value) {
        const digits = digitsOnly(value).slice(0, 11);
        let result = digits.slice(0, 3);
        if (digits.length > 3) result += '.' + digits.slice(3, 6);
        if (digits.length > 6) result += '.' + digits.slice(6, 9);
        if (digits.length > 9) result += '-' + digits.slice(9, 11);
        return result;
    }

    function maskWhatsapp(value) {
        let digits = digitsOnly(value);
        if (digits.length > 11 && digits.startsWith('55')) digits = digits.slice(2);
        digits = digits.slice(0, 11);
        let result = '';
        if (digits.length) result = '(' + digits.slice(0, 2);
        if (digits.length >= 2) result += ') ';
        if (digits.length > 2) result += digits.slice(2, 7);
        if (digits.length > 7) result += '-' + digits.slice(7, 11);
        return result;
    }

    function validateCpf() {
        const digits = digitsOnly(cpfInput.value);
        cpfInput.setCustomValidity(digits.length === 0 || isValidCpf(digits) ? '' : 'Informe um CPF válido, sem números repetidos ou sequenciais.');
    }

    function validateWhatsapp() {
        const digits = digitsOnly(whatsappInput.value);
        whatsappInput.setCustomValidity(digits.length === 0 || isValidWhatsapp(digits) ? '' : 'Informe um WhatsApp válido com DDD, sem números repetidos ou sequenciais.');
    }

    cpfInput.addEventListener('input', function () {
        this.value = maskCpf(this.value);
        validateCpf();
    });
    whatsappInput.addEventListener('input', function () {
        this.value = maskWhatsapp(this.value);
        validateWhatsapp();
    });
    cpfInput.addEventListener('blur', validateCpf);
    whatsappInput.addEventListener('blur', validateWhatsapp);
    form.addEventListener('submit', function () {
        validateCpf();
        validateWhatsapp();
    });
})();
</script>
