<?php if (!function_exists('avatar_img')) { @include_once '../../helpers.php'; } ?>
<div class="grid" style="margin-top:40px;max-width:520px;margin-left:auto;margin-right:auto">
  <?php if($m = flash('error')): ?>
    <div class="alert alert-error">
      <i class="fas fa-exclamation-circle"></i>
      <div><?php echo h($m); ?></div>
    </div>
  <?php endif; ?>
  
  <?php if($m = flash('success')): ?>
    <div class="alert alert-success">
      <i class="fas fa-check-circle"></i>
      <div><?php echo h($m); ?></div>
    </div>
  <?php endif; ?>
  
  <form class="card" method="post" id="registerForm">
<?= csrf_field() ?>

    <h2 style="margin-top:0"><i class="fas fa-user-plus"></i> Crear cuenta</h2>
    <div class="muted" style="margin-bottom:16px">Acceso por invitación. Se pedirán datos básicos.</div>
    
    <div class="grid">
      <div>
        <label for="username" style="display:block;margin-bottom:8px;font-weight:500">Nombre de usuario</label>
        <input id="username" name="username" placeholder="Tu nombre de usuario" required minlength="3" maxlength="50">
      </div>
      
      <div>
        <label for="email" style="display:block;margin-bottom:8px;font-weight:500">Email</label>
        <input id="email" name="email" placeholder="tu@email.com" type="email" required>
      </div>
      
      <div>
        <label for="email_confirm" style="display:block;margin-bottom:8px;font-weight:500">Confirmar email</label>
        <input id="email_confirm" name="email_confirm" placeholder="Confirma tu email" type="email" required>
      </div>
      
      <div>
        <label for="birth_date" style="display:block;margin-bottom:8px;font-weight:500">Fecha de nacimiento</label>
        <input id="birth_date" type="date" name="birth_date" required 
               max="<?php echo date('Y-m-d', strtotime('-16 years')); ?>">
        <div class="muted" style="font-size:0.8rem;margin-top:4px">Debes tener al menos 16 años</div>
      </div>
      
      
      <div>
        <label for="gender" style="display:block;margin-bottom:8px;font-weight:500">Género</label>
        <select id="gender" name="gender" required>
          <option value="">Selecciona</option>
          <option value="male">Hombre</option>
          <option value="female">Mujer</option>
          <option value="other">Otro</option>
        </select>
      </div>

      <div>
        <label for="country" style="display:block;margin-bottom:8px;font-weight:500">País</label>
        <select id="country" name="country" required>
          <option value="">Selecciona país</option>
          <option value="ES">España</option>
          <option value="PT">Portugal</option>
          <option value="FR">Francia</option>
          <option value="IT">Italia</option>
          <option value="DE">Alemania</option>
          <option value="UK">Reino Unido</option>
          <option value="US">Estados Unidos</option>
          <option value="MX">México</option>
          <option value="AR">Argentina</option>
          <option value="CL">Chile</option>
        </select>
      </div>

      <div>
        <label for="region" style="display:block;margin-bottom:8px;font-weight:500">Comunidad / Región</label>
        <select id="region" name="region" required>
          <option value="">Selecciona región</option>
        </select>
      </div>

      <div>
        <label for="city" style="display:block;margin-bottom:8px;font-weight:500">Ciudad</label>
        <input id="city" name="city" placeholder="Tu ciudad" required maxlength="120">
      </div>

      </div>
<div>
        <label for="password" style="display:block;margin-bottom:8px;font-weight:500">Contraseña</label>
        <input id="password" type="password" name="password" placeholder="Mínimo 8 caracteres" required minlength="8">
      </div>
      
      <div>
        <label for="password_confirm" style="display:block;margin-bottom:8px;font-weight:500">Confirmar contraseña</label>
        <input id="password_confirm" type="password" name="password_confirm" placeholder="Repite tu contraseña" required>
      </div>
      
      <div>
        <label for="invite_code" style="display:block;margin-bottom:8px;font-weight:500">Código de invitación</label>
        <input id="invite_code" name="invite_code" placeholder="Código de invitación" required>
      </div>
      
      <button class="btn primary" type="submit"><i class="fas fa-user-plus"></i> Crear cuenta</button>
    </div>
  </form>
  
  <div class="muted" style="margin-top:16px;text-align:center">
    <p>¿Ya tienes cuenta? <a href="./?r=login" style="color:var(--accent);">Inicia sesión aquí</a></p>
    <p>Código de prueba: <b>DEMO-INVITE-1234</b></p>
  </div>
</div>

<script>
document.getElementById('registerForm').addEventListener('submit', function(e) {
  const password = document.getElementById('password');
  const passwordConfirm = document.getElementById('password_confirm');
  const email = document.getElementById('email');
  const emailConfirm = document.getElementById('email_confirm');
  const birthDate = document.getElementById('birth_date');
  
  let errors = [];
  
  if (password.value !== passwordConfirm.value) {
    errors.push('Las contraseñas no coinciden');
    password.focus();
  }
  
  if (email.value !== emailConfirm.value) {
    errors.push('Los emails no coinciden');
    email.focus();
  }
  
  // Validar edad mínima
  const birth = new Date(birthDate.value);
  const today = new Date();
  const age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  
  if (age < 16) {
    errors.push('Debes tener al menos 16 años para registrarte');
    birthDate.focus();
  }
  
  if (errors.length > 0) {
    e.preventDefault();
    alert('Errores:\n' + errors.join('\n'));
    return false;
  }
  
  return true;
});
</script>

<script>
/* FULL COUNTRY & REGION JS */
(function(){
  // Minimal ISO country list (expanded)
  const COUNTRIES = [
    ["ES","España"],["PT","Portugal"],["FR","Francia"],["IT","Italia"],["DE","Alemania"],["UK","Reino Unido"],["IE","Irlanda"],
    ["NL","Países Bajos"],["BE","Bélgica"],["LU","Luxemburgo"],["CH","Suiza"],["AT","Austria"],["PL","Polonia"],
    ["CZ","Chequia"],["SK","Eslovaquia"],["HU","Hungría"],["SI","Eslovenia"],["HR","Croacia"],["BA","Bosnia y Herzegovina"],
    ["RS","Serbia"],["RO","Rumanía"],["BG","Bulgaria"],["GR","Grecia"],["TR","Turquía"],["NO","Noruega"],
    ["SE","Suecia"],["FI","Finlandia"],["DK","Dinamarca"],["EE","Estonia"],["LV","Letonia"],["LT","Lituania"],
    ["US","Estados Unidos"],["CA","Canadá"],["MX","México"],["AR","Argentina"],["CL","Chile"],["CO","Colombia"],
    ["PE","Perú"],["UY","Uruguay"],["PY","Paraguay"],["BO","Bolivia"],["BR","Brasil"],["VE","Venezuela"],
    ["EC","Ecuador"],["CR","Costa Rica"],["PA","Panamá"],["DO","República Dominicana"],["CU","Cuba"],
    ["GB","Reino Unido"],["AU","Australia"],["NZ","Nueva Zelanda"],["JP","Japón"],["CN","China"],["KR","Corea del Sur"],
    ["IN","India"],["AE","Emiratos Árabes"],["SA","Arabia Saudí"],["MA","Marruecos"],["EG","Egipto"],["ZA","Sudáfrica"]
  ];
  // España: Comunidades y ciudades principales (muestra; se puede ampliar)
  const ES_REGIONS = {
    "Andalucía": ["Sevilla","Málaga","Córdoba","Granada","Cádiz","Huelva","Jaén","Almería"],
    "Aragón": ["Zaragoza","Huesca","Teruel"],
    "Asturias": ["Oviedo","Gijón","Avilés"],
    "Baleares": ["Palma","Ibiza","Mahon"],
    "Canarias": ["Las Palmas","Santa Cruz de Tenerife","Arrecife","San Cristóbal de La Laguna"],
    "Cantabria": ["Santander","Torrelavega","Castro-Urdiales"],
    "Castilla-La Mancha": ["Toledo","Albacete","Ciudad Real","Cuenca","Guadalajara"],
    "Castilla y León": ["Valladolid","León","Burgos","Salamanca","Segovia","Soria","Ávila","Palencia","Zamora"],
    "Cataluña": ["Barcelona","Tarragona","Lleida","Girona","Hospitalet de Llobregat","Badalona","Sabadell","Terrassa"],
    "Comunidad Valenciana": ["Valencia","Alicante","Castellón de la Plana","Elche","Gandía","Torrent"],
    "Extremadura": ["Badajoz","Cáceres","Mérida"],
    "Galicia": ["A Coruña","Santiago de Compostela","Vigo","Ourense","Lugo","Pontevedra","Ferrol"],
    "La Rioja": ["Logroño","Calahorra","Arnedo"],
    "Comunidad de Madrid": ["Madrid","Alcalá de Henares","Móstoles","Fuenlabrada","Getafe","Leganés","Alcorcón"],
    "Región de Murcia": ["Murcia","Cartagena","Lorca"],
    "Navarra": ["Pamplona","Tudela","Burlada"],
    "País Vasco": ["Bilbao","Vitoria-Gasteiz","San Sebastián","Barakaldo","Getxo"],
    "Ceuta": ["Ceuta"],
    "Melilla": ["Melilla"]
  };

  const country = document.getElementById('country');
  const region = document.getElementById('region');
  const city   = document.getElementById('city');

  function fillCountries(){
    country.innerHTML = '<option value="">Selecciona país</option>';
    COUNTRIES.forEach(([code,name]) => {
      const o = document.createElement('option'); o.value = code; o.textContent = name; country.appendChild(o);
    });
    // Por defecto España
    if (!country.value) country.value = 'ES';
    handleCountry();
  }
  function handleCountry(){
    region.innerHTML = '<option value="">Selecciona región</option>';
    city.innerHTML = '<option value="">Selecciona ciudad</option>';
    if (country.value === 'ES') {
      region.disabled = false; city.disabled = true;
      Object.keys(ES_REGIONS).forEach(r => {
        const o = document.createElement('option'); o.value = r; o.textContent = r; region.appendChild(o);
      });
    } else {
      // Otros países: región/ciudad opcional deshabilitado (para no bloquear registro)
      region.disabled = true; city.disabled = true;
      region.innerHTML = '<option value="">No aplica</option>';
      city.innerHTML = '<option value="">No aplica</option>';
    }
  }
  function handleRegion(){
    city.innerHTML = '<option value="">Selecciona ciudad</option>';
    if (country.value === 'ES' && ES_REGIONS[region.value]) {
      city.disabled = false;
      ES_REGIONS[region.value].forEach(c => {
        const o = document.createElement('option'); o.value = c; o.textContent = c; city.appendChild(o);
      });
    } else {
      city.disabled = true;
      city.innerHTML = '<option value="">No aplica</option>';
    }
  }

  country.addEventListener('change', handleCountry);
  region.addEventListener('change', handleRegion);
  fillCountries();
})();
</script>
