<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Avaliação Gratuita | Aurion ERP</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary: #2C3E50;
            --primary-light: #34495e;
            --secondary: #0066CC;
            --success: #27ae60;
            --bg-light: #F8F9FA;
            --bg-white: #FFFFFF;
            --text-dark: #1A1A1A;
            --text-gray: #6C757D;
            --border: #E0E6ED;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #f0f4f8 0%, #e8edf2 100%);
            min-height: 100vh;
            padding: 2rem 0;
        }

        .register-wrapper {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 1rem;
        }

        .register-card {
            background: var(--bg-white);
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        .register-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
            color: white;
            padding: 2.5rem;
            text-align: center;
        }

        .register-header img {
            max-height: 90px;
            margin-bottom: 1.5rem;
            filter: brightness(0) invert(1);
        }

        .register-header h1 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .register-header p {
            opacity: 0.9;
            margin: 0;
            font-size: 1.1rem;
        }

        .register-body {
            padding: 2.5rem;
        }

        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 2.5rem;
            gap: 1rem;
        }

        .step {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--text-gray);
            font-size: 0.9rem;
        }

        .step.active {
            color: var(--primary);
            font-weight: 600;
        }

        .step-number {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .step.active .step-number {
            background: var(--primary);
            color: white;
        }

        .form-section {
            display: none;
        }

        .form-section.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid var(--border);
        }

        .form-label {
            color: var(--text-dark);
            font-weight: 500;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }

        .form-label .required {
            color: #dc3545;
        }

        .form-control,
        .form-select {
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 0.75rem 1rem;
            transition: all 0.3s;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(44, 62, 80, 0.1);
        }

        .input-group-text {
            background: var(--bg-light);
            border: 1px solid var(--border);
            color: var(--text-gray);
        }

        .btn-primary {
            background: var(--primary);
            border: none;
            padding: 0.875rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            background: var(--primary-light);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(44, 62, 80, 0.2);
        }

        .btn-secondary {
            background: white;
            border: 2px solid var(--border);
            color: var(--text-dark);
            padding: 0.875rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .btn-secondary:hover {
            border-color: var(--primary);
            color: var(--primary);
        }

        .plan-cards {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .plan-card {
            border: 2px solid var(--border);
            border-radius: 12px;
            padding: 2rem 1.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: white;
            position: relative;
            min-height: 320px;
            display: flex;
            flex-direction: column;
        }

        .plan-card:hover {
            border-color: var(--primary);
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(44, 62, 80, 0.1);
        }

        .plan-card.selected {
            border-color: var(--primary);
            background: linear-gradient(135deg, rgba(44, 62, 80, 0.05) 0%, rgba(52, 73, 94, 0.05) 100%);
            box-shadow: 0 5px 15px rgba(44, 62, 80, 0.15);
        }

        .plan-card input[type="radio"] {
            display: none;
        }

        .plan-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            background: var(--success);
            color: white;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-bottom: 0.75rem;
            text-transform: uppercase;
        }

        .plan-name {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 0.5rem;
        }

        .plan-price {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 0.5rem;
            line-height: 1.2;
            min-height: 65px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }

        .plan-price small {
            font-size: 0.875rem;
            font-weight: 400;
            color: var(--text-gray);
            display: block;
            margin-top: 0.25rem;
        }

        .plan-price .price-prefix {
            font-size: 0.75rem;
            font-weight: 500;
            color: var(--text-gray);
            display: block;
            margin-bottom: 0.25rem;
        }

        .plan-features {
            list-style: none;
            padding: 0;
            margin: 1rem 0 0 0;
            font-size: 0.875rem;
            color: var(--text-gray);
            flex-grow: 1;
            text-align: left;
        }

        .plan-features li {
            padding: 0.4rem 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .plan-features li::before {
            content: '✓';
            color: var(--success);
            font-weight: 700;
            font-size: 1rem;
        }

        .loading-indicator {
            display: none;
            color: var(--secondary);
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }

        .loading-indicator.show {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .success-indicator {
            display: none;
            color: var(--success);
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }

        .success-indicator.show {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .back-link {
            text-align: center;
            margin-top: 1.5rem;
        }

        .back-link a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }

        .back-link a:hover {
            text-decoration: underline;
        }

        @media (max-width: 768px) {
            .plan-cards {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div class="register-wrapper">
        <div class="register-card">
            <!-- Header -->
            <div class="register-header">
                <img src="storage/uploads/logo.png" alt="Systhema ERP">
                <h1>Cadastro Empresarial</h1>
                <p>Complete o cadastro e comece a usar o sistema imediatamente</p>
            </div>

            <!-- Body -->
            <div class="register-body">
                <!-- Indicador de Etapas -->
                <div class="step-indicator">
                    <div class="step active" data-step="1">
                        <span class="step-number">1</span>
                        <span>Plano</span>
                    </div>
                    <div class="step" data-step="2">
                        <span class="step-number">2</span>
                        <span>Empresa</span>
                    </div>
                    <div class="step" data-step="3">
                        <span class="step-number">3</span>
                        <span>Acesso</span>
                    </div>
                </div>

                <form id="registerForm">
                    <!-- ETAPA 1: Seleção de Plano -->
                    <div class="form-section active" data-section="1">
                        <h2 class="section-title">
                            <i class="bi bi-star me-2"></i>Escolha seu Plano
                        </h2>

                        <div class="plan-cards">
                            <div class="plan-card selected" data-plan="trial">
                                <input type="radio" name="plan" value="trial" checked>
                                <div class="plan-badge">Avaliação</div>
                                <div class="plan-name">Trial</div>
                                <div class="plan-price">72 horas<small> grátis</small></div>
                                <ul class="plan-features">
                                    <li>Até 2 usuários</li>
                                    <li>1 CNPJ</li>
                                    <li>5 notas fiscais</li>
                                </ul>
                            </div>

                            <div class="plan-card" data-plan="pro">
                                <input type="radio" name="plan" value="pro">
                                <div class="plan-badge" style="background: var(--secondary);">Recomendado</div>
                                <div class="plan-name">Profissional</div>
                                <div class="plan-price">R$ 199,99<small>/mês</small></div>
                                <ul class="plan-features">
                                    <li>Até 5 usuários</li>
                                    <li>2 empresas (CNPJs)</li>
                                    <li>NF-e ilimitadas</li>
                                    <li>Suporte Técnico</li>
                                </ul>
                            </div>

                            <div class="plan-card" data-plan="enterprise">
                                <input type="radio" name="plan" value="enterprise">
                                <div class="plan-badge" style="background: #e67e22;">Premium</div>
                                <div class="plan-name">Enterprise</div>
                                <div class="plan-price">
                                    <span class="price-prefix">A partir de</span>
                                    R$ 499,99<small>/mês</small>
                                </div>
                                <ul class="plan-features">
                                    <li>Usuários ilimitados</li>
                                    <li>Empresas ilimitadas</li>
                                    <li>NF-e ilimitadas</li>
                                    <li>API + Integrações</li>
                                    <li>Suporte Premium</li>
                                    <li>Relatórios customizados</li>
                                    <li>SLA garantido</li>
                                    <li>Gerente dedicado</li>
                                </ul>
                            </div>
                        </div>

                        <div class="d-grid">
                            <button type="button" class="btn btn-primary btn-lg" onclick="nextStep(2)">
                                Continuar <i class="bi bi-arrow-right ms-2"></i>
                            </button>
                        </div>
                    </div>

                    <!-- ETAPA 2: Dados da Empresa -->
                    <div class="form-section" data-section="2">
                        <h2 class="section-title">
                            <i class="bi bi-building me-2"></i>Dados da Empresa
                        </h2>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="cnpj" class="form-label">
                                    CNPJ <span class="required">*</span>
                                </label>
                                <input type="text" class="form-control" id="cnpj" name="cnpj"
                                    placeholder="00.000.000/0000-00" required>
                                <div class="loading-indicator" id="cnpjLoading">
                                    <div class="spinner-border spinner-border-sm" role="status"></div>
                                    <span>Buscando dados...</span>
                                </div>
                                <div class="success-indicator" id="cnpjSuccess">
                                    <i class="bi bi-check-circle-fill"></i>
                                    <span>Dados encontrados e preenchidos!</span>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="company_name" class="form-label">
                                    Razão Social <span class="required">*</span>
                                </label>
                                <input type="text" class="form-control" id="company_name" name="company_name" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="trade_name" class="form-label">Nome Fantasia</label>
                                <input type="text" class="form-control" id="trade_name" name="trade_name">
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="email" class="form-label">
                                    Email da Empresa <span class="required">*</span>
                                </label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="phone" class="form-label">Telefone</label>
                                <input type="text" class="form-control" id="phone" name="phone"
                                    placeholder="(00) 0000-0000">
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="mobile" class="form-label">Celular</label>
                                <input type="text" class="form-control" id="mobile" name="mobile"
                                    placeholder="(00) 00000-0000">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="zip_code" class="form-label">CEP</label>
                                <input type="text" class="form-control" id="zip_code" name="zip_code"
                                    placeholder="00000-000">
                            </div>

                            <div class="col-md-8 mb-3">
                                <label for="address" class="form-label">Endereço</label>
                                <input type="text" class="form-control" id="address" name="address">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="numero" class="form-label">Número</label>
                                <input type="text" class="form-control" id="numero" name="numero">
                            </div>

                            <div class="col-md-3 mb-3">
                                <label for="complemento" class="form-label">Complemento</label>
                                <input type="text" class="form-control" id="complemento" name="complemento">
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="bairro" class="form-label">Bairro</label>
                                <input type="text" class="form-control" id="bairro" name="bairro">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label for="city" class="form-label">Cidade</label>
                                <input type="text" class="form-control" id="city" name="city">
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="state" class="form-label">Estado</label>
                                <select class="form-select" id="state" name="state">
                                    <option value="">Selecione...</option>
                                    <option value="AC">Acre</option>
                                    <option value="AL">Alagoas</option>
                                    <option value="AP">Amapá</option>
                                    <option value="AM">Amazonas</option>
                                    <option value="BA">Bahia</option>
                                    <option value="CE">Ceará</option>
                                    <option value="DF">Distrito Federal</option>
                                    <option value="ES">Espírito Santo</option>
                                    <option value="GO">Goiás</option>
                                    <option value="MA">Maranhão</option>
                                    <option value="MT">Mato Grosso</option>
                                    <option value="MS">Mato Grosso do Sul</option>
                                    <option value="MG">Minas Gerais</option>
                                    <option value="PA">Pará</option>
                                    <option value="PB">Paraíba</option>
                                    <option value="PR">Paraná</option>
                                    <option value="PE">Pernambuco</option>
                                    <option value="PI">Piauí</option>
                                    <option value="RJ">Rio de Janeiro</option>
                                    <option value="RN">Rio Grande do Norte</option>
                                    <option value="RS">Rio Grande do Sul</option>
                                    <option value="RO">Rondônia</option>
                                    <option value="RR">Roraima</option>
                                    <option value="SC">Santa Catarina</option>
                                    <option value="SP">São Paulo</option>
                                    <option value="SE">Sergipe</option>
                                    <option value="TO">Tocantins</option>
                                </select>
                            </div>
                        </div>

                        <div class="d-flex gap-2 justify-content-between mt-4">
                            <button type="button" class="btn btn-secondary" onclick="prevStep(1)">
                                <i class="bi bi-arrow-left me-2"></i> Voltar
                            </button>
                            <button type="button" class="btn btn-primary" onclick="nextStep(3)">
                                Continuar <i class="bi bi-arrow-right ms-2"></i>
                            </button>
                        </div>
                    </div>

                    <!-- ETAPA 3: Dados de Acesso -->
                    <div class="form-section" data-section="3">
                        <h2 class="section-title">
                            <i class="bi bi-person-check me-2"></i>Dados de Acesso
                        </h2>

                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="subdomain" class="form-label">
                                    Subdomínio <span class="required">*</span>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="subdomain" name="subdomain"
                                        placeholder="minhaempresa" pattern="[a-z0-9-]+" required>
                                    <span class="input-group-text">.Systhema.com.br</span>
                                </div>
                                <small class="text-muted d-block mt-1">
                                    Use apenas letras minúsculas, números e hífen
                                </small>
                                <div class="availability-check" id="availabilityCheck"></div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="name" class="form-label">
                                    Seu Nome <span class="required">*</span>
                                </label>
                                <input type="text" class="form-control" id="name" name="name"
                                    placeholder="Nome do administrador" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="password" class="form-label">
                                    Senha <span class="required">*</span>
                                </label>
                                <input type="password" class="form-control" id="password" name="password" required
                                    minlength="8" placeholder="Mínimo 8 caracteres">
                                <small class="text-muted d-block mt-1">
                                    Mínimo 8 caracteres
                                </small>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="password_confirmation" class="form-label">
                                    Confirmar Senha <span class="required">*</span>
                                </label>
                                <input type="password" class="form-control" id="password_confirmation"
                                    name="password_confirmation" required>
                            </div>
                        </div>

                        <div class="form-check mb-4">
                            <input class="form-check-input" type="checkbox" id="terms" required>
                            <label class="form-check-label" for="terms">
                                Aceito os <a href="#" style="color: var(--primary);">Termos de Uso</a> e
                                <a href="#" style="color: var(--primary);">Política de Privacidade</a>
                            </label>
                        </div>

                        <div class="d-flex gap-2 justify-content-between">
                            <button type="button" class="btn btn-secondary" onclick="prevStep(2)">
                                <i class="bi bi-arrow-left me-2"></i> Voltar
                            </button>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-check-circle me-2"></i> Criar Conta
                            </button>
                        </div>
                    </div>
                </form>

                <div class="back-link">
                    Já tem uma conta? <a href="login">Fazer login</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- jQuery Mask Plugin -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>

    <script>
        $(document).ready(function () {
            // Máscaras
            $('#cnpj').mask('00.000.000/0000-00');
            $('#phone').mask('(00) 0000-00009');
            $('#mobile').mask('(00) 00000-0000');
            $('#zip_code').mask('00000-000');

            // Seleção de plano
            $('.plan-card').on('click', function () {
                $('.plan-card').removeClass('selected');
                $(this).addClass('selected');
                $(this).find('input[type="radio"]').prop('checked', true);
            });

            // Preview do subdomínio
            let checkTimeout;
            $('#subdomain').on('input', function () {
                let subdomain = $(this).val().toLowerCase().replace(/[^a-z0-9-]/g, '');
                $(this).val(subdomain);

                if (subdomain.length >= 3) {
                    clearTimeout(checkTimeout);
                    checkTimeout = setTimeout(function () {
                        checkSubdomainAvailability(subdomain);
                    }, 500);
                }
            });

            // Buscar CNPJ automaticamente no blur
            $('#cnpj').on('blur', function () {
                const cnpj = $(this).val().replace(/\D/g, '');
                if (cnpj.length === 14) {
                    buscarCNPJ();
                }
            });

            // Buscar CEP automaticamente no blur
            $('#zip_code').on('blur', function () {
                const cep = $(this).val().replace(/\D/g, '');
                if (cep.length === 8) {
                    buscarCEP(cep);
                }
            });
        });

        function nextStep(step) {
            // Validar etapa atual antes de avançar
            const currentSection = $('.form-section.active');
            const inputs = currentSection.find('input[required], select[required]');
            let valid = true;

            inputs.each(function () {
                if (!this.checkValidity()) {
                    valid = false;
                    $(this).addClass('is-invalid');
                } else {
                    $(this).removeClass('is-invalid');
                }
            });

            if (!valid) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Atenção',
                    text: 'Preencha todos os campos obrigatórios antes de continuar'
                });
                return;
            }

            // Atualizar indicadores
            $('.step').removeClass('active');
            $(`.step[data-step="${step}"]`).addClass('active');

            // Mostrar seção
            $('.form-section').removeClass('active');
            $(`.form-section[data-section="${step}"]`).addClass('active');

            // Scroll para o topo
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }

        function prevStep(step) {
            $('.step').removeClass('active');
            $(`.step[data-step="${step}"]`).addClass('active');

            $('.form-section').removeClass('active');
            $(`.form-section[data-section="${step}"]`).addClass('active');

            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }

        async function buscarCNPJ() {
            const cnpj = $('#cnpj').val().replace(/\D/g, '');

            if (cnpj.length !== 14) {
                Swal.fire({
                    icon: 'warning',
                    title: 'CNPJ Inválido',
                    text: 'Digite um CNPJ válido com 14 dígitos'
                });
                return;
            }

            $('#cnpjLoading').addClass('show');
            $('#cnpjSuccess').removeClass('show');

            try {
                const response = await $.ajax({
                    url: `https://www.receitaws.com.br/v1/cnpj/${cnpj}`,
                    type: 'GET',
                    dataType: 'jsonp'
                });

                if (response.status === 'ERROR') {
                    $('#cnpjLoading').removeClass('show');
                    Swal.fire({
                        icon: 'error',
                        title: 'Erro',
                        text: response.message || 'CNPJ não encontrado'
                    });
                    return;
                }

                // Preencher campos automaticamente
                $('#company_name').val(response.nome || '');
                $('#trade_name').val(response.fantasia || response.nome || '');
                $('#email').val(response.email || '');
                $('#phone').val(response.telefone || '');
                $('#zip_code').val(response.cep ? response.cep.replace(/\D/g, '').replace(/(\d{5})(\d{3})/, '$1-$2') :
                    '');
                $('#address').val(response.logradouro || '');
                $('#numero').val(response.numero || '');
                $('#complemento').val(response.complemento || '');
                $('#bairro').val(response.bairro || '');
                $('#city').val(response.municipio || '');
                $('#state').val(response.uf || '');

                $('#cnpjLoading').removeClass('show');
                $('#cnpjSuccess').addClass('show');

                Swal.fire({
                    icon: 'success',
                    title: 'Dados Encontrados!',
                    text: 'Os dados da empresa foram preenchidos automaticamente',
                    timer: 2000,
                    showConfirmButton: false
                });

            } catch (error) {
                $('#cnpjLoading').removeClass('show');
                Swal.fire({
                    icon: 'error',
                    title: 'Erro na Consulta',
                    text: 'Não foi possível buscar os dados do CNPJ. Preencha manualmente.'
                });
            }
        }

        async function buscarCEP(cep) {
            try {
                const response = await $.ajax({
                    url: `https://viacep.com.br/ws/${cep}/json/`,
                    type: 'GET',
                    dataType: 'json'
                });

                if (!response.erro) {
                    $('#address').val(response.logradouro || '');
                    $('#bairro').val(response.bairro || '');
                    $('#city').val(response.localidade || '');
                    $('#state').val(response.uf || '');
                    $('#numero').focus();
                }
            } catch (error) {
                console.error('Erro ao buscar CEP:', error);
            }
        }

        function checkSubdomainAvailability(subdomain) {
            $.ajax({
                url: 'check-subdomain',
                type: 'POST',
                data: {
                    subdomain
                },
                dataType: 'json',
                success: function (response) {
                    const checkDiv = $('#availabilityCheck');
                    if (response.data.available) {
                        checkDiv.html(
                            '<small style="color: #28a745;"><i class="bi bi-check-circle me-1"></i>Disponível!</small>'
                        ).show();
                    } else {
                        checkDiv.html(
                            '<small style="color: #dc3545;"><i class="bi bi-x-circle me-1"></i>Não disponível</small>'
                        ).show();
                    }
                }
            });
        }

        // Submit do formulário
        $('#registerForm').on('submit', function (e) {
            e.preventDefault();

            const formData = {
                company_name: $('#company_name').val(),
                trade_name: $('#trade_name').val(),
                cnpj: $('#cnpj').val().replace(/\D/g, ''),
                email: $('#email').val(),
                phone: $('#phone').val(),
                mobile: $('#mobile').val(),
                zip_code: $('#zip_code').val(),
                address: $('#address').val(),
                numero: $('#numero').val(),
                complemento: $('#complemento').val(),
                bairro: $('#bairro').val(),
                city: $('#city').val(),
                state: $('#state').val(),
                subdomain: $('#subdomain').val(),
                name: $('#name').val(),
                password: $('#password').val(),
                password_confirmation: $('#password_confirmation').val(),
                plan: $('input[name="plan"]:checked').val()
            };

            // Validar senhas
            if (formData.password !== formData.password_confirmation) {
                Swal.fire({
                    icon: 'error',
                    title: 'Erro',
                    text: 'As senhas não coincidem'
                });
                return;
            }

            // Mostra loading
            Swal.fire({
                title: 'Criando sua conta...',
                html: 'Configurando sua empresa no sistema<br><small>Isso pode levar alguns segundos</small>',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            $.ajax({
                url: 'register',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Conta Criada com Sucesso!',
                            html: `
                            <p class="mb-2">${response.message}</p>
                            <p class="text-muted">Redirecionando para seu sistema...</p>
                        `,
                            showConfirmButton: false,
                            timer: 3000
                        }).then(() => {
                            window.location.href = response.data.redirect;
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Erro',
                            text: response.message
                        });
                    }
                },
                error: function (xhr) {
                    const response = xhr.responseJSON;
                    let errorMessage = response?.message || 'Erro ao criar conta';

                    if (response?.errors && Object.keys(response.errors).length > 0) {
                        let errorList = '<ul style="text-align: left;">';
                        for (let field in response.errors) {
                            response.errors[field].forEach(err => {
                                errorList += `<li>${err}</li>`;
                            });
                        }
                        errorList += '</ul>';

                        Swal.fire({
                            icon: 'error',
                            title: 'Erro de Validação',
                            html: errorList
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Erro',
                            text: errorMessage
                        });
                    }
                }
            });
        });
    </script>
</body>

</html>