<?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';

$album = normalizeMetaParam($_GET['album'] ?? $_GET['id'] ?? '');
$artist = normalizeMetaParam($_GET['artist'] ?? '');
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'track';

$params = [];
$albumWhere = metaWhereSql('s.album', ':album', $album === '알 수 없는 앨범' ? '' : $album, $params);
$where = "s.is_missing = 0 AND $albumWhere";
if ($artist !== '') {
    $where .= " AND " . metaWhereSql('s.artist', ':artist', $artist === '알 수 없는 아티스트' ? '' : $artist, $params);
}

$orderMap = [
    'track' => 's.track_no IS NULL ASC, s.track_no ASC, s.title ASC',
    'title' => 's.title ASC',
    'plays' => 's.play_count DESC, s.title ASC',
];
$songs = fetchSongs($where, $params, $orderMap[$sort] ?? $orderMap['track']);
$first = $songs[0] ?? null;
$albumLabel = albumName($album);
$artistLabel = $first ? artistName($first['artist'] ?? '') : artistName($artist);
$genreLabel = $first ? genreName($first['genre'] ?? '') : '알 수 없는 장르';
$yearLabel = $first ? metaValue($first['year'] ?? '', '-') : '-';

renderHeader($albumLabel, 'albums');
?>
<div class="detail-page">
    <div class="detail-hero">
        <img src="<?php echo $first ? 'cover.php?id=' . h($first['id']) : 'assets/img/default-cover.svg'; ?>" alt="" class="detail-cover" width="180" height="180" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
        <div>
            <span class="detail-kicker">앨범</span>
            <h1 class="page-main-title"><?php echo h($albumLabel); ?></h1>
            <p class="page-subtitle"><?php echo h($artistLabel); ?> · <?php echo h($genreLabel); ?> · <?php echo h($yearLabel); ?></p>
            <?php renderStatGrid([
                ['label' => '곡 수', 'value' => number_format(count($songs))],
                ['label' => '총 재생', 'value' => number_format(array_sum(array_column($songs, 'play_count')))],
            ]); ?>
        </div>
    </div>
    <form class="library-toolbar" method="GET">
        <input type="hidden" name="album" value="<?php echo h($albumLabel); ?>">
        <input type="hidden" name="artist" value="<?php echo h($artistLabel); ?>">
        <select name="sort" onchange="this.form.submit()">
            <option value="track" <?php echo $sort === 'track' ? 'selected' : ''; ?>>트랙번호순</option>
            <option value="title" <?php echo $sort === 'title' ? 'selected' : ''; ?>>제목순</option>
            <option value="plays" <?php echo $sort === 'plays' ? 'selected' : ''; ?>>재생횟수순</option>
        </select>
    </form>
    <?php renderSongList($songs); ?>
</div>
<?php renderFooter(); ?>
