<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/layout.php';

$pdo = getDBConnection();
$genres = $pdo->query("
    SELECT COALESCE(NULLIF(TRIM(genre), ''), '알 수 없는 장르') AS genre_label,
           COUNT(*) AS song_count,
           COUNT(DISTINCT COALESCE(NULLIF(TRIM(artist), ''), '알 수 없는 아티스트')) AS artist_count,
           COUNT(DISTINCT COALESCE(NULLIF(TRIM(album), ''), '알 수 없는 앨범')) AS album_count,
           COALESCE(SUM(play_count), 0) AS total_plays
    FROM songs
    WHERE is_missing = 0
    GROUP BY genre_label
    ORDER BY genre_label ASC
")->fetchAll();

renderHeader('장르', 'genres');
?>
<div class="library-page">
    <div class="page-title-section">
        <h1 class="page-main-title">장르</h1>
        <p class="page-subtitle">장르별 보관함 규모와 재생 흐름을 확인합니다.</p>
    </div>
    <div class="genre-card-grid">
        <?php foreach ($genres as $genre): ?>
            <a class="genre-card" href="genre.php?name=<?php echo urlencode($genre['genre_label']); ?>">
                <h2><?php echo h($genre['genre_label']); ?></h2>
                <p><?php echo number_format($genre['song_count']); ?>곡 · <?php echo number_format($genre['artist_count']); ?>아티스트 · <?php echo number_format($genre['album_count']); ?>앨범</p>
                <span><?php echo number_format($genre['total_plays']); ?>회 재생</span>
            </a>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
