<?php if (!function_exists('avatar_img')) { @include_once '../../helpers.php'; } ?>
<?php
// Vista de perfil: publicaciones a la izquierda, perfil/edición a la derecha
?>
<div class="profile-container">
  <div class="profile-grid">
    
    <!-- Columna izquierda: Publicaciones -->
    <div class="profile-posts-column">
      <div class="card">
        <header class="card-header">
          <h3 class="card-title">Publicaciones</h3>
        </header>
        
        <div class="card-content">
          <?php if (!empty($posts) && is_array($posts)): ?>
            <div class="posts-grid">
              <?php foreach ($posts as $p): ?>
                <article class="post-card">
                  <header class="post-header">
                    <h4 class="post-title">
                      <?php 
                        $title = trim((string)($p['caption'] ?? '')); 
                        if ($title === '') $title = 'Publicación'; 
                        if (mb_strlen($title) > 60) $title = mb_substr($title, 0, 60) . '…'; 
                        echo h($title); 
                      ?>
                    </h4>
                    <time class="post-date muted">
                      <?php if (!empty($p['created_at'])) echo date('d/m/Y', strtotime($p['created_at'])); ?>
                    </time>
                  </header>
                  
                  <?php if (!empty($p['url'])): ?>
                    <div class="post-image-container">
                      <img 
                        src="<?= h($p['url']) ?>" 
                        alt="Imagen de la publicación" 
                        class="post-image"
                        loading="lazy"
                      >
                    </div>
                  <?php endif; ?>
                  
                  <?php 
                    $summary = trim(strip_tags($p['caption'] ?? ($p['content'] ?? ($p['body'] ?? '')))); 
                    if (mb_strlen($summary) > 180) { 
                      $summary = mb_substr($summary, 0, 180) . '…'; 
                    }
                  ?>
                  
                  <?php if ($summary): ?>
                    <p class="post-summary muted"><?= h($summary) ?></p>
                  <?php endif; ?>
                  
                  <footer class="post-footer">
                    <a class="btn btn-sm" href="./?r=posts/view<?= !empty($p['id']) ? '&id=' . urlencode($p['id']) : '' ?>">
                      Ver publicación
                    </a>
                  </footer>
                </article>
              <?php endforeach; ?>
            </div>
            
            <div class="posts-action">
              <a href="./?r=posts" class="btn btn-secondary">
                <i class="fas fa-list"></i> Ver todas las publicaciones
              </a>
            </div>
          <?php else: ?>
            <div class="empty-state">
              <i class="fas fa-image empty-state-icon"></i>
              <p class="muted">No hay publicaciones aún</p>
              <a href="./?r=posts/new" class="btn btn-primary">Crear primera publicación</a>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Columna derecha: Tarjeta de perfil + edición -->
    <div class="profile-info-column">
      <div class="card">
        <div class="profile-header">
          <div class="avatar-container" style="overflow:hidden;border-radius:50%;padding:0;background:none;">
            <?php if (!empty($user['avatar_url'])): ?>
              <img 
                src="<?php echo h($user['avatar_url']); ?>" 
                alt="Avatar de <?php echo h($user['username']); ?>"
                class="avatar-image"
                id="currentAvatar"
              >
            <?php else: ?>
              <div class="avatar-placeholder" style="overflow:hidden;border-radius:50%;padding:0;background:none;">
                <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
              </div>
            <?php endif; ?>
          </div>
          
          <div class="profile-info">
            <h2 class="username">@<?php echo h($user['username']); ?></h2>
            <p class="member-since muted">
              Miembro desde <?php echo date('M Y', strtotime($user['created_at'])); ?>
            </p>
          </div>
        </div>

        <!-- === Uploader de avatar MEJORADO === -->
        <form id="avatarForm" action="?r=profile/updateAvatar" method="post" enctype="multipart/form-data" style="margin-top:16px">
          <?php echo function_exists('csrf_field') ? csrf_field() : ''; ?>

          <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap">
            <input
              type="file"
              id="avatarInput"
              name="avatar"
              accept="image/jpeg,image/png,image/gif,image/webp"
              style="padding:10px 14px;border-radius:10px;border:1px solid #2a2e3a;background:#10131a;color:#e9eaf1;cursor:pointer"
            >
            <button type="submit" id="avatarBtn" class="btn" style="padding:10px 14px;border-radius:10px;border:1px solid transparent;background:#ff9cf2;color:#0b0c10;font-weight:600;cursor:pointer">
              <i class="fas fa-upload"></i> Subir avatar
            </button>
            <span id="avatarHint" class="muted" style="font-size:.9rem;color:#a7acb9"></span>
          </div>
        </form>

        <!-- Estadísticas -->
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-number"><?php echo $stats['post_count'] ?? 0; ?></div>
            <div class="stat-label muted">Publicaciones</div>
          </div>
          <div class="stat-card">
            <div class="stat-number"><?php echo $stats['friend_count'] ?? 0; ?></div>
            <div class="stat-label muted">Amigos</div>
          </div>
        </div>

        <!-- Formulario de edición de perfil -->
        <form method="post" action="./?r=profile/update" class="profile-form" id="profile-form">
          <?php echo csrf_field(); ?>
          
          <div class="form-group">
            <label for="username">Nombre de usuario</label>
            <input 
              type="text" 
              id="username" 
              name="username" 
              value="<?php echo h($user['username']); ?>" 
              required
              maxlength="50"
            >
          </div>

          <div class="form-group">
            <label for="bio">Biografía</label>
            <textarea 
              id="bio" 
              name="bio" 
              rows="3" 
              placeholder="Cuenta algo sobre ti..."
              maxlength="500"
            ><?php echo h($user['bio'] ?? ''); ?></textarea>
            <div class="char-counter muted" id="bio-counter">0/500</div>
          </div>

          <div class="form-group">
            <label>Email</label>
            <input 
              type="email" 
              value="<?php echo h($user['email']); ?>" 
              disabled 
              class="disabled-input"
            >
            <small class="muted">El email no se puede modificar</small>
          </div>

          <div class="form-group">
            <label>Fecha de nacimiento</label>
            <input 
              type="text" 
              value="<?php echo h($user['birth_date'] ?? ''); ?>" 
              disabled 
              class="disabled-input"
            >
          </div>

          <div class="form-group">
            <label for="gender">Género</label>
            <?php $g = strtolower($user['gender'] ?? ''); ?>
            <select id="gender" name="gender" required>
              <option value="">Selecciona</option>
              <option value="male" <?= $g === 'male' ? 'selected' : '' ?>>Hombre</option>
              <option value="female" <?= $g === 'female' ? 'selected' : '' ?>>Mujer</option>
              <option value="other" <?= $g === 'other' ? 'selected' : '' ?>>Otro</option>
              <option value="prefer_not_to_say" <?= $g === 'prefer_not_to_say' ? 'selected' : '' ?>>Prefiero no decirlo</option>
            </select>
          </div>

          <div class="form-group">
            <label for="country">País</label>
            <?php $cc = $user['country_code'] ?? ($user['country'] ?? 'ES'); ?>
            <select id="country" name="country" required></select>
          </div>

          <div class="form-group">
            <label for="region">Comunidad / Región</label>
            <select id="region" name="region" required disabled>
              <option value="">Selecciona región</option>
            </select>
          </div>

          <div class="form-group">
            <label for="city">Ciudad</label>
            <select id="city" name="city" required disabled>
              <option value="">Selecciona ciudad</option>
            </select>
          </div>

          <div class="form-actions">
            <button type="submit" class="btn btn-primary btn-save btn-primary">
              <i class="fas fa-save"></i> Guardar cambios
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<style>
/* Variables y reset */
:root {
  --radius-sm: 6px;
  --radius-md: 8px;
  --radius-lg: 12px;
  --accent: #7cd1ff;
  --accent2: #b99cff;
  --transition: all 0.3s ease;
  --brand-pink: #ff9cf2;
}

.profile-container {
  margin-top: 40px;
}

.profile-grid {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

@media (max-width: 900px) {
  .profile-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
}

/* Tarjetas */
.profile-container .card {
  background: rgba(255, 255, 255, 0.05);
  border-radius: var(--radius-lg);
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: var(--transition);
}

.profile-container .card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.profile-container .profile-container .card-header {
  margin-bottom: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 12px;
}

.profile-container .profile-container .card-title {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
}

/* Publicaciones */
.posts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 14px;
}

.post-card {
  padding: 0;
  border: 1px solid #1f2330;
  background: #0f121a;
  border-radius: var(--radius-md);
  overflow: hidden;
  transition: var(--transition);
}

.post-card:hover {
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.12);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  padding: 10px 12px;
}

.post-title {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  line-height: 1.4;
}

.post-date {
  font-size: 0.85rem;
  white-space: nowrap;
  margin-left: 12px;
}

.post-image-container {
  margin: 0;
}

.post-image { 
  display:block; 
  width:100%; 
  aspect-ratio: 4/3; 
  object-fit: cover; 
}

.post-summary {
  padding: 0 12px 12px;
  margin: 0;
  line-height: 1.5;
  font-size: 0.9rem;
}

.post-footer {
  display: flex;
  justify-content: flex-end;
  padding: 0 12px 12px;
}

/* Estados vacíos */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-state-icon {
  font-size: 2rem;
  opacity: 0.5;
  margin-bottom: 12px;
  display: block;
}

/* Botones */
.profile-container .btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  border-radius: var(--radius-sm);
  text-decoration: none;
  font-weight: 500;
  transition: var(--transition);
  border: none;
  cursor: pointer;
  font-size: 0.9rem;
}

.profile-container .btn-sm {
  padding: 8px 12px;
  font-size: 0.8rem;
}

.profile-container .btn-primary, .profile-container .btn-primary:visited {
  background: var(--brand-pink) !important;
  color: #0b0c10 !important;
  border-color: transparent !important;
}

.profile-container .btn-primary:hover {
  filter: brightness(0.95);
  transform: translateY(-1px);
}

.profile-container .btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.profile-container .btn-secondary:hover {
  background: rgba(255, 255, 255, 0.15);
}

/* Información de perfil */
.profile-header {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-container {
  margin-bottom: 16px;
}

.avatar-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin: 0 auto;
  border: 3px solid var(--accent);
  box-shadow: 0 4px 12px rgba(124, 209, 255, 0.3);
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--accent), var(--accent2));
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  color: white;
  font-size: 2.5rem;
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.username {
  margin: 0 0 8px 0;
  font-size: 1.5rem;
}

.member-since {
  margin: 0;
  font-size: 0.9rem;
}

/* Formularios */
.form-group {
  margin-bottom: 20px;
}

.form-group .profile-container label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
}

.form-group .profile-container input,
.form-group .profile-container select,
.form-group .profile-container textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: var(--radius-sm);
  background: rgba(255, 255, 255, 0.05);
  color: #fff;
  font-size: 0.9rem;
  transition: var(--transition);
}

.form-group .profile-container input:focus,
.form-group .profile-container select:focus,
.form-group .profile-container textarea:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: 0 0 0 2px rgba(124, 209, 255, 0.2);
}

.disabled-input {
  background: rgba(255, 255, 255, 0.1) !important;
  cursor: not-allowed;
  opacity: 0.7;
}

.char-counter {
  text-align: right;
  font-size: 0.8rem;
  margin-top: 4px;
}

.form-actions {
  text-align: right;
  margin-top: 24px;
}

/* Estadísticas */
.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  padding: 16px;
  background: rgba(124, 209, 255, 0.1);
  border-radius: var(--radius-md);
  transition: var(--transition);
}

.stat-card:nth-child(2) {
  background: rgba(185, 156, 255, 0.1);
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--accent);
}

.stat-card:nth-child(2) .stat-number {
  color: var(--accent2);
}

.stat-label {
  font-size: 0.85rem;
}

/* Utilidades */
.muted {
  opacity: 0.7;
}

.posts-action {
  text-align: center;
  margin-top: 16px;
}

/* Estados de carga */
.loading {
  opacity: 0.7;
  pointer-events: none;
}

.loading::after {
  content: '';
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-left: 8px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Responsive */
@media (min-width: 1200px) {
  .posts-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
}

@media (min-width: 1600px) {
  .posts-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
}

/* Mensajes de éxito/error */
.success-message {
  color: #4ade80;
}

.error-message {
  color: #ff6b6b;
}
</style>

<script>
/* PROFILE GEO JS: países → regiones → ciudades (España) */
(function(){
  const COUNTRIES = [
    ["ES","España"],["PT","Portugal"],["FR","Francia"],["IT","Italia"],["DE","Alemania"],["GB","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"],["RO","Rumanía"],
    ["GR","Grecia"],["TR","Turquía"],["NO","Noruega"],["SE","Suecia"],["FI","Finlandia"],["DK","Dinamarca"],
    ["US","Estados Unidos"],["CA","Canadá"],["MX","México"],["AR","Argentina"],["CL","Chile"],["CO","Colombia"],
    ["PE","Perú"],["UY","Uruguay"],["BR","Brasil"],["VE","Venezuela"],["EC","Ecuador"],["CR","Costa Rica"],["PA","Panamá"]
  ];
  
  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');
  const currentCountry = "<?php echo h($cc ?? 'ES'); ?>";
  const currentRegion  = "<?php echo h($user['region'] ?? ''); ?>";
  const currentCity    = "<?php echo h($user['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; 
      if (code === currentCountry) o.selected = true;
      country.appendChild(o);
    });
    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; 
        if (r === currentRegion) o.selected = true;
        region.appendChild(o);
      });
      
      handleRegion();
    } else {
      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;
        if (c === currentCity) o.selected = true;
        city.appendChild(o);
      });
    } else {
      city.disabled = true;
      city.innerHTML = '<option value="">No aplica</option>';
    }
  }
  
  // Event listeners
  country?.addEventListener('change', handleCountry);
  region?.addEventListener('change', handleRegion);
  
  // Inicialización
  fillCountries();
})();

/* Upload de avatar - CÓDIGO CORREGIDO Y MEJORADO */
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('avatarForm');
    const input = document.getElementById('avatarInput');
    const btn = document.getElementById('avatarBtn');
    const hint = document.getElementById('avatarHint');
    
    if (!form || !input || !btn) {
        console.error('❌ Elementos del formulario de avatar no encontrados');
        return;
    }

    console.log('✅ Script de avatar cargado correctamente');

    // Validar archivo antes de enviar
    input.addEventListener('change', function() {
        if (!input.files || !input.files[0]) {
            hint.textContent = '';
            return;
        }
        
        const file = input.files[0];
        const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        
        if (!validTypes.includes(file.type)) {
            hint.textContent = 'Formato no válido. Use JPEG, PNG, GIF o WebP.';
            hint.style.color = '#ff6b6b';
            input.value = '';
            return;
        }
        
        if (file.size > 10 * 1024 * 1024) {
            hint.textContent = 'El archivo es demasiado grande (máx. 10MB).';
            hint.style.color = '#ff6b6b';
            input.value = '';
            return;
        }
        
        hint.textContent = `Archivo: ${file.name} (${Math.round(file.size/1024)} KB)`;
        hint.style.color = '';
    });

    // Envío AJAX corregido
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        if (!input.files || !input.files[0]) {
            hint.textContent = 'Selecciona un archivo primero';
            hint.style.color = '#ff6b6b';
            return;
        }

        // Cambiar estado del botón
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Subiendo...';
        btn.disabled = true;
        hint.textContent = 'Subiendo...';
        hint.style.color = '';

        // Variable para almacenar la respuesta
        let responseData = null;

        try {
            const formData = new FormData(form);
            
            // Añadir indicador AJAX
            const url = form.action + (form.action.includes('?') ? '&' : '?') + 'ajax=1';
            
            console.log('🔄 Enviando avatar a:', url);
            
            const response = await fetch(url, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });
            
            console.log('📨 Respuesta recibida, status:', response.status);
            
            try {
                responseData = await response.json();
                console.log('📊 Datos JSON:', responseData);
            } catch (jsonError) {
                console.error('❌ Error parseando JSON:', jsonError);
                throw new Error('Respuesta del servidor no válida');
            }
            
            if (responseData && responseData.success) {
                console.log('✅ Avatar subido exitosamente');
                
                // Actualizar avatar visualmente
                const avatarImg = document.querySelector('.avatar-image');
                const avatarPlaceholder = document.querySelector('.avatar-placeholder');
                
                if (responseData.url) {
                    const newSrc = responseData.url + '?t=' + Date.now(); // Cache busting
                    console.log('🖼️ Nueva URL del avatar:', newSrc);
                    
                    if (avatarImg) {
                        avatarImg.src = newSrc;
                        console.log('✅ Avatar image actualizado');
                    } else if (avatarPlaceholder) {
                        // Reemplazar placeholder por imagen
                        const newImg = document.createElement('img');
                        newImg.src = newSrc;
                        newImg.alt = 'Avatar';
                        newImg.className = 'avatar-image';
                        newImg.style.width = '100px';
                        newImg.style.height = '100px';
                        newImg.style.borderRadius = '50%';
                        newImg.style.objectFit = 'cover';
                        avatarPlaceholder.parentNode.replaceChild(newImg, avatarPlaceholder);
                        console.log('✅ Placeholder reemplazado por imagen');
                    }
                }
                
                hint.textContent = '✓ Avatar actualizado correctamente';
                hint.style.color = '#4ade80';
                
                // Recargar la página después de 1.5 segundos para asegurar consistencia
                setTimeout(() => {
                    console.log('🔄 Recargando página para mostrar cambios...');
                    window.location.reload();
                }, 1500);
                
            } else {
                const errorMsg = responseData?.message || responseData?.error || 'Error al subir el avatar';
                console.error('❌ Error del servidor:', errorMsg);
                hint.textContent = '✗ ' + errorMsg;
                hint.style.color = '#ff6b6b';
                
                // Restaurar botón después de error
                setTimeout(() => {
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }, 3000);
            }
            
        } catch (error) {
            console.error('❌ Error de conexión:', error);
            hint.textContent = '✗ Error de conexión: ' + error.message;
            hint.style.color = '#ff6b6b';
            
            // Fallback: enviar formulario normalmente después de mostrar error
            setTimeout(() => {
                hint.textContent = 'Intentando envío normal...';
                const newForm = form.cloneNode(true);
                form.parentNode.replaceChild(newForm, form);
                newForm.submit();
            }, 2000);
            
        } finally {
            // Restaurar botón solo si no fue exitoso (en éxito se recarga la página)
            if (!(responseData && responseData.success)) {
                setTimeout(() => {
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }, 3000);
            }
        }
    });
});

/* Mejoras adicionales de UX */
document.addEventListener('DOMContentLoaded', function() {
  // Contador de caracteres para biografía
  const bioTextarea = document.getElementById('bio');
  const bioCounter = document.getElementById('bio-counter');
  
  if (bioTextarea && bioCounter) {
    function updateBioCounter() {
      const length = bioTextarea.value.length;
      bioCounter.textContent = `${length}/500`;
      
      if (length > 450) {
        bioCounter.style.color = '#ff6b6b';
      } else if (length > 400) {
        bioCounter.style.color = '#ffa726';
      } else {
        bioCounter.style.color = '';
      }
    }
    
    bioTextarea.addEventListener('input', updateBioCounter);
    updateBioCounter(); // Inicializar contador
  }
  
  // Indicador de carga para formularios
  const forms = document.querySelectorAll('form');
  forms.forEach(form => {
    if (form.id !== 'avatarForm') { // Excluir el formulario de avatar que ya tiene su propio manejo
      form.addEventListener('submit', function() {
        const submitBtn = this.querySelector('button[type="submit"]');
        if (submitBtn) {
          submitBtn.classList.add('loading');
          submitBtn.disabled = true;
          
          // Restaurar después de 10 segundos por si hay error
          setTimeout(() => {
            submitBtn.classList.remove('loading');
            submitBtn.disabled = false;
          }, 10000);
        }
      });
    }
  });
  
  // Mejorar accesibilidad de selects
  const selects = document.querySelectorAll('select');
  selects.forEach(select => {
    select.addEventListener('focus', function() {
      this.parentElement.classList.add('focused');
    });
    
    select.addEventListener('blur', function() {
      this.parentElement.classList.remove('focused');
    });
  });

  // Mostrar mensajes flash automáticamente
  const flashMessages = document.querySelectorAll('.flash-message');
  flashMessages.forEach(message => {
    setTimeout(() => {
      message.style.opacity = '0';
      setTimeout(() => {
        if (message.parentNode) {
          message.parentNode.removeChild(message);
        }
      }, 500);
    }, 5000);
  });
});

// Función auxiliar para mostrar notificaciones
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        transition: all 0.3s ease;
        max-width: 300px;
    `;
    
    if (type === 'success') {
        notification.style.background = '#4ade80';
    } else if (type === 'error') {
        notification.style.background = '#ff6b6b';
    } else if (type === 'warning') {
        notification.style.background = '#ffa726';
    } else {
        notification.style.background = '#7cd1ff';
    }
    
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // Animar entrada
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // Remover después de 5 segundos
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 5000);
}
</script>