<?php 
// Asegurarnos de que esta vista use el sistema de vistas común
if (!function_exists('view')) {
    function view($name, $data = []) {
        extract($data);
        include __DIR__ . '/_header.php';
        include __DIR__ . "/$name.php";
        include __DIR__ . '/_footer.php';
    }
}

// Incluir helpers si no existen
if (!function_exists('avatar_img')) { 
    @include_once '../helpers.php'; 
}
?>

<style>
.dashboard-container {
    margin-top: 20px;
}

.dashboard-header {
    background: linear-gradient(135deg, rgba(124,209,255,0.1), rgba(185,156,255,0.1));
    border-left: 4px solid var(--accent);
}

.notification-wrapper {
    position: relative;
    display: inline-block;
}

.notification-badge {
    position: absolute;
    top: 2px;
    right: 2px;
    background: var(--accent3);
    color: white;
    border-radius: 50%;
    min-width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    font-weight: bold;
    padding: 0;
    border: 2px solid rgba(15, 17, 23, 0.95);
    z-index: 10;
    line-height: 1;
}

.notification-btn {
    position: relative;
    padding: 12px 16px 12px 16px !important;
}

/* Birthday Card Styles */
.bday-card {
    position: relative;
    border-radius: 16px;
    background: radial-gradient(1200px 400px at -10% -20%, rgba(255,255,255,0.06), transparent 60%),
                radial-gradient(800px 300px at 110% 120%, rgba(255,255,255,0.04), transparent 60%),
                var(--card);
    border: 1px solid var(--border);
    overflow: hidden;
}

.bday-card::before {
    content: "";
    position: absolute;
    inset: 0;
    padding: 1px;
    border-radius: 16px;
    background: linear-gradient(90deg, #ffcc70, #ff7eb3, #7bdff2, #b2f7ef, #ffd166, #ffcc70);
    -webkit-mask: 
      linear-gradient(#000 0 0) content-box, 
      linear-gradient(#000 0 0);
    -webkit-mask-composite: xor;
            mask-composite: exclude;
    animation: bday-border 6s linear infinite;
}

@keyframes bday-border {
    to { background-position: 200% 0; }
}

.bday-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 14px 0;
}

.bday-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: grid;
    place-items: center;
    background: linear-gradient(135deg, #ff8a00, #e52e71);
    color: white;
    box-shadow: 0 8px 24px rgba(229,46,113,0.35);
    animation: pop 1.1s cubic-bezier(.2,.7,.3,1) 1, floaty 3.5s ease-in-out infinite;
}

@keyframes pop { 
    0% { transform: scale(.8); } 
    60% { transform: scale(1.1); } 
    100% { transform: scale(1); } 
}

@keyframes floaty { 
    0%,100% { transform: translateY(0); } 
    50% { transform: translateY(-4px); } 
}

.bday-title {
    font-weight: 800;
    letter-spacing: .2px;
    background: linear-gradient(90deg, #ffd166, #ff7eb3, #7bdff2);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}

.bday-close {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: grid;
    place-items: center;
    border: 1px solid var(--border-light);
    background: rgba(255,255,255,0.04);
    color: var(--text);
    cursor: pointer;
    transition: transform .15s ease, background .2s ease, border-color .2s ease;
    z-index: 20;
}

.bday-close:hover { 
    transform: scale(1.05); 
    background: rgba(255,255,255,0.08); 
    border-color: var(--accent); 
}

.bday-chip {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border-radius: 10px;
    border: 1px solid var(--border-light);
    background: rgba(255, 215, 0, 0.08);
    transition: transform .15s ease, box-shadow .2s ease;
    position: relative;
    z-index: 10;
}

.bday-chip:hover { 
    transform: translateY(-2px); 
    box-shadow: 0 8px 20px rgba(0,0,0,.2);
}

.bday-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: grid;
    place-items: center;
    color: white;
    font-weight: 700;
    background: linear-gradient(135deg, var(--accent), var(--accent2));
    animation: floaty 4s ease-in-out infinite;
}

.bday-me {
    margin-bottom: 14px;
    padding: 10px 12px;
    border-radius: 10px;
    border: 1px solid var(--success);
    background: rgba(0,255,170,0.08);
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
    position: relative;
    z-index: 10;
}

/* Confetti canvas */
#bday-confetti {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
}

/* Post Styles */
.thirty-feed {
    display: flex;
    flex-direction: column;
    gap: 20px;
    max-width: 700px;
    margin: 0 auto;
}

.thirty-post {
    transition: all 0.3s ease;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    overflow: hidden;
}

.thirty-post:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
}

.post-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border-light);
}

.user-badge {
    width: 42px;
    height: 42px;
    border-radius: 12px;
    background: var(--gradient);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    font-size: 16px;
}

.username-link {
    color: var(--accent);
    text-decoration: none;
    font-weight: 600;
}

.username-link:hover {
    text-decoration: underline;
    color: var(--accent-light);
}

.post-stats {
    display: flex;
    gap: 16px;
}

.post-media {
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid var(--border);
    margin-bottom: 12px;
}

.post-media img {
    width: 100%;
    display: block;
}

.post-caption {
    padding: 12px;
    background: rgba(15,18,24,0.3);
    border-radius: 12px;
    border-left: 3px solid var(--accent);
}

.post-connections {
    margin-bottom: 16px;
}

.connection-tag {
    transition: all 0.3s ease;
    cursor: pointer;
    padding: 4px 10px;
    border-radius: 999px;
    background: rgba(124, 209, 255, 0.15);
    color: var(--accent);
    font-size: 0.85rem;
    font-weight: 500;
    text-decoration: none;
    display: inline-block;
}

.connection-tag:hover {
    background: rgba(124, 209, 255, 0.25);
    transform: translateY(-1px);
}

.post-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 16px;
}

.thirty-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 10px;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: transparent;
    color: var(--text);
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    width: 100%;
    font-weight: 500;
}

.thirty-btn:hover {
    background: rgba(124, 209, 255, 0.1);
    border-color: var(--accent);
    color: var(--accent);
}

.thirty-btn.like-btn {
    border: 1px solid var(--border);
    background: transparent;
    color: var(--text);
}

.thirty-btn.like-btn:hover {
    background: rgba(255, 156, 242, 0.1);
    border-color: var(--accent3);
    color: var(--accent3);
}

.thirty-btn.like-btn.liked {
    background: rgba(255, 156, 242, 0.2);
    border-color: var(--accent3);
    color: var(--accent3);
}

.thirty-btn.comment-btn {
    border: 1px solid var(--border);
    background: transparent;
    color: var(--text);
}

.thirty-btn.comment-btn:hover {
    background: rgba(124, 209, 255, 0.1);
    border-color: var(--accent);
    color: var(--accent);
}

/* Notification Styles */
.notification {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    border-radius: 8px;
    background: var(--success);
    color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateX(calc(100% + 40px));
    transition: transform 0.3s ease;
    z-index: 1000;
}

.notification.show {
    transform: translateX(0);
}

.notification.error {
    background: var(--error);
}

/* Ad Styles */
.ad-card {
    border: 1px solid var(--border-light);
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    margin-bottom: 16px;
    position: relative;
}

.ad-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.2);
    border-color: var(--accent);
}

.ad-card img {
    width: 100%;
    height: 150px;
    object-fit: cover;
    display: block;
}

.ad-badge {
    position: absolute;
    top: 8px;
    right: 8px;
    background: rgba(0,0,0,0.7);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.8rem;
    z-index: 5;
}

.ad-content {
    padding: 16px;
}

.ad-content h4 {
    margin: 0 0 8px 0;
    font-size: 1.1rem;
    color: var(--text);
}

.ad-content p {
    margin: 0 0 12px 0;
    color: var(--muted);
    font-size: 0.9rem;
    line-height: 1.4;
}

.ad-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.8rem;
}

.ad-advertiser {
    color: var(--accent);
    font-weight: 600;
}

.ad-sponsored {
    color: var(--muted);
}

.ad-click-counter {
    position: absolute;
    top: 8px;
    left: 8px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 2px 6px;
    border-radius: 10px;
    font-size: 0.7rem;
    font-weight: bold;
    z-index: 5;
}

/* Responsive */
@media (max-width: 768px) {
    .thirty-feed {
        gap: 16px;
    }

    .post-stats {
        gap: 12px !important;
    }

    .post-actions {
        grid-template-columns: 1fr !important;
        gap: 6px !important;
    }
    
    .notification-badge {
        top: 1px;
        right: 1px;
        min-width: 16px;
        height: 16px;
        font-size: 9px;
    }
    
    .notification-btn {
        padding: 10px 14px 10px 14px !important;
    }
}
</style>

<div class="dashboard-container">
    <!-- Header del dashboard -->
    <div class="card dashboard-header">
        <div style="display:flex;justify-content:space-between;align-items:center">
            <div>
                <h2 style="margin:0 0 8px 0;display:flex;align-items:center;gap:12px">
                    <span class="dot" style="width:32px;height:32px;"><i class="fas fa-compass"></i></span>
                    <span>Mi Thirty</span>
                </h2>
                <p class="muted" style="margin:0">Descubre las últimas publicaciones de tu círculo</p>
            </div>

            <!-- Indicador de notificaciones -->
            <?php
            $unread_count = $_SESSION['unread_notifications'] ?? 0;
            if ($unread_count > 0): ?>
                <div class="notification-wrapper">
                    <a href="./?r=notifications" class="btn primary notification-btn">
                        <i class="fas fa-bell"></i> Notificaciones
                        <span class="notification-badge">
                            <?php echo $unread_count > 9 ? '9+' : $unread_count; ?>
                        </span>
                    </a>
                </div>
            <?php else: ?>
                <a href="./?r=notifications" class="btn">
                    <i class="fas fa-bell"></i> Notificaciones
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- SECCIÓN DE ANUNCIOS -->
    <?php 
    // Obtener anuncios activos usando la función helper
    $activeAds = getActiveAdsForDashboard($db, 3);
    
    // Verificar si el usuario ha cerrado la sección de anuncios
    $adsSectionClosed = isAdsSectionClosed();

    if (!empty($activeAds) && !$adsSectionClosed): ?>
        <div class="card" style="margin-bottom: 24px; position: relative;" id="ads-section">
            <!-- Botón cerrar anuncios -->
            <button id="close-ads-btn" class="bday-close" style="top: 10px; right: 10px; z-index: 20;" aria-label="Ocultar anuncios">
                <i class="fas fa-xmark"></i>
            </button>
            
            <div class="card-header" style="border-bottom: 1px solid var(--border-light); padding: 16px 20px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-ad" style="color: var(--warning); font-size: 1.2rem;"></i>
                    <h3 style="margin: 0; font-size: 1.1rem;">Anuncios Patrocinados</h3>
                    <small class="muted" style="font-size: 0.8rem; margin-left: 8px;">
                        • Estos apoyan a Thirty
                    </small>
                </div>
            </div>
            <div class="ads-container" style="padding: 16px 20px 20px 20px;">
                <div style="display: grid; gap: 16px;">
                    <?php foreach ($activeAds as $ad): ?>
                        <?php 
                        // Registrar impresión del anuncio SOLO si está activo
                        if ($ad['status'] === 'active') {
                            trackAdImpression($db, $ad['id']);
                        }
                        ?>
                        <div class="ad-card" data-ad-id="<?= h($ad['id']) ?>">
                            <a href="./?r=ad-click&id=<?= h($ad['id']) ?>" target="_blank" 
                               style="text-decoration: none; color: inherit; display: block;">
                                <div style="position: relative;">
                                    <img src="<?= h(media_url($ad['image_url'])) ?>" 
                                         alt="<?= h($ad['title']) ?>" 
                                         loading="lazy" decoding="async" style="width: 100%; height: 150px; object-fit: cover; border-radius: 12px; aspect-ratio: 16/9; display: block;"
                                         onerror="this.src='https://via.placeholder.com/300x150/0b0c10/7cd1ff?text=Anuncio+Thirty'">
                                    <div class="ad-badge">Anuncio</div>
                                    <!-- Indicador de estado -->
                                    <div style="position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,0.7); color: white; padding: 4px 8px; border-radius: 12px; font-size: 0.7rem; font-weight: bold;">
                                        <?php
                                        $now = time();
                                        $start = strtotime($ad['start_date']);
                                        $end = strtotime($ad['end_date']);
                                        
                                        if ($now < $start) {
                                            echo '🔜 PROGRAMADO';
                                        } elseif ($now > $end) {
                                            echo '⏰ EXPIRADO';
                                        } else {
                                            echo '✅ ACTIVO';
                                        }
                                        ?>
                                    </div>
                                </div>
                                <div class="ad-content" style="padding: 16px;">
                                    <h4 style="margin: 0 0 8px 0; font-size: 1.1rem; color: var(--text);"><?= h($ad['title']) ?></h4>
                                    <p style="margin: 0 0 12px 0; color: var(--muted); font-size: 0.9rem; line-height: 1.4;"><?= h(limit_text($ad['description'] ?? '', 120)) ?></p>
                                    <div class="ad-footer" style="display: flex; justify-content: space-between; align-items: center; font-size: 0.8rem;">
                                        <span class="ad-advertiser" style="color: var(--accent); font-weight: 600;"><?= h($ad['advertiser']) ?></span>
                                        <span class="ad-sponsored" style="color: var(--muted);">
                                            <?= h(fdt_madrid($ad['start_date'], 'd/m')) ?> - <?= h(fdt_madrid($ad['end_date'], 'd/m')) ?>
                                        </span>
                                    </div>
                                </div>
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <script>
            // Script para cerrar la sección de anuncios (cookie de 24 horas)
            document.addEventListener('DOMContentLoaded', function() {
                const closeBtn = document.getElementById('close-ads-btn');
                const adsSection = document.getElementById('ads-section');
                
                if (closeBtn && adsSection) {
                    closeBtn.addEventListener('click', function() {
                        // Usar cookie para persistencia (24 horas)
                        const date = new Date();
                        date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // 24 horas
                        const expires = "expires=" + date.toUTCString();
                        document.cookie = "ads_section_closed=true;" + expires + ";path=/";
                        
                        // Animación de desvanecimiento
                        adsSection.style.opacity = '0';
                        adsSection.style.transition = 'opacity 0.3s ease';
                        setTimeout(function() {
                            adsSection.style.display = 'none';
                        }, 300);
                    });
                }
            });
            </script>
        </div>
    <?php endif; ?>

    <!-- Cumpleaños de AMIGOS -->
    <?php
    $current_month = date('m');
    
    // Consulta para obtener amigos
    try {
        $friends_stmt = $db->prepare("
            SELECT u.id, u.username, u.birth_date, u.profile_image
            FROM friends f
            JOIN users u ON (
                (f.user1_id = ? AND u.id = f.user2_id) OR 
                (f.user2_id = ? AND u.id = f.user1_id)
            )
            WHERE f.status = 'accepted'
            AND DATE_FORMAT(u.birth_date, '%m-%d') = DATE_FORMAT(CURDATE(), '%m-%d')
            AND u.id != ?
            ORDER BY DAY(u.birth_date)
        ");
        
        $friends_stmt->execute([
            $_SESSION['user']['id'],
            $_SESSION['user']['id'],
            $_SESSION['user']['id']
        ]);
        
        $friend_birthdays = $friends_stmt->fetchAll();
    } catch (Exception $e) {
        $friend_birthdays = [];
        error_log("Error obteniendo cumpleaños: " . $e->getMessage());
    }
    
    // ¿Es mi cumpleaños hoy?
    $isMyBirthday = false;
    $my_username = '';
    try {
        $stmt_me = $db->prepare("SELECT birth_date, username FROM users WHERE id = ? LIMIT 1");
        $stmt_me->execute([$_SESSION['user']['id']]);
        $row_me = $stmt_me->fetch();
        if ($row_me && date('m-d') === date('m-d', strtotime($row_me['birth_date']))) {
            $isMyBirthday = true;
            $my_username = $row_me['username'];
        }
    } catch (Exception $e) {
        error_log("Error verificando cumpleaños propio: " . $e->getMessage());
    }

    // Verificar si el usuario ha cerrado el panel de cumpleaños
    $birthday_panel_closed = isset($_COOKIE['birthday_panel_closed']) ? $_COOKIE['birthday_panel_closed'] === 'true' : false;

    if ((!empty($friend_birthdays) || $isMyBirthday) && !$birthday_panel_closed): ?>
        <div class="card bday-card" id="birthdays-card">
            <?php if ($isMyBirthday): ?>
                <canvas id="bday-confetti"></canvas>
            <?php endif; ?>
            
            <button id="birthdays-close" class="bday-close" aria-label="Cerrar"><i class="fas fa-xmark"></i></button>
            
            <script>
            (function(){
                // Usar cookie para persistencia entre sesiones (24 horas)
                function setCookie(name, value, days) {
                    const date = new Date();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                    const expires = "expires=" + date.toUTCString();
                    document.cookie = name + "=" + value + ";" + expires + ";path=/";
                }
                
                function getCookie(name) {
                    const nameEQ = name + "=";
                    const ca = document.cookie.split(';');
                    for(let i=0; i < ca.length; i++) {
                        let c = ca[i];
                        while (c.charAt(0) === ' ') c = c.substring(1);
                        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length);
                    }
                    return null;
                }
                
                function hideCard(){ 
                    var c=document.getElementById('birthdays-card'); 
                    if(c){ 
                        c.style.opacity = '0';
                        c.style.transition = 'opacity 0.3s ease';
                        setTimeout(function() {
                            c.style.display='none'; 
                        }, 300);
                    } 
                }
                
                function confetti(){
                    const canvas = document.getElementById('bday-confetti');
                    if(!canvas) return;
                    
                    // Ajustar el tamaño del canvas al contenedor
                    const container = document.getElementById('birthdays-card');
                    const w = canvas.width = container.offsetWidth;
                    const h = canvas.height = container.offsetHeight;
                    
                    const ctx = canvas.getContext('2d');
                    const pieces = Array.from({length: 200}, () => ({
                        x: Math.random() * w,
                        y: -20 - Math.random() * 100,
                        r: 2 + Math.random() * 4,
                        c: ['#ffd166','#ff7eb3','#7bdff2','#b2f7ef','#caffbf','#9bf6ff','#ffc6ff','#fdffb6'][Math.floor(Math.random()*8)],
                        s: 0.5 + Math.random() * 3,
                        a: Math.random() * Math.PI * 2
                    }));
                    
                    let t = 0;
                    let animationId;
                    
                    function draw() {
                        ctx.clearRect(0, 0, w, h);
                        
                        pieces.forEach(p => {
                            p.y += p.s;
                            p.x += Math.sin(t/30 + p.a) * 0.8;
                            
                            // Si el confeti sale de la parte inferior, reiniciarlo en la parte superior
                            if(p.y > h + 20) {
                                p.y = -20;
                                p.x = Math.random() * w;
                            }
                            
                            // Si el confeti sale de los lados, reiniciarlo
                            if(p.x < -20 || p.x > w + 20) {
                                p.x = Math.random() * w;
                                p.y = -20;
                            }
                            
                            ctx.beginPath();
                            ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
                            ctx.fillStyle = p.c;
                            ctx.fill();
                        });
                        
                        t++;
                        animationId = requestAnimationFrame(draw);
                    }
                    
                    // Iniciar la animación
                    draw();
                    
                    // Detener después de 8 segundos
                    setTimeout(() => {
                        cancelAnimationFrame(animationId);
                        ctx.clearRect(0, 0, w, h);
                    }, 8000);
                }
                
                document.addEventListener('DOMContentLoaded', function(){
                    if (getCookie('birthday_panel_closed') === 'true') { 
                        hideCard(); 
                        return;
                    }
                    
                    var close = document.getElementById('birthdays-close');
                    if(close){ 
                        close.addEventListener('click', function(){ 
                            setCookie('birthday_panel_closed', 'true', 1); // Expira en 1 día
                            hideCard(); 
                        }); 
                    }
                    
                    // Solo activar confeti si es MI cumpleaños
                    var me = document.querySelector('.bday-me');
                    if(me) { 
                        setTimeout(confetti, 200); 
                    }
                });
            })();
            </script>

            <div class="bday-header">
                <div class="bday-icon"><i class="fas fa-birthday-cake"></i></div>
                <h3 class="bday-title" style="margin:0;font-size:1.1rem;">
                    <?php echo $isMyBirthday ? '¡Feliz Cumpleaños!' : 'Cumpleaños de hoy'; ?>
                </h3>
            </div>

            <?php if ($isMyBirthday): ?>
                <div class="bday-me">
                    <i class="fas fa-crown" style="color:var(--warning);"></i>
                    <span>🎉 ¡Feliz cumpleaños @<?php echo h($my_username); ?>! 🎂</span>
                </div>
            <?php endif; ?>

            <?php if (!empty($friend_birthdays)): ?>
                <p style="margin-bottom:12px;color:var(--muted);font-size:0.95rem;">
                    <i class="fas fa-gift"></i> Hoy es el cumpleaños de tus amigos. ¡Envíales tus felicitaciones!
                </p>
                
                <div class="bday-list" style="display:flex;flex-wrap:wrap;gap:12px">
                    <?php foreach ($friend_birthdays as $friend): ?>
                        <div class="bday-chip">
                            <div class="bday-avatar" style="overflow:hidden;border-radius:50%;padding:0;background:none;">
                                <?php echo strtoupper(substr($friend['username'], 0, 1)); ?>
                            </div>
                            <div>
                                <a href="./?r=profile/friend&id=<?php echo h($friend['id']); ?>" class="username-link">@<?php echo h($friend['username']); ?></a>
                                <div class="muted" style="font-size:0.8rem">
                                    <?php echo date('d/m', strtotime($friend['birth_date'])); ?>
                                    <span style="color:var(--warning);font-weight:bold;"> ¡Hoy!</span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <!-- FEED DE PUBLICACIONES -->
    <?php if (!empty($postsWithPhotos)): ?>
        <div class="thirty-feed">
            <?php foreach ($postsWithPhotos as $p): ?>
                <div class="thirty-post card" id="post-<?php echo h($p['id']); ?>">
                    <!-- Encabezado con información del autor -->
                    <div class="post-meta">
                        <div style="display:flex;align-items:center;gap:12px">
                            <div class="user-badge" style="overflow:hidden;border-radius:50%;padding:0;background:none;">
                                <?php
                                $__av = '';
                                if (!empty($p['author_avatar_url'])) { $__av = $p['author_avatar_url']; }
                                elseif (!empty($p['avatar_url'])) { $__av = $p['avatar_url']; }
                                if ($__av && substr($__av,0,9)==='/uploads/' && isset($__base) && $__base !== '' && $__base !== '/') { $__av = $__base . $__av; }
                                $__ini = strtoupper(substr($p['username'] ?? 'U', 0, 1));
                                ?>
                                <?php if ($__av): ?>
                                    <img src="<?php echo h($__av); ?>" alt="Avatar" style="width:36px;height:36px;border-radius:50%;object-fit:cover;display:block;">
                                <?php else: ?>
                                    <?php echo h($__ini); ?>
                                <?php endif; ?>
                            </div>
                            <div>
                                <a href="<?php echo ($p['author_id'] == $_SESSION['user']['id']) ? './?r=profile' : './?r=profile/friend&id='.h($p['author_id']); ?>" class="username-link">@<?php echo h($p['username'] ?? 'usuario'); ?></a>
                                <div class="muted" style="font-size:0.85rem">
                                    <i class="far fa-clock"></i> <?php echo h(fdt_madrid($p['created_at'], 'd/m/Y · H:i')); ?>
                                </div>
                            </div>
                        </div>
                        <div class="post-stats">
                            <div style="text-align:center">
                                <div style="font-size:1.1rem;font-weight:700;color:var(--accent)" class="like-count"><?php echo h($p['like_count'] ?? 0); ?></div>
                                <div class="muted" style="font-size:0.8rem">Likes</div>
                            </div>
                            <div style="text-align:center">
                                <div style="font-size:1.1rem;font-weight:700;color:var(--accent2)"><?php echo h($p['comment_count'] ?? 0); ?></div>
                                <div class="muted" style="font-size:0.8rem">Com.</div>
                            </div>
                            <div style="text-align:center">
                                <div style="font-size:1.1rem;font-weight:700;color:var(--purple-light)"><?php echo h($p['tag_count'] ?? 0); ?></div>
                                <div class="muted" style="font-size:0.8rem">Tags</div>
                            </div>
                        </div>
                    </div>

                    <!-- Contenido multimedia -->
                    <div class="post-content" style="margin-bottom:16px">
                        <div class="post-media">
                            <img src="<?php echo h($p['url']); ?>" alt="Publicación" loading="lazy" decoding="async" style="width:100%;display:block">
                        </div>

                        <?php if (!empty($p['caption'])): ?>
                            <div class="post-caption">
                                <p style="margin:0;line-height:1.5"><?php echo h($p['caption']); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Etiquetas reales -->
                    <?php if (!empty($p['tags'])): ?>
                        <div class="post-connections">
                            <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center">
                                <span class="muted" style="font-size:0.9rem"><i class="fas fa-link"></i> Conecta con:</span>
                                <?php foreach ($p['tags'] as $tag): ?>
                                    <!-- ENLACE CORREGIDO: buscar ID del usuario etiquetado y usar ruta correcta -->
                                    <?php
                                    // Buscar el ID del usuario etiquetado por su username
                                    try {
                                        $tag_user_stmt = $db->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
                                        $tag_user_stmt->execute([$tag]);
                                        $tag_user = $tag_user_stmt->fetch();
                                        $tag_user_id = $tag_user ? $tag_user['id'] : null;
                                    } catch (Exception $e) {
                                        $tag_user_id = null;
                                        error_log("Error buscando usuario etiquetado: " . $e->getMessage());
                                    }
                                    ?>
                                    <?php if ($tag_user_id): ?>
                                        <a href="./?r=profile/friend&id=<?php echo h($tag_user_id); ?>" class="connection-tag">@<?php echo h($tag); ?></a>
                                    <?php else: ?>
                                        <span class="connection-tag">@<?php echo h($tag); ?></span>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Acciones del post -->
                    <div class="post-actions">
                        <form method="post" action="./?r=posts/like&id=<?php echo h($p['id']); ?>" class="like-form" style="margin:0">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="like_action" value="<?php echo $p['is_liked'] ? 'unlike' : 'like'; ?>">
                            <button type="submit" class="thirty-btn like-btn <?php echo $p['is_liked'] ? 'liked' : ''; ?>" style="width:100%">
                                <i class="fas fa-heart"></i>
                                <span class="like-text"><?php echo $p['is_liked'] ? 'Quitar like' : 'Dar like'; ?></span>
                            </button>
                        </form>
                        <a href="./?r=posts/view&id=<?php echo h($p['id']); ?>" class="thirty-btn comment-btn" style="text-decoration:none">
                            <i class="fas fa-comment"></i>
                            <span>Comentar</span>
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="card" style="text-align:center;padding:40px 20px">
            <div style="font-size:4rem;margin-bottom:20px;color:var(--muted)">
                <i class="fas fa-image"></i>
            </div>
            <h3 style="margin-bottom:12px">No hay publicaciones aún</h3>
            <p class="muted" style="margin-bottom:20px">Sé el primero en compartir una foto y conectar con otros</p>
            <a href="./?r=posts/create" class="btn primary">
                <i class="fas fa-plus"></i> Crear primera publicación
            </a>
        </div>
    <?php endif; ?>
</div>

<!-- Notificación flotante -->
<div id="notification" class="notification">
    <i class="fas fa-check-circle"></i>
    <span id="notification-text">Operación realizada con éxito</span>
</div>

<script>
// Función para mostrar notificaciones
function showNotification(message, isError = false) {
    const notification = document.getElementById('notification');
    const notificationText = document.getElementById('notification-text');
    
    if (!notification || !notificationText) {
        console.log('📢 ' + message);
        return;
    }
    
    notificationText.textContent = message;
    
    if (isError) {
        notification.classList.add('error');
    } else {
        notification.classList.remove('error');
    }
    
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 4000);
}

// Sistema de likes con AJAX
document.addEventListener('DOMContentLoaded', function() {
    const likeForms = document.querySelectorAll('.like-form');
    
    likeForms.forEach(form => {
        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const button = this.querySelector('.like-btn');
            const likeText = this.querySelector('.like-text');
            const likeCount = this.closest('.thirty-post')?.querySelector('.like-count');
            const formData = new FormData(this);
            
            if (!button) return;
            
            button.disabled = true;
            
            try {
                const response = await fetch(this.action, {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    if (result.liked) {
                        button.classList.add('liked');
                        likeText.textContent = 'Quitar like';
                        this.querySelector('input[name="like_action"]').value = 'unlike';
                        if (likeCount) likeCount.textContent = parseInt(likeCount.textContent) + 1;
                    } else {
                        button.classList.remove('liked');
                        likeText.textContent = 'Dar like';
                        this.querySelector('input[name="like_action"]').value = 'like';
                        if (likeCount) likeCount.textContent = parseInt(likeCount.textContent) - 1;
                    }
                    
                    showNotification(result.liked ? 'Like agregado correctamente' : 'Like eliminado correctamente');
                } else {
                    showNotification('Error al procesar el like', true);
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('Error de conexión', true);
            }
            
            button.disabled = false;
        });
    });

    // Efecto hover en las publicaciones
    document.querySelectorAll('.thirty-post').forEach(post => {
        post.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 12px 30px rgba(0, 0, 0, 0.3)';
        });
        
        post.addEventListener('mouseleave', function() {
            this.style.transform = '';
            this.style.boxShadow = '';
        });
    });
});
</script>