<?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();
$rawGenre = normalizeMetaParam($_GET['name'] ?? $_GET['id'] ?? '');
$unknownGenreLabel = genreName('');
$genreValue = ($rawGenre === $unknownGenreLabel || strcasecmp($rawGenre, 'unknown') === 0) ? '' : $rawGenre;
$genreLabel = genreName($genreValue);

$params = [];
$genreWhere = metaWhereSql('s.genre', ':genre', $genreValue, $params);
$baseWhere = "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND $genreWhere";

$songs = fetchSongs($baseWhere, $params, 's.artist ASC, s.album ASC, s.track_no IS NULL ASC, s.track_no ASC, s.title ASC', 500);

$summaryStmt = $pdo->prepare("
    SELECT COUNT(*) AS song_count,
           COUNT(DISTINCT COALESCE(NULLIF(TRIM(s.artist), ''), '__unknown_artist__')) AS artist_count,
           COUNT(DISTINCT COALESCE(NULLIF(TRIM(s.album), ''), '__unknown_album__')) AS album_count,
           COALESCE(SUM(s.play_count), 0) AS total_plays,
           MAX(s.id) AS cover_song_id,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.cover_hash, '') ORDER BY s.play_count DESC, s.id DESC SEPARATOR '||'), '||', 1) AS cover_hash,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.metadata_updated_at, '') ORDER BY s.play_count DESC, s.id DESC SEPARATOR '||'), '||', 1) AS metadata_updated_at,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.updated_at, '') ORDER BY s.play_count DESC, s.id DESC SEPARATOR '||'), '||', 1) AS updated_at
    FROM songs s
    WHERE $baseWhere
");
$summaryStmt->execute($params);
$summary = $summaryStmt->fetch() ?: [];

$popularSongs = fetchSongs($baseWhere, $params, 's.play_count DESC, s.title ASC', 6);
$likedSongs = fetchSongs($baseWhere . ' AND l.id IS NOT NULL', $params, 'l.created_at DESC, s.play_count DESC, s.title ASC', 6);
$recommendSongs = fetchSongs($baseWhere, $params, 'COALESCE(r.rating, 0) DESC, COALESCE(l.id, 0) DESC, s.play_count ASC, s.updated_at DESC, s.id DESC', 8);

$recentStmt = $pdo->prepare("
    " . baseSongSelectSql() . "
    INNER JOIN (
        SELECT song_id, MAX(played_at) AS last_played_at
        FROM play_history
        GROUP BY song_id
    ) recent ON recent.song_id = s.id
    WHERE $baseWhere
    ORDER BY recent.last_played_at DESC
    LIMIT 6
");
$recentStmt->execute($params);
$recentSongs = $recentStmt->fetchAll();

$coverSong = [
    'id' => $summary['cover_song_id'] ?? null,
    'cover_hash' => $summary['cover_hash'] ?? '',
    'metadata_updated_at' => $summary['metadata_updated_at'] ?? '',
    'updated_at' => $summary['updated_at'] ?? '',
];
$canBulkEditGenre = function_exists('hasPermission') && hasPermission('metadata_bulk_edit');

renderHeader($genreLabel, 'genres');
?>
<div class="genre-detail-page detail-page">
    <section class="genre-hero-card">
        <div class="genre-cover-stack" aria-hidden="true">
            <img src="<?php echo h(!empty($coverSong['id']) ? coverUrl($coverSong) : 'assets/img/default-cover.svg'); ?>" alt="" class="genre-hero-cover" loading="lazy" width="220" height="220" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
        </div>
        <div class="genre-hero-copy">
            <span class="detail-kicker">장르</span>
            <h1 class="page-main-title"><?php echo h($genreLabel); ?></h1>
            <p class="page-subtitle">이 장르의 곡을 모아보고 바로 이어 들을 수 있습니다.</p>
            <?php renderStatGrid([
                ['label' => '곡 수', 'value' => number_format((int)($summary['song_count'] ?? 0))],
                ['label' => '아티스트', 'value' => number_format((int)($summary['artist_count'] ?? 0))],
                ['label' => '앨범', 'value' => number_format((int)($summary['album_count'] ?? 0))],
                ['label' => '총 재생', 'value' => number_format((int)($summary['total_plays'] ?? 0))],
            ]); ?>
            <div class="list-play-actions genre-action-row">
                <?php if (!empty($songs)): ?>
                    <button type="button" class="btn btn-primary btn-play-all"><i class="fas fa-play"></i> 장르 전체 재생</button>
                    <button type="button" class="btn btn-secondary btn-shuffle-all"><i class="fas fa-random"></i> 셔플 재생</button>
                    <button type="button" class="btn btn-secondary btn-add-page-to-queue"><i class="fas fa-list"></i> 대기열 추가</button>
                <?php else: ?>
                    <a class="btn btn-secondary" href="genres.php"><i class="fa-solid fa-tags"></i> 장르 목록으로 이동</a>
                <?php endif; ?>
                <?php if ($canBulkEditGenre): ?>
                    <a class="btn btn-secondary" href="admin/bulk_edit.php?search=<?php echo rawurlencode($genreLabel); ?>"><i class="fa-solid fa-wand-magic-sparkles"></i> 표기 통합 확인</a>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <?php if (empty($songs)): ?>
        <section class="home-section">
            <div class="empty-list-state">
                <i class="fa-solid fa-tags"></i>
                <p>이 장르에 표시할 곡이 없습니다.</p>
                <a class="btn btn-secondary" href="genres.php">장르 목록으로 이동</a>
            </div>
        </section>
    <?php else: ?>
        <section class="home-section genre-recommend-section">
            <div class="section-heading-row">
                <div>
                    <h2 class="section-title">이 장르에서 다시 듣기 좋은 곡</h2>
                    <p class="section-subtitle">좋아요, 별점, 재생 수를 기준으로 가볍게 골랐습니다.</p>
                </div>
            </div>
            <div class="genre-recommend-grid">
                <?php foreach ($recommendSongs as $song): ?>
                    <a class="genre-recommend-card"
                       href="song.php?id=<?php echo h($song['id']); ?>">
                        <img src="<?php echo h(coverUrl($song)); ?>" alt="" loading="lazy" width="72" height="72" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                        <span>
                            <b><?php echo h($song['title']); ?></b>
                            <small><?php echo h(artistName($song['artist'] ?? '')); ?></small>
                        </span>
                        <span class="genre-recommend-cue" aria-hidden="true"><i class="fas fa-chevron-right"></i></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </section>

        <div class="genre-insight-grid">
            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">많이 들은 곡</h2>
                </div>
                <?php if (empty($popularSongs)): ?>
                    <p class="empty-text">아직 재생 기록이 없습니다.</p>
                <?php else: ?>
                    <div class="artist-mini-list">
                        <?php foreach ($popularSongs as $index => $song): ?>
                            <a class="artist-mini-row" href="song.php?id=<?php echo h($song['id']); ?>">
                                <strong><?php echo number_format($index + 1); ?></strong>
                                <img src="<?php echo h(coverUrl($song)); ?>" alt="" loading="lazy" width="44" height="44" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <span><b><?php echo h($song['title']); ?></b><small><?php echo number_format((int)($song['play_count'] ?? 0)); ?>회 재생</small></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">최근 재생</h2>
                </div>
                <?php if (empty($recentSongs)): ?>
                    <p class="empty-text">최근 재생 기록이 없습니다.</p>
                <?php else: ?>
                    <div class="artist-mini-list">
                        <?php foreach ($recentSongs as $song): ?>
                            <a class="artist-mini-row artist-mini-row-compact" href="song.php?id=<?php echo h($song['id']); ?>">
                                <img src="<?php echo h(coverUrl($song)); ?>" alt="" loading="lazy" width="44" height="44" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <span><b><?php echo h($song['title']); ?></b><small><?php echo h(formatDuration($song['duration'] ?? null)); ?></small></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">좋아요한 곡</h2>
                </div>
                <?php if (empty($likedSongs)): ?>
                    <p class="empty-text">이 장르에서 좋아요한 곡이 없습니다.</p>
                <?php else: ?>
                    <div class="artist-mini-list">
                        <?php foreach ($likedSongs as $song): ?>
                            <a class="artist-mini-row artist-mini-row-compact" href="song.php?id=<?php echo h($song['id']); ?>">
                                <img src="<?php echo h(coverUrl($song)); ?>" alt="" loading="lazy" width="44" height="44" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <span><b><?php echo h($song['title']); ?></b><small><?php echo h(artistName($song['artist'] ?? '')); ?></small></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>
        </div>

        <section class="home-section genre-song-section">
            <div class="section-heading-row">
                <div>
                    <h2 class="section-title">전체 곡</h2>
                    <p class="section-subtitle">아티스트, 앨범, 트랙 순서 기준으로 정리했습니다.</p>
                </div>
                <span class="settings-muted"><?php echo number_format(count($songs)); ?>곡</span>
            </div>
            <?php renderSongList($songs, ['show_play_actions' => false]); ?>
        </section>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
