<div class="container">
  <div class="dashboard-layout">
    <!-- Sidebar con información adicional -->
    <aside class="dashboard-sidebar">
      <?php if ($is_my_birthday): ?>
      <section class="card birthday-alert" id="birthdayAlert">
        <div style="position:relative;z-index:2;">
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:12px;">
            <div style="flex:1;">
              <h3 style="color:white;margin:0 0 8px 0;font-size:1.3rem;text-shadow:0 1px 2px rgba(0,0,0,0.3);">🎂 ¡Feliz Cumpleaños!</h3>
              <p style="margin:0;color:white;font-weight:500;text-shadow:0 1px 2px rgba(0,0,0,0.3);">¡Que tengas un día maravilloso, @<?php echo htmlspecialchars(user()['nick']??''); ?>! 🎉</p>
            </div>
            <button class="close-birthday-alert" style="background:none;border:none;color:white;cursor:pointer;font-size:1.5rem;font-weight:bold;padding:0;width:24px;height:24px;display:flex;align-items:center;justify-content:center;text-shadow:0 1px 2px rgba(0,0,0,0.3);">×</button>
          </div>
          <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <span style="background:rgba(255,255,255,0.2);padding:4px 12px;border-radius:20px;font-size:0.85rem;color:white;font-weight:500;text-shadow:0 1px 2px rgba(0,0,0,0.3);">¡Disfruta tu día!</span>
            <span style="background:rgba(255,255,255,0.2);padding:4px 12px;border-radius:20px;font-size:0.85rem;color:white;font-weight:500;text-shadow:0 1px 2px rgba(0,0,0,0.3);">🎈 🎁 🎊</span>
          </div>
        </div>
        <canvas id="confettiCanvas" style="position:absolute;top:0;left:0;width:100%;height:100%;border-radius:12px;pointer-events:none;z-index:1;"></canvas>
      </section>
      <?php endif; ?>

      <section class="card">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:16px;">
          <h3 style="margin:0;flex:1;">🎉 Cumpleaños esta semana</h3>
          <span style="background:#6366f1;color:white;padding:2px 8px;border-radius:12px;font-size:0.8rem;font-weight:bold;">
            <?php echo count($birthdays); ?>
          </span>
        </div>
        
        <?php if (empty($birthdays)): ?>
          <div style="text-align:center;padding:20px 0;">
            <div style="font-size:2rem;margin-bottom:8px;">🎂</div>
            <p style="margin:0;color:#94a3b8;">Ninguno de tus amigos cumple años esta semana.</p>
          </div>
        <?php else: ?>
          <div style="display:flex;flex-direction:column;gap:12px;">
            <?php foreach ($birthdays as $friend): ?>
              <?php 
              $birthday = new DateTime($friend['dob']);
              $today = new DateTime();
              
              // Crear fecha de cumpleaños para este año
              $birthday_this_year = new DateTime();
              $birthday_this_year->setDate(
                  $today->format('Y'), 
                  $birthday->format('m'), 
                  $birthday->format('d')
              );
              
              // Si el cumpleaños ya pasó este año, usar el próximo año
              if ($birthday_this_year < $today) {
                  $birthday_this_year->modify('+1 year');
              }
              
              $is_today = $birthday_this_year->format('Y-m-d') == $today->format('Y-m-d');
              $days_diff = $today->diff($birthday_this_year)->days;
              ?>
              <div style="display:flex;align-items:center;gap:12px;padding:12px;background:<?php echo $is_today ? 'rgba(99, 102, 241, 0.1)' : 'transparent'; ?>;border-radius:8px;border:1px solid <?php echo $is_today ? '#6366f1' : '#2b3138'; ?>;">
                <div style="width:44px;height:44px;border-radius:50%;background:linear-gradient(135deg,<?php echo $is_today ? '#f59e0b,#fbbf24' : '#6366f1,#8b5cf6'; ?>);display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;font-size:1.1rem;">
                  🎂
                </div>
                <div style="flex:1;">
                  <div style="display:flex;align-items:center;gap:6px;margin-bottom:2px;">
                    <a href="<?php echo htmlspecialchars(base_url('/profile?nick=' . $friend['nick'])); ?>" style="color:white;text-decoration:none;font-weight:bold;">
                      @<?php echo htmlspecialchars($friend['nick']); ?>
                    </a>
                    <?php if ($is_today): ?>
                      <span style="background:#f59e0b;color:#1f2937;padding:1px 6px;border-radius:8px;font-size:0.7rem;font-weight:bold;">HOY</span>
                    <?php endif; ?>
                  </div>
                  <div style="color:#94a3b8;font-size:0.85rem;margin-bottom:2px;">
                    <?php echo htmlspecialchars($friend['first_name'] . ' ' . $friend['last_name']); ?>
                  </div>
                  <div style="color:<?php echo $is_today ? '#fbbf24' : '#6366f1'; ?>;font-size:0.8rem;font-weight:bold;">
                    <?php 
                    if ($is_today) {
                        echo "¡Cumple hoy!";
                    } else {
                        echo $birthday_this_year->format('d M') . " (en " . $days_diff . " día" . ($days_diff > 1 ? "s" : "") . ")";
                    }
                    ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
        
        <?php if (!empty($birthdays)): ?>
          <div style="margin-top:16px;padding-top:16px;border-top:1px solid #2b3138;">
            <a href="<?php echo htmlspecialchars(base_url('/friends')); ?>" class="btn ghost" style="width:100%;text-align:center;font-size:0.9rem;">
              Ver todos los amigos
            </a>
          </div>
        <?php endif; ?>
      </section>

      <section class="card">
        <h3>🚀 Acciones rápidas</h3>
        <div style="display:flex;flex-direction:column;gap:8px;">
          <a href="<?php echo htmlspecialchars(base_url('/photos/upload')); ?>" class="btn" style="text-align:center;">
            Subir foto
          </a>
          <a href="<?php echo htmlspecialchars(base_url('/friends/search')); ?>" class="btn ghost" style="text-align:center;">
            Buscar amigos
          </a>
        </div>
      </section>
    </aside>

    <!-- Contenido principal - Feed -->
    <main class="dashboard-main">
      <div class="card" style="margin-bottom:20px;">
        <h2>Inicio</h2>
        <p>Bienvenido, <strong>@<?php echo htmlspecialchars(user()['nick']??''); ?></strong>. Aquí está tu feed de amigos.</p>
      </div>

      <?php if (empty($feed)): ?>
        <div class="card">
          <h3>Tu feed está vacío</h3>
          <p>Sigue a más amigos o <a href="<?php echo htmlspecialchars(base_url('/photos/upload')); ?>">sube tu primera foto</a> para empezar a ver contenido.</p>
          <div style="margin-top:16px;">
            <a href="<?php echo htmlspecialchars(base_url('/friends/search')); ?>" class="btn">Buscar amigos</a>
            <a href="<?php echo htmlspecialchars(base_url('/photos/upload')); ?>" class="btn ghost">Subir foto</a>
          </div>
        </div>
      <?php else: ?>
        <div class="posts-grid" id="postsContainer">
          <?php foreach ($feed as $post): ?>
            <article class="card post-card">
              <header class="post-header">
                <div class="post-avatar"><?php if(!empty($post['avatar_url'])): ?><img src="<?php echo htmlspecialchars($post['avatar_url']); ?>" alt="avatar" class="user-avatar"><?php else: ?><?php echo strtoupper(substr($post['nick'], 0, 1)); ?><?php endif; ?></div>
                <div class="post-user-info">
                  <a href="<?php echo htmlspecialchars(base_url('/profile?nick=' . $post['nick'])); ?>" class="post-username">
                    @<?php echo htmlspecialchars($post['nick']); ?>
                  </a>
                  <div class="post-date"><?php echo htmlspecialchars($post['created_at']); ?></div>
                </div>
              </header>
              
              <?php if (!empty($post['storage_rel_path'])): ?>
                <div class="post-image-container">
                  <a href="<?php echo htmlspecialchars(base_url('/photo?id=' . $post['post_id'])); ?>">
                    <img 
                      src="<?php echo htmlspecialchars(asset_url($post['storage_rel_path'])); ?>" 
                      alt="Foto de @<?php echo htmlspecialchars($post['nick']); ?>" 
                      class="post-image"
                      loading="lazy"
                    >
                  </a>
                </div>
              <?php endif; ?>
              
              <?php if (!empty($post['text'])): ?>
                <div class="post-caption">
                  <?php echo htmlspecialchars($post['text']); ?>
                </div>
              <?php endif; ?>
              
              <div class="post-actions">
                <form method="post" action="<?php echo htmlspecialchars(base_url('/like/toggle')); ?>" class="like-form">
                  <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                  <input type="hidden" name="post_id" value="<?php echo (int)$post['post_id']; ?>">
                  <button class="btn <?php echo $post['i_like'] ? '' : 'ghost'; ?> like-btn">
                    ❤️ <?php echo (int)$post['like_count']; ?>
                  </button>
                </form>
                
                <?php if (!empty($post['storage_rel_path'])): ?>
                  <?php 
                  $comment_count = $comment_counts[$post['post_id']] ?? 0;
                  ?>
                  <a href="<?php echo htmlspecialchars(base_url('/photo?id=' . $post['post_id'])); ?>" class="btn ghost comment-btn">
                    💬 <?php echo (int)$comment_count; ?>
                  </a>
                <?php else: ?>
                  <span class="btn ghost disabled-comment-btn">
                    💬 0
                  </span>
                <?php endif; ?>

                <button class="btn ghost report-btn" data-post-id="<?php echo $post['post_id']; ?>">
                  ⚠️ Reportar
                </button>
              </div>
            </article>
          <?php endforeach; ?>
        </div>

        <?php if ($has_more): ?>
          <div id="loadMoreContainer" style="text-align: center; margin-top: 30px; margin-bottom: 20px;">
            <button id="loadMoreBtn" class="btn" style="padding: 12px 24px; font-size: 1rem;">
              📥 Cargar más posts
            </button>
          </div>
        <?php endif; ?>
      <?php endif; ?>
    </main>
  </div>
</div>

<style>
.container {
  max-width: 1100px;
  margin: 0 auto;
  padding: 16px;
}

.dashboard-layout {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 24px;
  align-items: start;
  margin-top: 20px;
}

.dashboard-sidebar {
  position: sticky;
  top: 100px;
}

.dashboard-sidebar .card {
  margin-bottom: 20px;
}

.dashboard-main {
  min-width: 0;
}

/* Grid de posts uniforme */
.posts-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.post-card {
  margin-bottom: 0 !important;
  display: flex;
  flex-direction: column;
  min-height: 400px;
  height: fit-content;
}

.post-header {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.post-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg,#6366f1,#8b5cf6);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  flex-shrink: 0;
}

.post-user-info {
  flex: 1;
  min-width: 0;
}

.post-username {
  color: white;
  text-decoration: none;
  font-weight: bold;
  transition: color 0.2s ease;
}

.post-username:hover {
  color: #6366f1;
}

.post-date {
  color: #94a3b8;
  font-size: 0.85rem;
}

.post-image-container {
  margin-bottom: 12px;
  flex-shrink: 0;
}

.post-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 12px;
  background: linear-gradient(135deg, #2b3138, #1a1d23);
  min-height: 200px;
}

.post-caption {
  margin-bottom: 16px;
  line-height: 1.5;
  color: #e2e8f0;
  flex: 1;
  min-height: 40px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border-left: 3px solid #6366f1;
}

.post-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding-top: 12px;
  border-top: 1px solid #2b3138;
  flex-shrink: 0;
}

.like-form {
  margin: 0;
}

.like-btn, .comment-btn, .report-btn {
  padding: 6px 12px !important;
  font-size: 0.85rem;
}

.comment-btn {
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.disabled-comment-btn {
  opacity: 0.5;
  cursor: not-allowed;
}

.report-btn:hover {
  background: rgba(239, 68, 68, 0.1) !important;
  border-color: #ef4444 !important;
  color: #ef4444 !important;
}

/* Estilos para la alerta de cumpleaños */
.birthday-alert {
  background: linear-gradient(135deg, #fbbf24, #f59e0b, #eab308);
  color: white;
  border: none;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(245, 158, 11, 0.3);
}

.birthday-alert h3,
.birthday-alert p {
  color: white !important;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
  position: relative;
  z-index: 3;
}

.close-birthday-alert:hover {
  background: rgba(255,255,255,0.3) !important;
  border-radius: 50%;
}

/* Responsive */
@media (max-width: 968px) {
  .dashboard-layout {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .dashboard-sidebar {
    position: static;
    order: 2;
  }
  
  .dashboard-main {
    order: 1;
  }
}

@media (max-width: 768px) {
  .post-actions {
    justify-content: center;
    gap: 8px;
  }
  
  .post-card {
    min-height: 350px;
  }
  
  .post-image {
    max-height: 300px;
  }
  
  .like-btn, .comment-btn, .report-btn {
    padding: 5px 10px !important;
    font-size: 0.8rem;
  }
}

@media (max-width: 480px) {
  .card {
    padding: 16px;
  }
  
  .post-header {
    gap: 8px;
  }
  
  .post-avatar {
    width: 32px;
    height: 32px;
    font-size: 0.8rem;
  }
  
  .post-actions {
    gap: 6px;
  }
}

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

.btn {
  background: #6366f1; /* MORADO ORIGINAL */
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
  transition: all 0.2s ease;
  font-size: 0.9rem;
}

.btn:hover {
  background: #4f46e5; /* Morado más oscuro */
  transform: translateY(-1px);
}

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

.btn.ghost:hover {
  background: rgba(255,255,255,0.05);
  border-color: #6366f1; /* Morado en hover */
}
</style>

<!-- El JavaScript se mantiene igual -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  const closeButton = document.querySelector('.close-birthday-alert');
  if (closeButton) {
    closeButton.addEventListener('click', function() {
      this.closest('.birthday-alert').style.display = 'none';
    });
  }

  const birthdayAlert = document.getElementById('birthdayAlert');
  if (birthdayAlert) {
    startConfetti();
  }

  // Botón de reportar (sin funcionalidad por ahora)
  const reportBtns = document.querySelectorAll('.report-btn');
  reportBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      const postId = this.dataset.postId;
      this.innerHTML = '⚠️ Próximamente';
      this.style.background = 'rgba(156, 163, 175, 0.1)';
      this.style.borderColor = '#9ca3af';
      this.style.color = '#9ca3af';
      this.disabled = true;
      
      setTimeout(() => {
        this.innerHTML = '⚠️ Reportar';
        this.style.background = '';
        this.style.borderColor = '';
        this.style.color = '';
        this.disabled = false;
      }, 2000);
    });
  });

  // Cargar más posts
  const loadMoreBtn = document.getElementById('loadMoreBtn');
  if (loadMoreBtn) {
    loadMoreBtn.addEventListener('click', loadMorePosts);
  }

  async function loadMorePosts() {
    if (!loadMoreBtn) return;
    
    const currentPage = <?php echo $current_page; ?>;
    const nextPage = currentPage + 1;
    
    loadMoreBtn.disabled = true;
    loadMoreBtn.innerHTML = '⏳ Cargando...';
    
    try {
      const response = await fetch(`?page=${nextPage}`);
      if (!response.ok) throw new Error('Error en la respuesta del servidor');
      
      const html = await response.text();
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = html;
      
      const newPosts = tempDiv.querySelector('#postsContainer');
      const newLoadMoreBtn = tempDiv.querySelector('#loadMoreContainer');
      
      if (newPosts) {
        document.getElementById('postsContainer').innerHTML += newPosts.innerHTML;
        // Re-asignar event listeners a los nuevos botones de reportar
        reassignReportButtons();
      }
      
      // Actualizar o eliminar el botón de cargar más
      if (newLoadMoreBtn) {
        loadMoreBtn.outerHTML = newLoadMoreBtn.outerHTML;
        // Re-asignar el event listener al nuevo botón
        const newBtn = document.getElementById('loadMoreBtn');
        if (newBtn) {
          newBtn.addEventListener('click', loadMorePosts);
        }
      } else {
        loadMoreBtn.remove();
      }
      
    } catch (error) {
      console.error('Error loading more posts:', error);
      loadMoreBtn.disabled = false;
      loadMoreBtn.innerHTML = '📥 Cargar más posts';
      loadMoreBtn.style.background = 'rgba(239, 68, 68, 0.1)';
      loadMoreBtn.style.borderColor = '#ef4444';
      loadMoreBtn.style.color = '#ef4444';
      
      setTimeout(() => {
        loadMoreBtn.style.background = '';
        loadMoreBtn.style.borderColor = '';
        loadMoreBtn.style.color = '';
      }, 3000);
    }
  }

  function reassignReportButtons() {
    // Re-asignar event listeners a los nuevos botones de reportar
    const newReportBtns = document.querySelectorAll('.report-btn');
    newReportBtns.forEach(btn => {
      btn.addEventListener('click', function() {
        const postId = this.dataset.postId;
        this.innerHTML = '⚠️ Próximamente';
        this.style.background = 'rgba(156, 163, 175, 0.1)';
        this.style.borderColor = '#9ca3af';
        this.style.color = '#9ca3af';
        this.disabled = true;
        
        setTimeout(() => {
          this.innerHTML = '⚠️ Reportar';
          this.style.background = '';
          this.style.borderColor = '';
          this.style.color = '';
          this.disabled = false;
        }, 2000);
      });
    });
  }

  function startConfetti() {
    try {
      const canvas = document.getElementById('confettiCanvas');
      if (!canvas) return;
      
      const ctx = canvas.getContext('2d');
      const confettiPieces = [];
      
      canvas.width = birthdayAlert.offsetWidth;
      canvas.height = birthdayAlert.offsetHeight;

      const colors = [
        '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF',
        '#FFA500', '#FF69B4', '#9370DB', '#32CD32', '#FFD700', '#FF6347'
      ];

      for (let i = 0; i < 25; i++) {
        confettiPieces.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height - canvas.height,
          size: Math.random() * 8 + 4,
          speed: Math.random() * 3 + 1.5,
          color: colors[Math.floor(Math.random() * colors.length)],
          rotation: Math.random() * 360,
          rotationSpeed: Math.random() * 8 - 4,
          shape: Math.random() > 0.5 ? 'circle' : 'rect',
          opacity: Math.random() * 0.7 + 0.3
        });
      }

      function animateConfetti() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        let activePieces = 0;
        
        confettiPieces.forEach(confetti => {
          ctx.save();
          ctx.translate(confetti.x, confetti.y);
          ctx.rotate(confetti.rotation * Math.PI / 180);
          ctx.globalAlpha = confetti.opacity;
          
          if (confetti.shape === 'circle') {
            ctx.beginPath();
            ctx.arc(0, 0, confetti.size / 2, 0, Math.PI * 2);
            ctx.fillStyle = confetti.color;
            ctx.fill();
          } else {
            ctx.fillStyle = confetti.color;
            ctx.fillRect(-confetti.size / 2, -confetti.size / 4, confetti.size, confetti.size / 2);
          }
          
          ctx.restore();
          
          confetti.y += confetti.speed;
          confetti.x += Math.sin(confetti.y * 0.01) * 1;
          confetti.rotation += confetti.rotationSpeed;
          confetti.speed += 0.03;
          
          if (confetti.y < canvas.height) {
            activePieces++;
          } else {
            confetti.y = -confetti.size;
            confetti.x = Math.random() * canvas.width;
            confetti.speed = Math.random() * 3 + 1.5;
            confetti.color = colors[Math.floor(Math.random() * colors.length)];
            confetti.opacity = Math.random() * 0.7 + 0.3;
          }
        });
        
        if (activePieces > 0 && birthdayAlert.style.display !== 'none') {
          requestAnimationFrame(animateConfetti);
        }
      }
      
      animateConfetti();
    } catch (error) {
      console.error('Error en confetti:', error);
    }
  }
});
</script>