<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Crear cuenta — ContaApp</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    body {
      background: #0f1623;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: 'Segoe UI', system-ui, sans-serif;
      padding: 24px 0;
    }
    .auth-wrap { width: 100%; max-width: 480px; padding: 16px; }

    .brand-icon {
      width: 48px; height: 48px; border-radius: 14px;
      background: linear-gradient(135deg,#4f86f7,#3a6fd8);
      display: flex; align-items: center; justify-content: center;
      font-size: 1.25rem; color: #fff;
      margin: 0 auto 12px;
    }

    .auth-card {
      background: #162038;
      border: 1px solid rgba(255,255,255,.08);
      border-radius: 18px;
      padding: 32px 36px 28px;
      box-shadow: 0 20px 60px rgba(0,0,0,.5);
    }
    .auth-card h2 { font-size: 1.2rem; font-weight: 700; color: #e2e8f0; margin-bottom: 4px; }
    .auth-card .sub { font-size: .83rem; color: #64748b; margin-bottom: 24px; }

    .form-label { font-size: .82rem; font-weight: 600; color: #94a3b8; }
    .form-control, .form-select {
      background: #1e2d45; border-color: #2d4a6e; color: #e2e8f0;
      border-radius: 10px; font-size: .875rem; padding: 9px 13px;
    }
    .form-control::placeholder { color: #4a6582; }
    .form-select option { background: #1e2d45; color: #e2e8f0; }
    .form-control:focus, .form-select:focus {
      background: #1e2d45; border-color: #4f86f7; color: #e2e8f0;
      box-shadow: 0 0 0 3px rgba(79,134,247,.2);
    }
    .form-text { color: #475569 !important; }

    /* Empresa toggle */
    .modo-tabs { display: flex; gap: 8px; margin-bottom: 14px; }
    .modo-tab {
      flex: 1; padding: 9px 12px; border-radius: 10px;
      border: 2px solid #2d4a6e; background: #1e2d45;
      text-align: center; font-size: .83rem; font-weight: 600;
      color: #64748b; cursor: pointer; transition: all .15s;
    }
    .modo-tab.active {
      border-color: #4f86f7; background: #1a3a6e; color: #93c5fd;
    }
    .modo-panel { display: none; }
    .modo-panel.active { display: block; }

    .section-label {
      font-size: .7rem; font-weight: 700; text-transform: uppercase;
      letter-spacing: .8px; color: #475569; margin: 20px 0 10px;
    }
    hr.soft { border-color: rgba(255,255,255,.06); margin: 20px 0; }

    .btn-primary {
      background: #4f86f7; border-color: #4f86f7;
      border-radius: 10px; font-weight: 600;
      padding: 10px; font-size: .9rem;
    }
    .btn-primary:hover { background: #3a6fd8; border-color: #3a6fd8; }

    .alert-danger {
      border-radius: 10px; border: none;
      background: #3a1515; color: #f87171;
      font-size: .85rem; padding: 10px 14px;
    }
    .alert-success {
      border-radius: 10px; border: none;
      background: #0d3321; color: #4ade80;
      font-size: .85rem; padding: 10px 14px;
    }
    .link-muted { color: #64748b; font-size: .83rem; text-decoration: none; }
    .link-primary { color: #4f86f7; font-size: .83rem; font-weight: 600; text-decoration: none; }
    .link-primary:hover { text-decoration: underline; }
    .divider { border-top: 1px solid rgba(255,255,255,.08); margin: 20px 0; }

    /* Info box sin empresa */
    .rounded-3[style*="background:#f8fafc"] {
      background: #1e2d45 !important;
      border-color: #2d4a6e !important;
      color: #64748b !important;
    }
  </style>
</head>
<body>
<div class="auth-wrap">

  <div class="text-center mb-4">
    <div class="brand-icon"><i class="bi bi-building"></i></div>
    <h1 class="text-white fw-bold mb-0" style="font-size:1.5rem">ContaApp</h1>
    <p class="text-muted small mt-1">Crea tu cuenta y empresa</p>
  </div>

  <div class="auth-card">
    <h2>Nueva cuenta</h2>
    <p class="sub">Elige un usuario, contraseña y empresa</p>

    {% with msgs = get_flashed_messages(with_categories=true) %}
      {% for cat, msg in msgs %}
      <div class="alert-{{ cat }} mb-3 rounded-3 p-2 px-3 small">{{ msg }}</div>
      {% endfor %}
    {% endwith %}

    {% if error %}
    <div class="alert-danger mb-3">
      <i class="bi bi-exclamation-circle me-1"></i>{{ error }}
    </div>
    {% endif %}

    <form method="post" id="formRegistro">

      <!-- Usuario y contraseña -->
      <div class="section-label"><i class="bi bi-person me-1"></i>Datos de acceso</div>
      <div class="mb-3">
        <label class="form-label">Nombre de usuario *</label>
        <input type="text" name="username" class="form-control" required
               placeholder="tu_usuario"
               value="{{ request.form.get('username', '') }}"
               pattern="[a-zA-Z0-9_\-\.]{3,30}"
               title="3-30 caracteres: letras, números, _ - .">
        <div class="form-text text-muted" style="font-size:.75rem">
          3-30 caracteres. Solo letras, números y _ - .
        </div>
      </div>
      <div class="row g-2 mb-1">
        <div class="col-6">
          <label class="form-label">Contraseña *</label>
          <input type="password" name="password" id="pw1" class="form-control"
                 placeholder="mín. 6 caracteres" required minlength="6">
        </div>
        <div class="col-6">
          <label class="form-label">Repetir contraseña *</label>
          <input type="password" name="confirm" id="pw2" class="form-control"
                 placeholder="igual que arriba" required>
        </div>
      </div>
      <div id="pwError" class="text-danger small mb-3" style="display:none">
        Las contraseñas no coinciden.
      </div>

      <!-- Empresa -->
      <hr class="soft">
      <div class="section-label"><i class="bi bi-building me-1"></i>Empresa</div>

      <div class="modo-tabs">
        <div class="modo-tab {% if modo != 'existente' %}active{% endif %}"
             onclick="setModo('nueva')">
          <i class="bi bi-plus-circle me-1"></i>Crear empresa
        </div>
        <div class="modo-tab {% if modo == 'existente' %}active{% endif %}"
             onclick="setModo('existente')">
          <i class="bi bi-people me-1"></i>Unirse a empresa
        </div>
      </div>
      <input type="hidden" name="modo" id="modoInput"
             value="{{ modo if modo == 'existente' else 'nueva' }}">

      <!-- Panel: nueva empresa -->
      <div class="modo-panel {% if modo != 'existente' %}active{% endif %}" id="panel-nueva">
        <label class="form-label">Nombre de la empresa *</label>
        <input type="text" name="empresa_nueva" class="form-control"
               placeholder="Ej: Acme S.L."
               value="{{ request.form.get('empresa_nueva', '') }}">
        <div class="form-text text-muted" style="font-size:.75rem">
          Se creará una nueva empresa con sus propios datos.
        </div>
      </div>

      <!-- Panel: unirse a empresa existente -->
      <div class="modo-panel {% if modo == 'existente' %}active{% endif %}" id="panel-existente">
        {% if empresas %}
        <label class="form-label">Selecciona la empresa *</label>
        <select name="empresa_existente" class="form-select">
          <option value="">— Selecciona —</option>
          {% for e in empresas %}
          <option value="{{ e.id }}"
            {% if request.form.get('empresa_existente') == e.id|string %}selected{% endif %}>
            {{ e.nombre }}
          </option>
          {% endfor %}
        </select>
        <div class="form-text text-muted" style="font-size:.75rem">
          Tu cuenta compartirá los datos de esa empresa.
        </div>
        {% else %}
        <div class="text-muted small p-3 rounded-3" style="background:#f8fafc;border:1px solid #e2e8f0">
          <i class="bi bi-info-circle me-1"></i>
          Aún no hay empresas. Sé el primero en crear una.
        </div>
        {% endif %}
      </div>

      <div class="mt-4">
        <button type="submit" class="btn btn-primary w-100">
          <i class="bi bi-person-plus me-1"></i>Crear cuenta
        </button>
      </div>
    </form>

    <div class="divider"></div>
    <div class="text-center">
      <span class="link-muted">¿Ya tienes cuenta?</span>
      <a href="{{ url_for('auth.login') }}" class="link-primary ms-1">Inicia sesión</a>
    </div>
  </div>

</div>

<script>
function setModo(m) {
  document.getElementById('modoInput').value = m;
  document.querySelectorAll('.modo-tab').forEach((t, i) => {
    t.classList.toggle('active', (m === 'nueva' && i === 0) || (m === 'existente' && i === 1));
  });
  document.getElementById('panel-nueva').classList.toggle('active', m === 'nueva');
  document.getElementById('panel-existente').classList.toggle('active', m === 'existente');
}

// Password match check
const pw1 = document.getElementById('pw1');
const pw2 = document.getElementById('pw2');
const pwErr = document.getElementById('pwError');
function checkPw() {
  const mismatch = pw2.value && pw1.value !== pw2.value;
  pwErr.style.display = mismatch ? 'block' : 'none';
  pw2.setCustomValidity(mismatch ? 'no coincide' : '');
}
pw1.addEventListener('input', checkPw);
pw2.addEventListener('input', checkPw);
</script>
</body>
</html>
