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

$pdo = getDBConnection();
$view = isset($_GET['view']) ? $_GET['view'] : 'home';
$sort = isset($_GET['sort']) ? (string)$_GET['sort'] : (string)($_COOKIE['melon_lite_library_sort'] ?? 'recent');
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$genreFilter = isset($_GET['genre']) ? trim($_GET['genre']) : '';
$yearFilter = isset($_GET['year']) ? trim((string)$_GET['year']) : '';
$extFilter = isset($_GET['ext']) ? trim($_GET['ext']) : '';
$onlyLiked = isset($_GET['only_liked']) ? intval($_GET['only_liked']) : 0;
$tagFilter = isset($_GET['tag']) ? (int)$_GET['tag'] : 0;
$page = max(1, (int)($_GET['page'] ?? 1));
$popularTags = getPopularTags(18);
$librarySortOptions = [
    'recent' => '최근 등록순',
    'title' => '제목순',
    'artist' => '아티스트순',
    'album' => '앨범순',
    'recent_played' => '최근 재생순',
    'popular' => '많이 들은 순',
    'liked' => '좋아요순',
    'year_desc' => '연도 최신순',
    'year_asc' => '연도 오래된순',
];
if (!isset($librarySortOptions[$sort])) {
    $sort = 'recent';
}
if ($view === 'all' && !headers_sent()) {
    setcookie('melon_lite_library_sort', $sort, [
        'expires' => time() + 60 * 60 * 24 * 180,
        'path' => '/',
        'samesite' => 'Lax',
    ]);
}

if ($view === 'home' && ($search !== '' || $genreFilter !== '' || $yearFilter !== '' || $extFilter !== '' || $onlyLiked === 1 || $tagFilter > 0)) {
    $view = 'all';
}

if ($view === 'home') {
    $stats = getLibraryStats();
    $homeLimit = settingInt('home_section_limit', 8, 3, 20);
    $showStats = settingBool('home_show_stats', true);
    $showRecentAdded = settingBool('home_show_recent_added', true);
    $showRecentPlayed = settingBool('home_show_recent_played', true);
    $showPopular = settingBool('home_show_popular', true);
    $showLiked = settingBool('home_show_liked', true);
    $showRecommendations = settingBool('home_show_recommendations', true);
    $showAutoPlaylists = settingBool('home_show_auto_playlists', true);
    $hiddenGemHome = $showRecommendations ? getAutoPlaylistSongs('hidden_gems', 6) : [];
    $todayRecommendedSongs = $showRecommendations ? getTodayRecommendationSongs16(6) : [];

    $recentAdded = $showRecentAdded ? fetchSongs('s.is_missing = 0', [], 's.id DESC', $homeLimit) : [];
    $popularSongs = $showPopular ? fetchSongs('s.is_missing = 0', [], 's.play_count DESC, s.title ASC', $homeLimit) : [];
    $likedSongs = $showLiked ? fetchSongs('s.is_missing = 0 AND l.id IS NOT NULL', [], 'l.created_at DESC', $homeLimit) : [];
    $recommendedSongs = $showRecommendations ? getPersonalizedRecommendedSongs48(settingInt('recommendation_limit', $homeLimit, 3, 50)) : [];
    $personalHome = getHomePersonalizedData($homeLimit);
    $recentPlaylists = $pdo->query("
        SELECT p.id, p.name, p.description, p.display_scope, p.updated_at, COUNT(ps.id) AS song_count
        FROM playlists p
        LEFT JOIN playlist_songs ps ON ps.playlist_id = p.id
        WHERE COALESCE(p.display_scope, 'private') != 'hidden'
        GROUP BY p.id, p.name, p.description, p.display_scope, p.updated_at
        ORDER BY (p.display_scope = 'home') DESC, p.updated_at DESC, p.id DESC
        LIMIT 6
    ")->fetchAll();
    $recentPlayed = [];
    if ($showRecentPlayed) {
        $recentPlayedStmt = $pdo->query("
            SELECT s.id, s.title, s.artist, s.album, s.genre, s.duration, s.extension, s.play_count,
                   s.created_at, s.updated_at, IF(l.id IS NOT NULL, 1, 0) AS is_liked,
                   recent.last_played_at
            FROM (
                SELECT song_id, MAX(played_at) AS last_played_at
                FROM play_history
                WHERE played_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)
                GROUP BY song_id
            ) recent
            INNER JOIN songs s ON s.id = recent.song_id
            LEFT JOIN liked_songs l ON l.song_id = s.id
            WHERE s.is_missing = 0
            ORDER BY recent.last_played_at DESC
            LIMIT " . $homeLimit
        );
        $recentPlayed = $recentPlayedStmt->fetchAll();
    }

    renderHeader('홈', 'home');
    ?>
    <div class="home-dashboard home-commercial" data-home-customize-root>
        <section class="home-hero-panel" aria-label="홈 요약">
            <div class="page-title-section">
                <span class="section-kicker">내 음악</span>
                <h1 class="page-main-title">오늘 들을 음악을 찾아보세요</h1>
                <p class="page-subtitle">최근에 듣던 곡, 추천 음악, 플레이리스트를 한 화면에서 바로 시작합니다.</p>
            </div>

            <?php if ($showStats): ?>
                <div class="home-library-summary" aria-label="음악 보관함 요약">
                    <span><i class="fa-solid fa-music" aria-hidden="true"></i><strong><?php echo number_format($stats['songs']); ?></strong>곡</span>
                    <span><i class="fa-solid fa-compact-disc" aria-hidden="true"></i><strong><?php echo number_format($stats['albums']); ?></strong>앨범</span>
                    <span><i class="fa-solid fa-list" aria-hidden="true"></i><strong><?php echo number_format($stats['playlists']); ?></strong>목록</span>
                    <span><i class="fa-solid fa-play" aria-hidden="true"></i><strong><?php echo number_format($stats['plays']); ?></strong>재생</span>
                </div>
            <?php endif; ?>

            <nav class="home-browse-strip" aria-label="음악 탐색 바로가기">
                <a href="artists.php"><i class="fas fa-user" aria-hidden="true"></i><span>아티스트</span></a>
                <a href="albums.php"><i class="fas fa-compact-disc" aria-hidden="true"></i><span>앨범</span></a>
                <a href="genres.php"><i class="fas fa-tags" aria-hidden="true"></i><span>장르</span></a>
                <button type="button" class="home-edit-trigger" data-home-edit-open aria-label="홈 편집" title="홈 편집"><i class="fa-solid fa-sliders" aria-hidden="true"></i><span>홈 편집</span></button>
            </nav>
        </section>

        <section class="home-section resume-listening-card" data-home-resume-card hidden aria-label="이어서 듣기">
            <div class="resume-listening-media">
                <img src="assets/img/default-cover.svg" alt="" data-home-resume-cover loading="lazy">
            </div>
            <div class="resume-listening-copy">
                <span class="section-kicker">이어서 듣기</span>
                <h2 class="section-title" data-home-resume-title>마지막으로 듣던 곡</h2>
                <p class="section-description" data-home-resume-meta>재생 위치를 복원할 수 있습니다.</p>
                <div class="resume-listening-progress" aria-hidden="true">
                    <span data-home-resume-progress></span>
                </div>
                <small data-home-resume-time>00:00</small>
            </div>
            <div class="resume-listening-actions">
                <button type="button" class="btn btn-primary btn-sm" data-home-resume-play>
                    <i class="fa-solid fa-play"></i> 이어 듣기
                </button>
                <a class="btn btn-secondary btn-sm" href="recent.php">
                    <i class="fa-regular fa-clock"></i> 최근 재생
                </a>
            </div>
        </section>

        <section class="home-section home-customizer-panel" data-home-customizer hidden aria-label="홈 화면 섹션 편집">
            <div class="section-heading-row">
                <div>
                    <h2 class="section-title">내 홈 구성</h2>
                    <p class="section-description">홈에 표시할 섹션과 순서를 현재 기기에 저장합니다.</p>
                </div>
                <div class="home-customizer-actions">
                    <button type="button" class="btn btn-secondary btn-sm" data-home-reset>기본 구성</button>
                    <button type="button" class="btn btn-secondary btn-sm" data-home-edit-close>닫기</button>
                </div>
            </div>
            <div class="home-customizer-list" data-home-editor-list></div>
            <p class="settings-muted">잘못된 설정값은 자동으로 무시됩니다. 음악 파일 경로는 저장하지 않습니다.</p>
        </section>

        <section class="home-section home-action-strip" aria-labelledby="home-action-strip-title">
            <div class="section-heading-row">
                <div>
                    <h2 class="section-title" id="home-action-strip-title">바로가기</h2>
                    <p class="section-description">자주 쓰는 감상 흐름만 빠르게 열 수 있습니다.</p>
                </div>
            </div>
            <div class="dashboard-quick-actions">
                <a class="quick-action-card primary" href="index.php?view=all"><i class="fa-solid fa-music"></i><strong>전체 음악</strong><span>보관함 열기</span></a>
                <a class="quick-action-card" href="recent.php"><i class="fa-regular fa-clock"></i><strong>최근 재생</strong><span>이어 듣기</span></a>
                <a class="quick-action-card" href="recommend.php"><i class="fa-solid fa-star"></i><strong>추천</strong><span>오늘 들을 곡</span></a>
                <a class="quick-action-card" href="playlists.php"><i class="fa-solid fa-list-ul"></i><strong>플레이리스트</strong><span>목록 관리</span></a>
                <a class="quick-action-card" href="stats.php"><i class="fa-solid fa-chart-line"></i><strong>리포트</strong><span>청취 흐름</span></a>
                <?php if (isLoggedIn()): ?>
                    <a class="quick-action-card admin" href="admin/index.php"><i class="fa-solid fa-screwdriver-wrench"></i><strong>관리 센터</strong><span>운영 관리</span></a>
                <?php endif; ?>
            </div>
        </section>

        <?php if ($showRecommendations): ?>
            <section class="home-section auto-mix-panel" aria-labelledby="auto-mix-home-title" data-home-section="auto_mix" data-home-label="자동 믹스">
                <div class="auto-mix-copy">
                    <span class="section-kicker">추천 대기열</span>
                    <h2 class="section-title" id="auto-mix-home-title">자동 믹스 만들기</h2>
                    <p>최근 재생, 좋아요, 별점, 장르를 조합해 지금 이어 듣기 좋은 곡을 자동으로 묶습니다.</p>
                </div>
                <div class="auto-mix-actions">
                    <button type="button" class="btn btn-primary btn-auto-mix" data-auto-mix-action="play" data-limit="24">
                        <i class="fa-solid fa-play"></i> 바로 재생
                    </button>
                    <button type="button" class="btn btn-secondary btn-auto-mix" data-auto-mix-action="append" data-limit="24">
                        <i class="fa-solid fa-list"></i> 대기열에 추가
                    </button>
                    <a class="btn btn-secondary" href="auto_playlists.php">
                        <i class="fa-solid fa-wand-magic-sparkles"></i> 자동 목록 보기
                    </a>
                </div>
            </section>
            <div class="home-section-shell" data-home-section="today_recommend" data-home-label="오늘의 추천">
                <?php renderTodayRecommendationSection16($todayRecommendedSongs); ?>
            </div>
        <?php endif; ?>

        <div class="home-section-grid" data-home-section-list>
            <section class="home-section" data-home-section="listening_summary" data-home-label="청취 요약">
                <div class="section-heading-row">
                    <h2 class="section-title">오늘의 청취 요약</h2>
                    <a class="section-more-link" href="stats.php">리포트</a>
                </div>
                <div class="daily-summary-grid">
                    <div><span>오늘</span><strong><?php echo number_format($personalHome['summary']['today']); ?></strong></div>
                    <div><span>이번 주</span><strong><?php echo number_format($personalHome['summary']['week']); ?></strong></div>
                    <div><span>이번 달</span><strong><?php echo number_format($personalHome['summary']['month']); ?></strong></div>
                </div>
            </section>
            <?php if ($showRecentPlayed) renderMiniSongSection('최근 재생한 음악', $recentPlayed, 'recent.php', 'recent_played'); ?>
            <?php renderMiniSongSection('최근 자주 듣는 곡', $personalHome['recent_frequent'], 'stats.php', 'recent_frequent'); ?>
            <?php if ($showRecommendations) renderMiniSongSection('나를 위한 추천', $recommendedSongs, 'recommend.php', 'recommendations'); ?>
            <?php if ($showRecommendations) renderMiniSongSection('숨은 명곡 다시 듣기', $hiddenGemHome, 'auto_playlist.php?type=hidden_gems', 'hidden_gems'); ?>
            <?php renderMiniSongSection('오래 안 들은 좋아요 곡', $personalHome['old_liked'], 'liked.php', 'old_liked'); ?>
            <?php if (!empty($recentPlaylists)): ?>
                <section class="home-section" data-home-section="playlists" data-home-label="추천 플레이리스트">
                    <div class="section-heading-row">
                        <h2 class="section-title">내 플레이리스트</h2>
                        <a class="section-more-link" href="playlists.php">더보기</a>
                    </div>
                    <div class="explore-card-grid">
                        <?php foreach ($recentPlaylists as $playlist): ?>
                            <a class="explore-card" href="playlist_view.php?id=<?php echo h($playlist['id']); ?>">
                                <strong><?php echo h($playlist['name']); ?></strong>
                                <span><?php echo number_format((int)$playlist['song_count']); ?>곡 · <?php echo h($playlist['description'] ?: '설명이 없습니다.'); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
            <?php if (!empty($popularTags)): ?>
                <section class="home-section" data-home-section="genre_tags" data-home-label="장르 추천">
                    <div class="section-heading-row">
                        <h2 class="section-title">태그로 찾기</h2>
                        <a class="section-more-link" href="tags.php">더보기</a>
                    </div>
                    <div class="tag-cloud">
                        <?php foreach (array_slice($popularTags, 0, 10) as $tag): ?>
                            <a class="tag-badge" href="tag.php?id=<?php echo h($tag['id']); ?>"><?php echo h($tag['name']); ?> <small><?php echo number_format((int)$tag['song_count']); ?></small></a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
            <?php if ($showAutoPlaylists): ?>
                <section class="home-section" data-home-section="auto_playlists" data-home-label="자동 플레이리스트">
                    <div class="section-heading-row">
                        <h2 class="section-title">자동 플레이리스트</h2>
                        <a class="section-more-link" href="auto_playlists.php">더보기</a>
                    </div>
                    <div class="explore-card-grid">
                        <?php foreach (array_slice(getAutoPlaylistDefinitions(), 0, 4) as $type => $definition): ?>
                            <a class="explore-card" href="auto_playlist.php?type=<?php echo h($type); ?>">
                                <strong><?php echo h($definition['title']); ?></strong>
                                <span><?php echo h($definition['description']); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
            <?php if ($showRecentAdded) renderMiniSongSection('최근 추가된 음악', $recentAdded, 'new.php', 'recent_added'); ?>
            <?php if ($showPopular) renderMiniSongSection('많이 들은 곡', $popularSongs, 'popular.php', 'popular'); ?>
            <?php if ($showLiked) renderMiniSongSection('좋아요한 곡', $likedSongs, 'liked.php', 'liked'); ?>
            <section class="home-section home-custom-empty" data-home-empty hidden>
                <h2 class="section-title">표시할 홈 섹션이 없습니다.</h2>
                <p class="empty-text">기본 홈 구성으로 복구하거나 홈 편집에서 필요한 섹션을 다시 켜세요.</p>
                <button type="button" class="btn btn-primary btn-sm" data-home-reset>기본 홈 구성으로 복구</button>
            </section>
            <?php if (!$showRecentAdded && !$showRecentPlayed && !$showPopular && !$showLiked): ?>
                <section class="home-section">
                    <h2 class="section-title">홈 섹션이 꺼져 있습니다.</h2>
                    <p class="empty-text">설정 페이지에서 홈 화면 섹션을 다시 켤 수 있습니다.</p>
                </section>
            <?php endif; ?>
        </div>
    </div>
    <?php
    renderFooter();
    exit;
}

$genres = $pdo->query("
    SELECT DISTINCT genre FROM songs
    WHERE genre IS NOT NULL AND genre != '' AND is_missing = 0
    ORDER BY genre ASC
")->fetchAll(PDO::FETCH_COLUMN);
$yearExpr = "TRIM(COALESCE(CAST(s.year AS CHAR), ''))";
$yearRows = $pdo->query("
    SELECT TRIM(COALESCE(CAST(year AS CHAR), '')) AS year_value, COUNT(*) AS song_count
    FROM songs
    WHERE is_missing = 0
      AND TRIM(COALESCE(CAST(year AS CHAR), '')) REGEXP '^[0-9]{4}$'
    GROUP BY year_value
    ORDER BY CAST(year_value AS UNSIGNED) DESC
")->fetchAll();
$decadeRows = $pdo->query("
    SELECT FLOOR(CAST(TRIM(COALESCE(CAST(year AS CHAR), '')) AS UNSIGNED) / 10) * 10 AS decade_start,
           COUNT(*) AS song_count
    FROM songs
    WHERE is_missing = 0
      AND TRIM(COALESCE(CAST(year AS CHAR), '')) REGEXP '^[0-9]{4}$'
    GROUP BY decade_start
    ORDER BY decade_start DESC
")->fetchAll();

$where = ["s.is_missing = 0"];
$params = [];
if ($search !== '') {
    $where[] = "(s.title LIKE :search1 OR s.artist LIKE :search2 OR s.album LIKE :search3 OR s.genre LIKE :search4)";
    $params[':search1'] = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
    $params[':search3'] = '%' . $search . '%';
    $params[':search4'] = '%' . $search . '%';
}
if ($genreFilter !== '') {
    $where[] = "s.genre = :genre";
    $params[':genre'] = $genreFilter;
}
if ($yearFilter !== '') {
    if ($yearFilter === 'unknown') {
        $where[] = "$yearExpr = ''";
    } elseif (preg_match('/^decade-(\d{4})$/', $yearFilter, $yearMatch)) {
        $yearStart = (int)$yearMatch[1];
        $where[] = "$yearExpr REGEXP '^[0-9]{4}$' AND CAST($yearExpr AS UNSIGNED) BETWEEN :year_start AND :year_end";
        $params[':year_start'] = $yearStart;
        $params[':year_end'] = $yearStart + 9;
    } elseif (preg_match('/^\d{4}$/', $yearFilter)) {
        $where[] = "$yearExpr = :year_filter";
        $params[':year_filter'] = $yearFilter;
    } else {
        $yearFilter = '';
    }
}
if ($extFilter !== '') {
    $where[] = "s.extension = :ext";
    $params[':ext'] = $extFilter;
}
if ($tagFilter > 0) {
    $where[] = "EXISTS (SELECT 1 FROM song_tags st WHERE st.song_id = s.id AND st.tag_id = :tag_id)";
    $params[':tag_id'] = $tagFilter;
}
if ($onlyLiked === 1 || $view === 'liked') {
    $where[] = "l.id IS NOT NULL";
}

$sortOrderMap = [
    'recent' => "s.id DESC",
    'title' => "s.title ASC, s.artist ASC, s.id ASC",
    'artist' => "s.artist ASC, s.title ASC, s.id ASC",
    'album' => "s.album ASC, s.track_no IS NULL ASC, s.track_no ASC, s.title ASC",
    'recent_played' => "recent.last_played_at IS NULL ASC, recent.last_played_at DESC, s.id DESC",
    'popular' => "s.play_count DESC, s.title ASC, s.id ASC",
    'liked' => "l.id IS NULL ASC, l.created_at DESC, s.title ASC",
    'year_desc' => "CASE WHEN $yearExpr REGEXP '^[0-9]{4}$' THEN 0 ELSE 1 END, CAST($yearExpr AS UNSIGNED) DESC, s.title ASC",
    'year_asc' => "CASE WHEN $yearExpr REGEXP '^[0-9]{4}$' THEN 0 ELSE 1 END, CAST($yearExpr AS UNSIGNED) ASC, s.title ASC",
];
$orderBy = $sortOrderMap[$sort] ?? $sortOrderMap['recent'];

$whereSql = implode(" AND ", $where);
$pageSize = getListDefaultLimit();
$totalSongs = countSongs($whereSql, $params);
$pages = max(1, (int)ceil($totalSongs / $pageSize));
$page = min($page, $pages);
$offset = ($page - 1) * $pageSize;
if ($sort === 'recent_played') {
    $recentSql = baseSongSelectSql() . "
        LEFT JOIN (
            SELECT song_id, MAX(played_at) AS last_played_at
            FROM play_history
            WHERE played_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)
            GROUP BY song_id
        ) recent ON recent.song_id = s.id
        WHERE $whereSql
        ORDER BY $orderBy
        LIMIT " . max(1, (int)$pageSize) . ($offset > 0 ? " OFFSET " . max(0, (int)$offset) : "");
    $recentStmt = $pdo->prepare($recentSql);
    $recentStmt->execute($params);
    $songs = $recentStmt->fetchAll();
} else {
    $songs = fetchSongs($whereSql, $params, $orderBy, $pageSize, $offset);
}
$pageTitle = $search !== '' ? '"' . $search . '" 검색 결과' : '전체 음악';

renderHeader($pageTitle, 'all');
?>
<div class="music-list-page library-view-mode-list library-density-normal" data-library-page="all">
    <div class="page-title-section">
        <h1 class="page-main-title"><?php echo h($pageTitle); ?></h1>
        <p class="page-subtitle">전체 <?php echo number_format($totalSongs); ?>곡 중 <?php echo number_format(count($songs)); ?>곡을 표시합니다.</p>
    </div>

    <section class="filter-preset-panel filter-preset-panel-compact" data-filter-preset-panel data-filter-preset-source="library" aria-label="저장된 검색 필터">
        <div class="filter-preset-head">
            <div>
                <h2 class="section-title">저장된 필터</h2>
                <p class="settings-muted">자주 쓰는 검색 조건을 바로 실행합니다.</p>
            </div>
            <a class="btn btn-secondary btn-sm" href="search.php"><i class="fa-solid fa-sliders"></i> 필터 만들기</a>
        </div>
        <div class="filter-preset-list" data-filter-preset-list></div>
        <p class="empty-text filter-preset-empty" data-filter-preset-empty>저장된 필터가 없습니다.</p>
    </section>

    <div class="list-filter-section">
        <div class="filter-left">
            <a href="index.php?view=all" class="filter-tab active">전체</a>
            <a href="new.php" class="filter-tab">최근 추가</a>
            <a href="popular.php" class="filter-tab">많이 들은 곡</a>
        </div>
        <div class="filter-right">
            <form action="index.php" method="GET" class="filter-sort-form" id="filter-form">
                <input type="hidden" name="view" value="all">
                <?php if ($search !== ''): ?><input type="hidden" name="search" value="<?php echo h($search); ?>"><?php endif; ?>
                <select name="genre" class="sort-select">
                    <option value="">모든 장르</option>
                    <?php foreach ($genres as $g): ?>
                        <option value="<?php echo h($g); ?>" <?php echo $genreFilter === $g ? 'selected' : ''; ?>><?php echo h($g); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="year" class="sort-select year-filter-select" aria-label="연도 필터">
                    <option value="">모든 연도</option>
                    <option value="unknown" <?php echo $yearFilter === 'unknown' ? 'selected' : ''; ?>>연도 없음</option>
                    <?php if (!empty($decadeRows)): ?>
                        <optgroup label="연대별">
                            <?php foreach ($decadeRows as $row): ?>
                                <?php $decade = (int)$row['decade_start']; $value = 'decade-' . $decade; ?>
                                <option value="<?php echo h($value); ?>" <?php echo $yearFilter === $value ? 'selected' : ''; ?>>
                                    <?php echo h($decade . '년대'); ?> · <?php echo number_format((int)$row['song_count']); ?>곡
                                </option>
                            <?php endforeach; ?>
                        </optgroup>
                    <?php endif; ?>
                    <?php if (!empty($yearRows)): ?>
                        <optgroup label="정확한 연도">
                            <?php foreach ($yearRows as $row): ?>
                                <?php $yearValue = (string)$row['year_value']; ?>
                                <option value="<?php echo h($yearValue); ?>" <?php echo $yearFilter === $yearValue ? 'selected' : ''; ?>>
                                    <?php echo h($yearValue . '년'); ?> · <?php echo number_format((int)$row['song_count']); ?>곡
                                </option>
                            <?php endforeach; ?>
                        </optgroup>
                    <?php endif; ?>
                </select>
                <select name="tag" class="sort-select">
                    <option value="0">모든 태그</option>
                    <?php foreach ($popularTags as $tag): ?>
                        <option value="<?php echo h($tag['id']); ?>" <?php echo $tagFilter === (int)$tag['id'] ? 'selected' : ''; ?>><?php echo h($tag['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="ext" class="sort-select">
                    <option value="">모든 형식</option>
                    <?php foreach (getAllowedExtensionsSetting() as $e): ?>
                        <option value="<?php echo h($e); ?>" <?php echo $extFilter === $e ? 'selected' : ''; ?>><?php echo h(strtoupper($e)); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="only_liked" class="sort-select">
                    <option value="0" <?php echo $onlyLiked === 0 ? 'selected' : ''; ?>>모든 곡</option>
                    <option value="1" <?php echo $onlyLiked === 1 ? 'selected' : ''; ?>>좋아요한 곡</option>
                </select>
                <select name="sort" class="sort-select">
                    <?php foreach ($librarySortOptions as $sortKey => $sortLabel): ?>
                        <option value="<?php echo h($sortKey); ?>" <?php echo $sort === $sortKey ? 'selected' : ''; ?>><?php echo h($sortLabel); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
    </div>
    <div class="library-display-controls" aria-label="음악 보관함 보기 설정">
        <div class="library-control-group">
            <span class="library-control-label">보기</span>
            <div class="library-segmented" role="group" aria-label="보기 방식">
                <button type="button" class="library-toggle active" data-library-view="list" aria-pressed="true"><i class="fa-solid fa-list"></i> 리스트</button>
                <button type="button" class="library-toggle" data-library-view="card" aria-pressed="false"><i class="fa-solid fa-border-all"></i> 카드</button>
                <button type="button" class="library-toggle" data-library-view="compact" aria-pressed="false"><i class="fa-solid fa-bars-staggered"></i> 간단</button>
            </div>
        </div>
        <div class="library-control-group">
            <span class="library-control-label">밀도</span>
            <div class="library-segmented" role="group" aria-label="목록 밀도">
                <button type="button" class="library-toggle active" data-library-density="normal" aria-pressed="true">기본</button>
                <button type="button" class="library-toggle" data-library-density="dense" aria-pressed="false">촘촘하게</button>
                <button type="button" class="library-toggle" data-library-density="large" aria-pressed="false">크게 보기</button>
            </div>
        </div>
    </div>
    <?php renderSongList($songs); ?>
    <?php renderSimplePager($page, $pages, '음악 목록 페이지'); ?>
</div>
<?php renderFooter(); ?>
