<h2>Unirse a Nebusa</h2>

<div class="auth-layout">
    <section class="card">
        <div class="card-header">
            <h3>Crear cuenta en España</h3>
            <div class="logo">🌌</div>
        </div>

        <?php if (isset($_SESSION['flash'])): ?>
            <div class="alert alert-error">
                <div class="alert-icon">⚠️</div>
                <div class="alert-content">
                    <p><?php echo htmlspecialchars($_SESSION['flash']); ?></p>
                </div>
            </div>
            <?php unset($_SESSION['flash']); ?>
        <?php endif; ?>

        <form method="post" action="<?php echo htmlspecialchars(base_url('/register')); ?>" class="auth-form" id="registerForm">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            
            <!-- Información Personal -->
            <div class="form-section">
                <h4 class="section-title">Información personal</h4>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="first_name" class="form-label">Nombre *</label>
                        <input 
                            type="text" 
                            name="first_name" 
                            id="first_name"
                            required 
                            minlength="2" 
                            maxlength="50" 
                            pattern="[A-Za-zÁÉÍÓÚÜÑáéíóúüñ\s'-]+"
                            class="form-input"
                            placeholder="Tu nombre"
                            value="<?php echo isset($_SESSION['old']['first_name']) ? htmlspecialchars($_SESSION['old']['first_name']) : ''; ?>"
                        >
                        <div class="form-hint">Solo letras y espacios</div>
                    </div>

                    <div class="form-group">
                        <label for="last_name" class="form-label">Apellidos *</label>
                        <input 
                            type="text" 
                            name="last_name" 
                            id="last_name"
                            required 
                            minlength="2" 
                            maxlength="70" 
                            pattern="[A-Za-zÁÉÍÓÚÜÑáéíóúüñ\s'-]+"
                            class="form-input"
                            placeholder="Tus apellidos"
                            value="<?php echo isset($_SESSION['old']['last_name']) ? htmlspecialchars($_SESSION['old']['last_name']) : ''; ?>"
                        >
                        <div class="form-hint">Solo letras y espacios</div>
                    </div>

                    <div class="form-group">
                        <label for="nick" class="form-label">Nombre de usuario *</label>
                        <input 
                            type="text" 
                            name="nick" 
                            id="nick"
                            required 
                            minlength="3" 
                            maxlength="20" 
                            pattern="[A-Za-z0-9._]+"
                            class="form-input"
                            placeholder="tu_usuario"
                            value="<?php echo isset($_SESSION['old']['nick']) ? htmlspecialchars($_SESSION['old']['nick']) : ''; ?>"
                        >
                        <div class="form-hint">Solo letras, números, . y _</div>
                    </div>

                    <div class="form-group">
                        <label for="dob" class="form-label">Fecha de nacimiento *</label>
                        <input 
                            type="date" 
                            name="dob" 
                            id="dob"
                            required 
                            class="form-input"
                            max="<?php echo date('Y-m-d', strtotime('-16 years')); ?>"
                            min="<?php echo date('Y-m-d', strtotime('-120 years')); ?>"
                            value="<?php echo isset($_SESSION['old']['dob']) ? htmlspecialchars($_SESSION['old']['dob']) : ''; ?>"
                        >
                        <div class="form-hint">Debes tener al menos 16 años (LOPDGDD)</div>
                    </div>
                </div>
            </div>

            <!-- Ubicación -->
            <div class="form-section">
                <h4 class="section-title">Ubicación en España</h4>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="province_code" class="form-label">Provincia *</label>
                        <select name="province_code" id="province_code" required class="form-select" disabled>
                            <option value="">Cargando provincias...</option>
                        </select>
                        <div class="form-hint">Selecciona tu provincia</div>
                    </div>

                    <div class="form-group">
                        <label for="municipality_code" class="form-label">Municipio *</label>
                        <select name="municipality_code" id="municipality_code" required class="form-select" disabled>
                            <option value="">Primero selecciona una provincia</option>
                        </select>
                        <div class="form-hint">Selecciona tu municipio</div>
                    </div>
                </div>
            </div>

            <!-- Credenciales -->
            <div class="form-section">
                <h4 class="section-title">Credenciales de acceso</h4>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="email" class="form-label">Email *</label>
                        <input 
                            type="email" 
                            name="email" 
                            id="email"
                            required 
                            class="form-input"
                            placeholder="tu@email.com"
                            autocomplete="email"
                            value="<?php echo isset($_SESSION['old']['email']) ? htmlspecialchars($_SESSION['old']['email']) : ''; ?>"
                        >
                        <div class="form-hint">Usaremos este email para contactarte</div>
                    </div>

                    <div class="form-group">
                        <label for="email2" class="form-label">Confirmar email *</label>
                        <input 
                            type="email" 
                            name="email2" 
                            id="email2"
                            required 
                            class="form-input"
                            placeholder="confirma@tu.email"
                            autocomplete="email"
                            value="<?php echo isset($_SESSION['old']['email2']) ? htmlspecialchars($_SESSION['old']['email2']) : ''; ?>"
                        >
                        <div class="form-hint">Repite tu email para verificar</div>
                    </div>

                    <div class="form-group">
                        <label for="password" class="form-label">Contraseña *</label>
                        <div class="password-input-container">
                            <input 
                                type="password" 
                                name="password" 
                                id="password"
                                required 
                                class="form-input"
                                placeholder="••••••••"
                                autocomplete="new-password"
                                minlength="8"
                                pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$"
                                title="La contraseña debe contener al menos una mayúscula, una minúscula y un número"
                            >
                            <button type="button" class="password-toggle" id="passwordToggle">👁️</button>
                        </div>
                        <div class="password-strength" id="passwordStrength">
                            <div class="strength-bar"></div>
                            <div class="strength-text">Seguridad de la contraseña</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="password2" class="form-label">Confirmar contraseña *</label>
                        <div class="password-input-container">
                            <input 
                                type="password" 
                                name="password2" 
                                id="password2"
                                required 
                                class="form-input"
                                placeholder="••••••••"
                                autocomplete="new-password"
                                minlength="8"
                            >
                            <button type="button" class="password-toggle" id="passwordToggle2">👁️</button>
                        </div>
                        <div class="form-hint">Las contraseñas deben coincidir</div>
                    </div>
                </div>
            </div>

            <!-- Invitación -->
            <?php if (env('APP_INVITES', 'off') === 'on'): ?>
            <div class="form-section">
                <h4 class="section-title">Código de invitación</h4>
                <div class="form-group">
                    <label for="invite_code" class="form-label">Código de invitación *</label>
                    <input 
                        type="text" 
                        name="invite_code" 
                        id="invite_code"
                        required 
                        minlength="6" 
                        maxlength="32" 
                        class="form-input"
                        placeholder="Ej: AB3D9K2P"
                        value="<?php echo isset($_SESSION['old']['invite_code']) ? htmlspecialchars($_SESSION['old']['invite_code']) : ''; ?>"
                    >
                    <div class="form-hint">Necesitas un código de invitación para registrarte</div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Consentimientos Legales -->
            <div class="form-section">
                <h4 class="section-title">Consentimientos legales</h4>
                
                <div class="form-group checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="accept_terms" id="accept_terms" required>
                        <span class="checkmark"></span>
                        <span class="checkbox-text">
                            He leído y acepto los <a href="<?php echo htmlspecialchars(base_url('/terms')); ?>" target="_blank" rel="noopener noreferrer">Términos de Servicio</a> *
                        </span>
                    </label>
                </div>

                <div class="form-group checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="accept_privacy" id="accept_privacy" required>
                        <span class="checkmark"></span>
                        <span class="checkbox-text">
                            He leído y acepto la <a href="<?php echo htmlspecialchars(base_url('/privacy')); ?>" target="_blank" rel="noopener noreferrer">Política de Privacidad</a> y doy mi consentimiento para el tratamiento de mis datos según el RGPD *
                        </span>
                    </label>
                </div>

                <div class="form-group checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="accept_cookies" id="accept_cookies" required>
                        <span class="checkmark"></span>
                        <span class="checkbox-text">
                            Acepto el uso de <a href="<?php echo htmlspecialchars(base_url('/cookies')); ?>" target="_blank" rel="noopener noreferrer">cookies necesarias</a> para el funcionamiento del sitio *
                        </span>
                    </label>
                </div>

                <div class="form-group checkbox-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="commercial_comm" id="commercial_comm">
                        <span class="checkmark"></span>
                        <span class="checkbox-text">
                            Acepto recibir comunicaciones comerciales y promocionales por email (opcional)
                        </span>
                    </label>
                </div>

                <div class="legal-notice">
                    <p><small>
                        * Campos obligatorios. De acuerdo con la <strong>LOPDGDD</strong>, debes tener al menos <strong>16 años</strong> para registrarte. 
                        Puedes ejercer tus derechos ARCO (Acceso, Rectificación, Cancelación, Oposición) contactando con nosotros.
                    </small></p>
                </div>
            </div>

            <!-- Submit -->
            <div class="form-actions">
                <button type="submit" class="btn btn-primary btn-full" id="submitBtn">
                    <span class="btn-text">Crear cuenta en Nebusa</span>
                    <span class="btn-loading hidden">⏳ Creando cuenta...</span>
                </button>
                
                <div class="auth-footer">
                    <p>¿Ya tienes cuenta? 
                        <a href="<?php echo htmlspecialchars(base_url('/login')); ?>" class="text-link">
                            Inicia sesión
                        </a>
                    </p>
                </div>
            </div>
        </form>
    </section>
</div>

<!-- Incluir el script de ubicaciones -->
<script src="/public/assets/js/location-selector.js"></script>

<style>
.auth-layout {
    max-width: 800px;
    margin: 2rem auto;
    padding: 0 1rem;
}

.card {
    background: #1a1a1a;
    border-radius: 12px;
    padding: 2rem;
    border: 1px solid #333;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #333;
}

.card-header h3 {
    margin: 0;
    color: #ffffff;
    font-size: 1.5rem;
    font-weight: 600;
}

.logo {
    font-size: 1.5rem;
}

.alert {
    display: flex;
    gap: 0.75rem;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
    align-items: flex-start;
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: #ef4444;
}

.alert-icon {
    font-size: 1.25rem;
    flex-shrink: 0;
}

.alert-content {
    flex: 1;
}

.alert-content p {
    margin: 0;
    font-size: 0.9rem;
}

.form-section {
    margin-bottom: 2rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid #333;
}

.section-title {
    color: #ffffff;
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0 0 1rem 0;
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

.auth-form {
    display: flex;
    flex-direction: column;
    gap: 0;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.form-label {
    color: #ffffff;
    font-weight: 600;
    font-size: 0.9rem;
}

.form-input, .form-select {
    background: #2d2d2d;
    border: 1px solid #404040;
    border-radius: 8px;
    padding: 0.75rem;
    color: #ffffff;
    font-size: 1rem;
    transition: all 0.2s ease;
    width: 100%;
    box-sizing: border-box;
}

.form-input:focus, .form-select:focus {
    outline: none;
    border-color: #6366f1;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.form-input:invalid:not(:focus):not(:placeholder-shown) {
    border-color: #ef4444;
}

.form-select:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.form-hint {
    font-size: 0.75rem;
    color: #6b7280;
    margin-top: 0.25rem;
}

.password-input-container {
    position: relative;
    display: flex;
    align-items: center;
}

.password-toggle {
    position: absolute;
    right: 0.75rem;
    background: none;
    border: none;
    color: #9ca3af;
    cursor: pointer;
    padding: 0.25rem;
    border-radius: 4px;
    transition: color 0.2s ease;
}

.password-toggle:hover {
    color: #ffffff;
    background: rgba(255, 255, 255, 0.1);
}

.password-strength {
    margin-top: 0.5rem;
}

.strength-bar {
    height: 4px;
    background: #4b5563;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: 0.25rem;
}

.strength-bar::before {
    content: '';
    display: block;
    height: 100%;
    width: 0%;
    background: #ef4444;
    transition: all 0.3s ease;
    border-radius: 2px;
}

.strength-bar.weak::before {
    width: 25%;
    background: #ef4444;
}

.strength-bar.medium::before {
    width: 50%;
    background: #f59e0b;
}

.strength-bar.strong::before {
    width: 75%;
    background: #10b981;
}

.strength-bar.very-strong::before {
    width: 100%;
    background: #059669;
}

.strength-text {
    font-size: 0.7rem;
    color: #6b7280;
}

.checkbox-group {
    margin: 0.75rem 0;
}

.checkbox-label {
    display: flex;
    align-items: flex-start;
    gap: 0.75rem;
    cursor: pointer;
    color: #d1d5db;
    font-size: 0.9rem;
    line-height: 1.4;
}

.checkbox-label input[type="checkbox"] {
    display: none;
}

.checkmark {
    width: 20px;
    height: 20px;
    border: 2px solid #4b5563;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    flex-shrink: 0;
    margin-top: 0.1rem;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark {
    background: #6366f1;
    border-color: #6366f1;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark::after {
    content: "✓";
    color: white;
    font-size: 12px;
    font-weight: bold;
}

.checkbox-text a {
    color: #6366f1;
    text-decoration: none;
}

.checkbox-text a:hover {
    text-decoration: underline;
}

.legal-notice {
    margin-top: 1.5rem;
    padding: 1rem;
    background: rgba(59, 130, 246, 0.1);
    border: 1px solid rgba(59, 130, 246, 0.3);
    border-radius: 8px;
}

.legal-notice p {
    margin: 0;
    color: #93c5fd;
    font-size: 0.8rem;
    line-height: 1.4;
}

.legal-notice strong {
    color: #ffffff;
}

.form-actions {
    margin-top: 2rem;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 1rem;
    gap: 0.5rem;
}

.btn-primary {
    background: #6366f1;
    color: white;
}

.btn-primary:hover:not(:disabled) {
    background: #5b5cdc;
    transform: translateY(-1px);
}

.btn-primary:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.btn-full {
    width: 100%;
    margin-bottom: 1rem;
}

.auth-footer {
    text-align: center;
    color: #9ca3af;
}

.auth-footer p {
    margin: 0;
}

.text-link {
    color: #6366f1;
    text-decoration: none;
}

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

.hidden {
    display: none !important;
}

.loading {
    opacity: 0.6;
    cursor: not-allowed;
}

/* Estilos para selects cuando están habilitados */
.form-select:not(:disabled) {
    cursor: pointer;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%239ca3af'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 0.75rem center;
    background-size: 1rem;
    padding-right: 2.5rem;
}

.form-select:not(:disabled):hover {
    border-color: #6366f1;
}

/* Estilos para las opciones del select */
.form-select option {
    background: #2d2d2d;
    color: #ffffff;
    padding: 0.5rem;
}

/* Responsive */
@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .card {
        padding: 1.5rem;
    }
}

@media (max-width: 480px) {
    .auth-layout {
        margin: 1rem auto;
    }
    
    .card {
        padding: 1rem;
    }
    
    .legal-notice {
        padding: 0.75rem;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const passwordToggle = document.getElementById('passwordToggle');
    const passwordToggle2 = document.getElementById('passwordToggle2');
    const passwordInput = document.getElementById('password');
    const passwordInput2 = document.getElementById('password2');
    const passwordStrength = document.getElementById('passwordStrength');
    const strengthBar = passwordStrength ? passwordStrength.querySelector('.strength-bar') : null;
    const strengthText = passwordStrength ? passwordStrength.querySelector('.strength-text') : null;
    const submitBtn = document.getElementById('submitBtn');
    const btnText = submitBtn ? submitBtn.querySelector('.btn-text') : null;
    const btnLoading = submitBtn ? submitBtn.querySelector('.btn-loading') : null;

    // Toggle password visibility
    if (passwordToggle && passwordToggle2) {
        [passwordToggle, passwordToggle2].forEach((toggle, index) => {
            toggle.addEventListener('click', function() {
                const targetInput = index === 0 ? passwordInput : passwordInput2;
                if (targetInput) {
                    const type = targetInput.getAttribute('type') === 'password' ? 'text' : 'password';
                    targetInput.setAttribute('type', type);
                    this.textContent = type === 'password' ? '👁️' : '🔒';
                }
            });
        });
    }

    // Password strength meter
    if (passwordInput && strengthBar && strengthText) {
        passwordInput.addEventListener('input', function() {
            const password = this.value;
            let strength = 0;
            let text = 'Muy débil';

            if (password.length >= 8) strength += 1;
            if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength += 1;
            if (password.match(/\d/)) strength += 1;
            if (password.match(/[^a-zA-Z\d]/)) strength += 1;

            // Actualizar barra y texto
            strengthBar.className = 'strength-bar';
            if (password.length === 0) {
                text = 'Seguridad de la contraseña';
            } else if (strength <= 1) {
                strengthBar.classList.add('weak');
                text = 'Muy débil';
            } else if (strength === 2) {
                strengthBar.classList.add('medium');
                text = 'Débil';
            } else if (strength === 3) {
                strengthBar.classList.add('strong');
                text = 'Buena';
            } else {
                strengthBar.classList.add('very-strong');
                text = 'Muy fuerte';
            }
            
            strengthText.textContent = text;
        });
    }

    // Validación de confirmación de contraseña
    if (passwordInput2) {
        passwordInput2.addEventListener('input', function() {
            if (this.value && passwordInput && this.value !== passwordInput.value) {
                this.style.borderColor = '#ef4444';
            } else {
                this.style.borderColor = '#404040';
            }
        });
    }

    // Validación de email
    const email2Input = document.getElementById('email2');
    const email1Input = document.getElementById('email');
    if (email2Input && email1Input) {
        email2Input.addEventListener('input', function() {
            const email1 = email1Input.value;
            if (this.value && this.value !== email1) {
                this.style.borderColor = '#ef4444';
            } else {
                this.style.borderColor = '#404040';
            }
        });
    }

    // Form submission
    if (registerForm && submitBtn && btnText && btnLoading) {
        registerForm.addEventListener('submit', function(e) {
            // Validar contraseñas
            if (passwordInput && passwordInput2 && passwordInput.value !== passwordInput2.value) {
                e.preventDefault();
                alert('Las contraseñas no coinciden.');
                return;
            }

            // Validar emails
            const email1 = document.getElementById('email');
            const email2 = document.getElementById('email2');
            if (email1 && email2 && email1.value !== email2.value) {
                e.preventDefault();
                alert('Los emails no coinciden.');
                return;
            }

            // Validar términos obligatorios
            const acceptTerms = document.getElementById('accept_terms');
            const acceptPrivacy = document.getElementById('accept_privacy');
            const acceptCookies = document.getElementById('accept_cookies');
            
            if ((acceptTerms && !acceptTerms.checked) || 
                (acceptPrivacy && !acceptPrivacy.checked) || 
                (acceptCookies && !acceptCookies.checked)) {
                e.preventDefault();
                alert('Debes aceptar todos los consentimientos obligatorios marcados con *.');
                return;
            }

            // Validar ubicación (SOLO provincia y municipio)
            const province = document.getElementById('province_code');
            const municipality = document.getElementById('municipality_code');
            
            if (province && municipality && (!province.value || !municipality.value)) {
                e.preventDefault();
                alert('Por favor, completa la información de provincia y municipio.');
                return;
            }

            // Validar edad (16 años)
            const dobInput = document.getElementById('dob');
            if (dobInput && dobInput.value) {
                const birthDate = new Date(dobInput.value);
                const today = new Date();
                const age = today.getFullYear() - birthDate.getFullYear();
                const monthDiff = today.getMonth() - birthDate.getMonth();
                
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                
                if (age < 16) {
                    e.preventDefault();
                    alert('Debes tener al menos 16 años para registrarte según la LOPDGDD.');
                    return;
                }
            }

            // Mostrar estado de carga
            submitBtn.disabled = true;
            btnText.classList.add('hidden');
            btnLoading.classList.remove('hidden');
            registerForm.classList.add('loading');
        });

        // Prevenir envío múltiple
        let formSubmitted = false;
        registerForm.addEventListener('submit', function(e) {
            if (formSubmitted) {
                e.preventDefault();
                return;
            }
            formSubmitted = true;
        });
    }
    
    console.log('✅ Register form JavaScript cargado correctamente');
});
</script>