<?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>
.ranking-container {
    margin-top: 20px;
}

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

.ranking-item {
    transition: all 0.3s ease;
    border: 1px solid var(--border);
    margin-bottom: 10px;
}

.ranking-item:hover {
    border-color: var(--accent);
    transform: translateY(-2px);
}

.ranking-position {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: var(--accent);
    color: var(--btnText);
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.1rem;
}

.ranking-1 .ranking-position {
    background: linear-gradient(135deg, #FFD700, #FFA500);
}

.ranking-2 .ranking-position {
    background: linear-gradient(135deg, #C0C0C0, #A9A9A9);
}

.ranking-3 .ranking-position {
    background: linear-gradient(135deg, #CD7F32, #8C6B46);
}

.user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--accent), var(--accent2));
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    font-size: 1.2rem;
}

.points-display {
    font-size: 1.4rem;
    font-weight: 800;
    color: var(--accent);
}

.birthday-item {
    transition: all 0.3s ease;
    border: 1px solid var(--border);
    margin-bottom: 10px;
}

.birthday-item:hover {
    border-color: var(--warning);
    transform: translateY(-2px);
}

.birthday-avatar {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    background: linear-gradient(135deg, #ff7aa2, #ffcf66);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #111;
    font-weight: 800;
    font-size: 1.1rem;
}
</style>

<div class="ranking-container">
    <div style="display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 20px;">
        <!-- Columna principal -->
        <div>
            <!-- EXPLICACIÓN DEL RANKING -->
            <div class="card ranking-header">
                <h2 style="margin:0 0 12px 0; display:flex; align-items:center; gap:10px">
                    <i class="fas fa-trophy" style="color: var(--accent);"></i> 
                    ¿Cómo funciona el ranking?
                </h2>
                <p class="muted" style="margin:0 0 15px; font-size: 1rem;">
                    Cada amigo suma puntos por sus interacciones contigo. La suma total ordena la clasificación.
                </p>
                <div style="display: grid; gap: 8px;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="background: rgba(124,209,255,0.2); padding: 6px 12px; border-radius: 20px; font-weight: 600; color: var(--accent);">+1</div>
                        <span>punto por cada <b>like</b> que tu amigo da a tus publicaciones</span>
                    </div>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="background: rgba(185,156,255,0.2); padding: 6px 12px; border-radius: 20px; font-weight: 600; color: var(--accent2);">+2</div>
                        <span>puntos por cada <b>comentario</b> que tu amigo deja en tus publicaciones</span>
                    </div>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="background: rgba(255,156,242,0.2); padding: 6px 12px; border-radius: 20px; font-weight: 600; color: var(--accent3);">+3</div>
                        <span>puntos por cada <b>etiqueta</b> que tu amigo hace de tu @usuario</span>
                    </div>
                </div>
                <div class="muted" style="margin-top: 15px; font-size: 0.9rem; padding: 10px; background: rgba(255,255,255,0.05); border-radius: 8px;">
                    <i class="fas fa-equals"></i> 
                    <b>Puntuación total</b> = (Likes × 1) + (Comentarios × 2) + (Etiquetas × 3)
                </div>
            </div>

            <!-- RANKING -->
            <div class="card" style="margin-top: 20px;">
                <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin:0; display:flex; align-items:center; gap:10px">
                        <i class="fas fa-list-ol" style="color: var(--accent2);"></i> 
                        Ranking de amigos
                    </h3>
                    <a href="./?r=ranking/refresh" class="btn sm" style="font-size: 0.8rem;">
                        <i class="fas fa-sync-alt"></i> Actualizar
                    </a>
                </div>

                <?php if (empty($ranking)): ?>
                    <div style="text-align: center; padding: 40px 20px;">
                        <div style="font-size: 3rem; margin-bottom: 15px; color: var(--muted);">
                            <i class="fas fa-trophy"></i>
                        </div>
                        <h4 style="margin-bottom: 10px; color: var(--muted);">Aún no hay interacciones</h4>
                        <p class="muted">Empieza a compartir publicaciones y conversar con tus amigos para ver resultados aquí.</p>
                        <a href="./?r=posts/create" class="btn primary" style="margin-top: 15px;">
                            <i class="fas fa-plus"></i> Crear publicación
                        </a>
                    </div>
                <?php else: ?>
                    <div style="display: grid; gap: 12px;">
                        <?php foreach ($ranking as $i => $row): ?>
                            <?php
                                $friendId = isset($row['id']) ? $row['id'] : '';
                                $friendUsername = isset($row['username']) ? $row['username'] : '';
                                $likes = (int)($row['likes_count'] ?? 0);
                                $comments = (int)($row['comments_count'] ?? 0);
                                $tags = (int)($row['tags_count'] ?? 0);
                                $points = (int)($row['points'] ?? 0);

                                $tooltip = $likes . ' like' . ($likes===1 ? '' : 's') . 
                                          ' + ' . $comments . ' comentario' . ($comments===1 ? '' : 's') . 
                                          ' + ' . $tags . ' etiqueta' . ($tags===1 ? '' : 's') . 
                                          ' = ' . $points . ' puntos';

                                $profileHref = './?r=profile/friend&id=' . rawurlencode($friendId);
                                $rankingClass = $i < 3 ? 'ranking-' . ($i + 1) : '';
                            ?>
                            <div class="card ranking-item <?= $rankingClass ?>" style="padding: 15px;">
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <div class="ranking-position">
                                        <?= $i + 1 ?>
                                    </div>

                                    <div class="user-avatar">
                                        <?= strtoupper(substr($friendUsername, 0, 1)) ?>
                                    </div>

                                    <div style="flex: 1;">
                                        <a href="<?= h($profileHref) ?>" style="font-weight: 600; color: inherit; text-decoration: none; font-size: 1.1rem;">
                                            @<?= h($friendUsername) ?>
                                        </a>
                                        <div style="display: flex; gap: 15px; margin-top: 5px;">
                                            <span class="muted" style="font-size: 0.85rem;">
                                                <i class="fas fa-heart" style="color: var(--accent3);"></i> <?= $likes ?> likes
                                            </span>
                                            <span class="muted" style="font-size: 0.85rem;">
                                                <i class="fas fa-comment" style="color: var(--accent);"></i> <?= $comments ?> comentarios
                                            </span>
                                            <span class="muted" style="font-size: 0.85rem;">
                                                <i class="fas fa-tag" style="color: var(--accent2);"></i> <?= $tags ?> etiquetas
                                            </span>
                                        </div>
                                    </div>

                                    <div style="text-align: right;">
                                        <div title="<?= h($tooltip) ?>" class="points-display" style="cursor: help;">
                                            <?= $points ?>
                                        </div>
                                        <div class="muted" style="font-size: 0.85rem;">puntos</div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Columna lateral -->
        <aside>
            <!-- CUMPLEAÑOS PRÓXIMOS -->
            <div class="card">
                <h3 style="margin:0 0 15px 0; display:flex; align-items:center; gap:10px">
                    <i class="fas fa-birthday-cake" style="color: var(--warning);"></i> 
                    Cumpleaños próximos
                </h3>
                <p class="muted" style="margin-bottom: 15px; font-size: 0.9rem;">
                    <i class="fas fa-info-circle"></i> Próximos 30 días
                </p>

                <?php if (empty($birthdays)): ?>
                    <div style="text-align: center; padding: 20px;">
                        <div style="font-size: 2rem; margin-bottom: 10px; color: var(--muted);">
                            <i class="fas fa-birthday-cake"></i>
                        </div>
                        <p class="muted">No hay cumpleaños próximos de tus amigos.</p>
                    </div>
                <?php else: ?>
                    <div style="display: grid; gap: 12px;">
                        <?php foreach ($birthdays as $b): ?>
                            <?php
                                $bId = isset($b['id']) ? $b['id'] : '';
                                $bUser = isset($b['username']) ? $b['username'] : '';
                                $bDate = isset($b['birth_date']) ? $b['birth_date'] : '';
                                $bHref = './?r=profile/friend&id=' . rawurlencode($bId);
                                
                                $daysUntil = floor((strtotime(date('Y') . '-' . date('m-d', strtotime($bDate))) - time()) / (60 * 60 * 24));
                                $daysUntil = $daysUntil < 0 ? $daysUntil + 365 : $daysUntil;
                                
                                $isToday = $daysUntil === 0;
                            ?>
                            <div class="birthday-item card" style="padding: 12px;">
                                <div style="display: flex; align-items: center; gap: 12px;">
                                    <div class="birthday-avatar">
                                        🎂
                                    </div>
                                    <div style="flex: 1;">
                                        <a href="<?= h($bHref) ?>" style="font-weight: 600; color: inherit; text-decoration: none;">
                                            @<?= h($bUser) ?>
                                        </a>
                                        <div style="display: flex; justify-content: between; align-items: center; margin-top: 4px;">
                                            <span class="muted" style="font-size: 0.85rem;">
                                                <?= date('d/m', strtotime($bDate)) ?>
                                            </span>
                                            <?php if ($isToday): ?>
                                                <span style="background: var(--success); color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">
                                                    ¡Hoy!
                                                </span>
                                            <?php else: ?>
                                                <span class="muted" style="font-size: 0.75rem;">
                                                    en <?= $daysUntil ?> día<?= $daysUntil !== 1 ? 's' : '' ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- INFORMACIÓN ADICIONAL -->
            <div class="card" style="margin-top: 20px; border-left: 4px solid var(--border-light); background: rgba(255,255,255,0.02);">
                <div style="display: flex; align-items: flex-start; gap: 10px;">
                    <i class="fas fa-info-circle" style="color: var(--accent); margin-top: 2px;"></i>
                    <div>
                        <h4 style="margin: 0 0 8px 0; font-size: 1rem;">Actualización en tiempo real</h4>
                        <div class="muted" style="font-size: 0.85rem; line-height: 1.4;">
                            Las puntuaciones se recalculan automáticamente. Las nuevas interacciones (likes, comentarios, etiquetas) se reflejan inmediatamente en el ranking.
                        </div>
                    </div>
                </div>
            </div>
        </aside>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Efectos hover mejorados para los items del ranking
    const rankingItems = document.querySelectorAll('.ranking-item');
    rankingItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-3px)';
            this.style.boxShadow = '0 6px 20px rgba(0, 0, 0, 0.15)';
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '';
        });
    });

    // Efectos para los cumpleaños
    const birthdayItems = document.querySelectorAll('.birthday-item');
    birthdayItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });

    // Tooltips para los puntos
    const pointsDisplays = document.querySelectorAll('.points-display');
    pointsDisplays.forEach(display => {
        display.addEventListener('click', function() {
            const tooltip = this.getAttribute('title');
            if (tooltip) {
                alert(tooltip);
            }
        });
    });
});
</script>