<div class="container" style="max-width:900px;margin:20px auto;">
  <h2>Editar perfil</h2>
  <?php if (!empty($_SESSION['flash'])): ?>
    <div class="alert"><?php echo htmlspecialchars($_SESSION['flash']); unset($_SESSION['flash']); ?></div>
  <?php endif; ?>
  
  <form method="post" action="<?php echo htmlspecialchars(base_url('/profile/update')); ?>" class="profile-edit-form" id="profileForm">
    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
    
    <section class="card">
      <h3>Cuenta</h3>
      <div class="form-grid">
        <div class="form-group">
          <label class="form-label">Email</label>
          <input type="email" name="email" required value="<?php echo htmlspecialchars($data['email']??''); ?>" class="form-input" id="emailInput">
          <div class="validation-message" id="emailMessage"></div>
        </div>
        <div class="form-group">
          <label class="form-label">Nombre de usuario (Nick)</label>
          <input type="text" name="nick" required pattern="[a-zA-Z0-9_]+" minlength="3" maxlength="30" 
                 value="<?php echo htmlspecialchars($data['nick']??''); ?>" class="form-input" id="nickInput"
                 title="Solo letras, números y guiones bajos. Mínimo 3 caracteres.">
          <div class="validation-message" id="nickMessage"></div>
          <small class="form-hint">Solo letras, números y _. Mínimo 3 caracteres.</small>
        </div>
        <div class="form-group">
          <label class="form-label">Nombre</label>
          <input type="text" name="first_name" value="<?php echo htmlspecialchars($data['first_name']??''); ?>" class="form-input">
        </div>
        <div class="form-group">
          <label class="form-label">Apellidos</label>
          <input type="text" name="last_name" value="<?php echo htmlspecialchars($data['last_name']??''); ?>" class="form-input">
        </div>
      </div>
      
      <div class="password-section">
        <h4>Cambiar contraseña</h4>
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">Contraseña actual</label>
            <input type="password" name="current_password" placeholder="Obligatoria si cambias contraseña" class="form-input">
          </div>
          <div class="form-group">
            <label class="form-label">Nueva contraseña</label>
            <input type="password" name="new_password" minlength="8" class="form-input">
          </div>
          <div class="form-group">
            <label class="form-label">Repetir nueva contraseña</label>
            <input type="password" name="new_password2" minlength="8" class="form-input">
          </div>
        </div>
      </div>
    </section>
    
    <section class="card">
      <h3>Ubicación</h3>
      <div class="form-grid">
        <div class="form-group">
          <label class="form-label">Provincia</label>
          <select name="province_code" id="provinceSelect" class="form-select">
            <option value="">-- Selecciona --</option>
            <?php foreach($provinces as $p): ?>
              <option value="<?php echo htmlspecialchars($p['code']); ?>" <?php echo (!empty($data['province_code']) && $data['province_code']===$p['code'])?'selected':''; ?>>
                <?php echo htmlspecialchars($p['name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Municipio</label>
          <select name="municipality_code" id="municipalitySelect" class="form-select">
            <option value="">-- Selecciona --</option>
            <?php foreach($municipalities as $m): ?>
              <option value="<?php echo htmlspecialchars($m['code']); ?>" <?php echo (!empty($data['municipality_code']) && $data['municipality_code']===$m['code'])?'selected':''; ?>>
                <?php echo htmlspecialchars($m['name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
    </section>
    
    <section class="card">
      <h3>Bio</h3>
      <div class="form-group">
        <textarea name="bio" rows="3" maxlength="300" placeholder="Cuéntanos algo de ti..." class="form-textarea"><?php echo htmlspecialchars($data['bio']??''); ?></textarea>
        <small class="form-hint">Máximo 300 caracteres</small>
      </div>
    </section>
    
    <div class="form-actions">
      <a href="<?php echo htmlspecialchars(base_url('/profile')); ?>" class="btn btn-ghost">Cancelar</a>
      <button class="btn btn-primary" type="submit" id="submitBtn">Guardar cambios</button>
    </div>
  </form>
</div>

<script>
// Variables para controlar el estado de validación
let isEmailValid = true;
let isNickValid = true;
let currentEmail = '<?php echo htmlspecialchars($data['email']??''); ?>';
let currentNick = '<?php echo htmlspecialchars($data['nick']??''); ?>';

// Elementos del DOM
const emailInput = document.getElementById('emailInput');
const nickInput = document.getElementById('nickInput');
const emailMessage = document.getElementById('emailMessage');
const nickMessage = document.getElementById('nickMessage');
const submitBtn = document.getElementById('submitBtn');
const profileForm = document.getElementById('profileForm');

// Función para mostrar mensajes de validación
function showValidationMessage(element, message, type) {
    element.textContent = message;
    element.className = 'validation-message ' + type;
}

// Función para limpiar mensajes de validación
function clearValidationMessage(element) {
    element.textContent = '';
    element.className = 'validation-message';
}

// Función para validar email
async function validateEmail(email) {
    if (email === currentEmail) {
        clearValidationMessage(emailMessage);
        isEmailValid = true;
        updateSubmitButton();
        return;
    }

    if (!email) {
        showValidationMessage(emailMessage, 'El email es obligatorio', 'error');
        isEmailValid = false;
        updateSubmitButton();
        return;
    }

    // Validación básica de formato
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        showValidationMessage(emailMessage, 'Formato de email inválido', 'error');
        isEmailValid = false;
        updateSubmitButton();
        return;
    }

    // Mostrar estado de carga
    showValidationMessage(emailMessage, 'Verificando email...', 'loading');

    try {
        const response = await fetch('<?php echo htmlspecialchars(base_url('/profile/check-email')); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `email=${encodeURIComponent(email)}&_csrf=<?php echo htmlspecialchars(csrf_token()); ?>`
        });

        const result = await response.json();

        if (result.available) {
            showValidationMessage(emailMessage, '✓ Email disponible', 'success');
            isEmailValid = true;
        } else {
            showValidationMessage(emailMessage, '✗ Este email ya está en uso', 'error');
            isEmailValid = false;
        }
    } catch (error) {
        showValidationMessage(emailMessage, 'Error al verificar el email', 'error');
        isEmailValid = false;
    }

    updateSubmitButton();
}

// Función para validar nick
async function validateNick(nick) {
    if (nick === currentNick) {
        clearValidationMessage(nickMessage);
        isNickValid = true;
        updateSubmitButton();
        return;
    }

    if (!nick) {
        showValidationMessage(nickMessage, 'El nombre de usuario es obligatorio', 'error');
        isNickValid = false;
        updateSubmitButton();
        return;
    }

    // Validación de formato
    const nickRegex = /^[a-zA-Z0-9_]+$/;
    if (!nickRegex.test(nick)) {
        showValidationMessage(nickMessage, 'Solo letras, números y guiones bajos', 'error');
        isNickValid = false;
        updateSubmitButton();
        return;
    }

    if (nick.length < 3) {
        showValidationMessage(nickMessage, 'Mínimo 3 caracteres', 'error');
        isNickValid = false;
        updateSubmitButton();
        return;
    }

    // Mostrar estado de carga
    showValidationMessage(nickMessage, 'Verificando nombre de usuario...', 'loading');

    try {
        const response = await fetch('<?php echo htmlspecialchars(base_url('/profile/check-nick')); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `nick=${encodeURIComponent(nick)}&_csrf=<?php echo htmlspecialchars(csrf_token()); ?>`
        });

        const result = await response.json();

        if (result.available) {
            showValidationMessage(nickMessage, '✓ Nombre de usuario disponible', 'success');
            isNickValid = true;
        } else {
            showValidationMessage(nickMessage, '✗ Este nombre de usuario ya está en uso', 'error');
            isNickValid = false;
        }
    } catch (error) {
        showValidationMessage(nickMessage, 'Error al verificar el nombre de usuario', 'error');
        isNickValid = false;
    }

    updateSubmitButton();
}

// Función para actualizar el estado del botón de envío
function updateSubmitButton() {
    if (isEmailValid && isNickValid) {
        submitBtn.disabled = false;
        submitBtn.style.opacity = '1';
        submitBtn.style.cursor = 'pointer';
    } else {
        submitBtn.disabled = true;
        submitBtn.style.opacity = '0.6';
        submitBtn.style.cursor = 'not-allowed';
    }
}

// Event listeners
emailInput.addEventListener('input', debounce(() => {
    validateEmail(emailInput.value.trim());
}, 500));

emailInput.addEventListener('blur', () => {
    validateEmail(emailInput.value.trim());
});

nickInput.addEventListener('input', debounce(() => {
    validateNick(nickInput.value.trim());
}, 500));

nickInput.addEventListener('blur', () => {
    validateNick(nickInput.value.trim());
});

// Función debounce para evitar muchas llamadas API
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Validación inicial al cargar la página
document.addEventListener('DOMContentLoaded', function() {
    validateEmail(emailInput.value.trim());
    validateNick(nickInput.value.trim());
});

// Cargar municipios cuando cambia la provincia
document.getElementById('provinceSelect')?.addEventListener('change', async function(){
    const code = this.value;
    const muni = document.getElementById('municipalitySelect');
    muni.innerHTML = '<option value="">Cargando...</option>';
    
    if (!code) { 
        muni.innerHTML = '<option value="">-- Selecciona --</option>'; 
        return; 
    }
    
    try {
        const res = await fetch('<?php echo htmlspecialchars(base_url('/location/municipalities')); ?>?province='+encodeURIComponent(code));
        const j = await res.json();
        if (j && j.success) {
            muni.innerHTML = '<option value="">-- Selecciona --</option>';
            j.data.forEach(it => {
                const opt = document.createElement('option');
                opt.value = it.code; 
                opt.textContent = it.name;
                muni.appendChild(opt);
            });
        } else {
            muni.innerHTML = '<option value="">-- Error --</option>';
        }
    } catch (error) {
        muni.innerHTML = '<option value="">-- Error --</option>';
        console.error('Error loading municipalities:', error);
    }
});
</script>

<style>
.profile-edit-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.card {
  background: #1a1d23;
  border: 1px solid #2b3138;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.card h3 {
  color: #f8fafc;
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 20px;
  border-bottom: 1px solid #2b3138;
  padding-bottom: 12px;
}

.card h4 {
  color: #cbd5e1;
  font-size: 1rem;
  font-weight: 500;
  margin-bottom: 16px;
}

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

.password-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #2b3138;
}

.password-section h4 {
  color: #cbd5e1;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 0;
  position: relative;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #cbd5e1;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-input, .form-textarea, .form-select {
  width: 100%;
  padding: 12px;
  background: #2b3138;
  border: 1px solid #3f4752;
  border-radius: 8px;
  color: #f8fafc;
  font-size: 0.9rem;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

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

.form-textarea {
  resize: vertical;
  min-height: 100px;
  font-family: inherit;
}

.form-hint {
  display: block;
  color: #64748b;
  font-size: 0.8rem;
  margin-top: 6px;
}

.validation-message {
  font-size: 0.8rem;
  margin-top: 6px;
  padding: 4px 8px;
  border-radius: 4px;
  display: none;
}

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

.validation-message.success {
  display: block;
  background: rgba(16, 185, 129, 0.1);
  color: #10b981;
  border: 1px solid rgba(16, 185, 129, 0.3);
}

.validation-message.loading {
  display: block;
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
  border: 1px solid rgba(99, 102, 241, 0.3);
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 8px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 8px;
  font-weight: 500;
  text-decoration: none;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.9rem;
  min-width: 120px;
  justify-content: center;
}

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

.btn-primary:hover:not(:disabled) {
  background: #4f46e5;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.btn-primary:disabled {
  background: #4b5563;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-ghost {
  background: transparent;
  color: #94a3b8;
  border: 1px solid #2b3138;
}

.btn-ghost:hover {
  background: rgba(255,255,255,0.05);
  color: #f8fafc;
  border-color: #3f4752;
}

.alert {
  background: rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.3);
  color: #6366f1;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .container {
    margin: 16px auto;
    padding: 0 16px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .card {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .card {
    padding: 16px;
  }
  
  .card h3 {
    font-size: 1.1rem;
  }
}
</style>