<?php
/**
 * 음악 상세 정보 보기 페이지 (song.php)
 */

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

$pdo = getDBConnection();
$songId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($songId <= 0) {
    renderHeader('오류');
    ?>
    <div class="alert-box alert-danger">
        <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
        <div class="alert-content">
            <h3>유효하지 않은 요청</h3>
            <p>잘못된 곡 ID 파라미터가 수신되었습니다.</p>
        </div>
    </div>
    <a href="index.php" class="btn btn-secondary">홈으로 돌아가기</a>
    <?php
    renderFooter();
    exit;
}

// 1. 곡 상세 정보 조회 (좋아요 여부 조인 포함)
$sql = "
    SELECT s.*, IF(l.id IS NOT NULL, 1, 0) AS is_liked
    FROM songs s
    LEFT JOIN liked_songs l ON s.id = l.song_id
    WHERE s.id = :id AND s.is_missing = 0
";
$stmt = $pdo->prepare($sql);
$stmt->execute([':id' => $songId]);
$song = $stmt->fetch();

if (!$song) {
    renderHeader('곡 정보 없음');
    ?>
    <div class="alert-box alert-danger">
        <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
        <div class="alert-content">
            <h3>곡 정보를 찾을 수 없습니다.</h3>
            <p>존재하지 않는 곡이거나 스캔 디렉토리에서 소실되어 제외 상태입니다.</p>
        </div>
    </div>
    <a href="index.php" class="btn btn-secondary">홈으로 돌아가기</a>
    <?php
    renderFooter();
    exit;
}

// 2. 최근 재생 50곡 리스트에 포함되어 있는지 판단
$recentCheckStmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM (
        SELECT song_id 
        FROM play_history 
        GROUP BY song_id 
        ORDER BY MAX(played_at) DESC 
        LIMIT 50
    ) tmp 
    WHERE tmp.song_id = :song_id
");
$recentCheckStmt->execute([':song_id' => $songId]);
$isRecentlyPlayed = $recentCheckStmt->fetchColumn() > 0;

// 3. 가사 데이터 조회
$lyricsText = '';
$lyricsQuery = $pdo->prepare("SELECT lyrics_text FROM lyrics WHERE song_id = :song_id");
$lyricsQuery->execute([':song_id' => $songId]);
$lyricsRow = $lyricsQuery->fetch();
if ($lyricsRow) {
    $lyricsText = $lyricsRow['lyrics_text'];
}

$songTags = getSongTags($songId);
$popularTags = getPopularTags(12);
$songNote = getSongNote($songId);
$songRating = getSongRating($songId);
$canDownloadSong = isLoggedIn() && hasPermission('music_manage');
$artistLabel = trim((string)($song['artist'] ?? ''));
$displayArtistLabel = artistName($song['artist'] ?? '');
$displayAlbumLabel = albumName($song['album'] ?? '');
$displayGenreLabel = genreName($song['genre'] ?? '');
$albumLabel = trim((string)($song['album'] ?? ''));
$genreLabel = trim((string)($song['genre'] ?? ''));
$albumDescription = $albumLabel !== '' ? fetchAlbumDescription($albumLabel, $artistLabel) : null;
$albumDescriptionText = trim(ensureUtf8String($albumDescription['description'] ?? ''));
$sameArtistSongs = $artistLabel !== ''
    ? fetchSongs(
        's.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND s.id <> :song_id AND s.artist = :artist',
        [':song_id' => $songId, ':artist' => $artistLabel],
        's.play_count DESC, s.title ASC',
        6
    )
    : [];
$sameAlbumWhere = 's.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND s.id <> :song_id AND s.album = :album';
$sameAlbumParams = [':song_id' => $songId, ':album' => $albumLabel];
if ($albumLabel !== '' && $artistLabel !== '') {
    $sameAlbumWhere .= ' AND s.artist = :album_artist';
    $sameAlbumParams[':album_artist'] = $artistLabel;
}
$sameAlbumSongs = $albumLabel !== ''
    ? fetchSongs($sameAlbumWhere, $sameAlbumParams, 's.track_no IS NULL ASC, s.track_no ASC, s.title ASC', 6)
    : [];
$sameGenreSongs = $genreLabel !== ''
    ? fetchSongs(
        's.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND s.id <> :song_id AND s.genre = :genre',
        [':song_id' => $songId, ':genre' => $genreLabel],
        's.play_count DESC, s.title ASC',
        6
    )
    : [];
$metadataHints = [];
if ($artistLabel === '') $metadataHints[] = '아티스트 정보가 비어 있습니다.';
if ($albumLabel === '') $metadataHints[] = '앨범 정보가 비어 있습니다.';
if ($genreLabel === '') $metadataHints[] = '장르 정보가 비어 있습니다.';
if (trim((string)($song['year'] ?? '')) === '') $metadataHints[] = '발매연도 정보가 비어 있습니다.';
if (empty($song['duration'])) $metadataHints[] = '재생시간 정보가 부족합니다.';
if (empty($song['has_cover'])) $metadataHints[] = '앨범아트가 없습니다.';

// 바이트 크기 포맷팅 로컬 함수
if (!function_exists('formatBytes')) {
    function formatBytes($bytes, $precision = 2) {
        $units = array('B', 'KB', 'MB', 'GB', 'TB');
        $bytes = max((int)$bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

if (!function_exists('renderRelatedSongSection20')) {
    function renderRelatedSongSection20($title, $songs, $emptyMessage) {
        ?>
        <section class="home-section related-song-section">
            <div class="section-heading-row">
                <h2 class="section-title"><?php echo h($title); ?></h2>
            </div>
            <?php if (empty($songs)): ?>
                <div class="detail-empty-state">
                    <i class="fa-regular fa-compass" aria-hidden="true"></i>
                    <p><?php echo h($emptyMessage); ?></p>
                </div>
            <?php else: ?>
                <div class="compact-song-grid related-song-grid">
                    <?php foreach ($songs as $related): ?>
                        <?php $isLiked = !empty($related['is_liked']); ?>
                        <div class="compact-song-card song-item"
                             data-id="<?php echo h($related['id']); ?>"
                             data-title="<?php echo h($related['title']); ?>"
                             data-artist="<?php echo h(artistName($related['artist'] ?? '')); ?>"
                             data-album="<?php echo h(albumName($related['album'] ?? '')); ?>"
                             data-duration="<?php echo h($related['duration'] ?? 0); ?>"
                             data-cover-url="<?php echo h(coverUrl($related)); ?>"
                             data-liked="<?php echo $isLiked ? '1' : '0'; ?>">
                            <button type="button" class="play-row-btn compact-play" title="재생" aria-label="재생"><i class="fas fa-play"></i></button>
                            <img src="<?php echo h(coverUrl($related)); ?>" alt="" class="compact-cover" loading="lazy" width="52" height="52" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                            <div class="compact-song-meta">
                                <a href="song.php?id=<?php echo h($related['id']); ?>" class="compact-title" title="<?php echo h($related['title']); ?>"><?php echo h($related['title']); ?></a>
                                <span title="<?php echo h(artistName($related['artist'] ?? '')); ?>"><?php echo h(artistName($related['artist'] ?? '')); ?></span>
                            </div>
                            <div class="compact-song-actions" aria-label="관련 곡 작업">
                                <button type="button" class="like-btn <?php echo $isLiked ? 'liked' : ''; ?>" title="<?php echo $isLiked ? '좋아요 취소' : '좋아요'; ?>" aria-label="<?php echo $isLiked ? '좋아요 취소' : '좋아요'; ?>">
                                    <i class="<?php echo $isLiked ? 'fas fa-heart' : 'far fa-heart'; ?>"></i>
                                </button>
                                <button type="button" class="add-next-btn" title="다음에 재생" aria-label="다음에 재생"><i class="fas fa-forward-step"></i></button>
                                <button type="button" class="add-playlist-btn" title="플레이리스트에 추가" aria-label="플레이리스트에 추가"><i class="fas fa-plus"></i></button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
        <?php
    }
}

renderHeader($song['title'] . ' 정보', 'all');
?>

<div class="song-detail-page">
    <div class="page-title-section song-detail-title-section">
        <span class="section-kicker">곡 상세</span>
        <h1 class="page-main-title"><?php echo h($song['title']); ?></h1>
        <p class="page-subtitle"><a class="song-meta-link artist-meta-link" href="artist.php?name=<?php echo rawurlencode($displayArtistLabel); ?>"><?php echo h($displayArtistLabel); ?></a> · <a class="song-meta-link album-meta-link" href="album.php?album=<?php echo rawurlencode($displayAlbumLabel); ?>&artist=<?php echo rawurlencode($displayArtistLabel); ?>"><?php echo h($displayAlbumLabel); ?></a></p>
    </div>

    <!-- 상세 보기 반응형 레이아웃 카드 -->
    <div class="song-detail-container" style="display: flex; gap: 32px; flex-wrap: wrap; margin-bottom: 30px;">
        <!-- 좌측: 대형 앨범아트 카드 -->
        <div class="song-detail-art-card" style="flex: 1; min-width: 280px; max-width: 360px; background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 20px;">
            <div class="album-art-large" style="width: 220px; height: 220px; border-radius: 12px; overflow: hidden; border: 2px solid var(--border-color); box-shadow: 0 8px 24px rgba(0,0,0,0.5);">
                <img src="<?php echo h(coverUrl($song)); ?>" alt="Cover" width="320" height="320" style="width:100%; height:100%; object-fit:cover;" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
            </div>
            
            <div class="song-art-meta">
                <h3 style="font-size: 18px; font-weight: 700; margin-bottom: 6px; white-space: normal; word-break: break-all;"><?php echo h($song['title']); ?></h3>
                <p style="color: var(--text-secondary); font-size: 14px;"><a class="song-meta-link artist-meta-link" href="artist.php?name=<?php echo rawurlencode($displayArtistLabel); ?>"><?php echo h($displayArtistLabel); ?></a></p>
            </div>
            
            <!-- 하단 빠른 조작 인터랙션 버튼 행 (song-item 데이터 속성 바인딩을 통해 플레이어 JS 및 비동기 좋아요 기능 연동 가능) -->
            <div class="song-item" 
                 data-id="<?php echo $song['id']; ?>" 
                 data-title="<?php echo h($song['title']); ?>" 
                 data-artist="<?php echo h($song['artist'] ?? '-'); ?>" 
                 data-album="<?php echo h($song['album'] ?? ''); ?>"
                 data-duration="<?php echo $song['duration'] ?? 0; ?>"
                 data-cover-url="<?php echo h(coverUrl($song)); ?>"
                 data-liked="<?php echo $song['is_liked']; ?>"
                 style="display: flex; gap: 10px; width: 100%; justify-content: center; align-items: center; margin-top: 10px;">
                
                <button type="button" class="btn btn-primary play-row-btn" style="flex: 2; border-radius: 8px; height: 40px; font-size: 14px;">
                    <i class="fas fa-play"></i> 바로 재생
                </button>
                
                <button type="button" class="btn btn-secondary like-btn <?php echo $song['is_liked'] ? 'liked' : ''; ?>" 
                        style="width: 40px; height: 40px; border-radius: 8px; font-size: 18px; display: inline-flex; justify-content: center; align-items: center;"
                        title="<?php echo $song['is_liked'] ? '좋아요 취소' : '좋아요'; ?>">
                    <i class="<?php echo $song['is_liked'] ? 'fas fa-heart' : 'far fa-heart'; ?>"></i>
                </button>
                
                <button type="button" class="btn btn-secondary add-playlist-btn" 
                        style="width: 40px; height: 40px; border-radius: 8px; font-size: 18px; display: inline-flex; justify-content: center; align-items: center;"
                        title="플레이리스트에 추가">
                    <i class="fas fa-plus"></i>
                </button>
                <button type="button" class="btn btn-secondary add-next-btn"
                        style="width: 40px; height: 40px; border-radius: 8px; font-size: 16px; display: inline-flex; justify-content: center; align-items: center;"
                        title="다음에 재생"
                        aria-label="다음에 재생">
                    <i class="fas fa-forward-step"></i>
                </button>
                <?php if ($canDownloadSong): ?>
                    <a href="download.php?id=<?php echo h($song['id']); ?>"
                       class="btn btn-secondary download-song-btn"
                       style="width: 40px; height: 40px; border-radius: 8px; font-size: 16px; display: inline-flex; justify-content: center; align-items: center;"
                       title="음원 다운로드"
                       aria-label="음원 다운로드"
                       data-no-pjax
                       download>
                        <i class="fas fa-download"></i>
                    </a>
                <?php endif; ?>
                <button type="button"
                        class="btn btn-secondary metadata-request-btn"
                        style="min-width: 40px; height: 40px; border-radius: 8px; font-size: 16px; display: inline-flex; justify-content: center; align-items: center;"
                        data-no-pjax
                        data-song-id="<?php echo h($song['id']); ?>"
                        data-song-title="<?php echo h($song['title']); ?>"
                        data-song-artist="<?php echo h($song['artist'] ?? ''); ?>"
                        data-song-album="<?php echo h($song['album'] ?? ''); ?>"
                        title="정보 수정 요청"
                        aria-label="정보 수정 요청">
                    <i class="fa-solid fa-pen-to-square"></i>
                </button>
            </div>
        </div>

        <!-- 우측: 메타데이터 상세 카드 -->
        <div class="song-detail-info-card song-spec-card" style="flex: 2; min-width: 320px; background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
            <div class="song-spec-heading">
                <i class="fas fa-info-circle" aria-hidden="true"></i>
                <h2>상세 스펙 시트</h2>
            </div>
            <dl class="song-spec-list">
                <div class="song-spec-row">
                    <dt>곡 제목</dt>
                    <dd class="song-spec-primary"><?php echo h($song['title']); ?></dd>
                </div>
                <div class="song-spec-row">
                    <dt>아티스트</dt>
                    <dd><a class="song-meta-link artist-meta-link" href="artist.php?name=<?php echo rawurlencode($displayArtistLabel); ?>"><?php echo h($displayArtistLabel); ?></a></dd>
                </div>
                <div class="song-spec-row">
                    <dt>수록 앨범</dt>
                    <dd><a class="song-meta-link album-meta-link" href="album.php?album=<?php echo rawurlencode($displayAlbumLabel); ?>&artist=<?php echo rawurlencode($displayArtistLabel); ?>"><?php echo h($displayAlbumLabel); ?></a></dd>
                </div>
                <div class="song-spec-row">
                    <dt>음악 장르</dt>
                    <dd><a class="song-meta-link genre-meta-link" href="genre.php?name=<?php echo rawurlencode($displayGenreLabel); ?>"><?php echo h($displayGenreLabel); ?></a></dd>
                </div>
                <div class="song-spec-row">
                    <dt>발매 연도</dt>
                    <dd><?php echo h($song['year'] ?? '정보 없음'); ?></dd>
                </div>
                <div class="song-spec-row">
                    <dt>트랙 번호</dt>
                    <dd><?php echo $song['track_no'] !== null ? h($song['track_no'] . '번 트랙') : '정보 없음'; ?></dd>
                </div>
                <div class="song-spec-row">
                    <dt>재생 시간</dt>
                    <dd><?php echo h(formatDuration($song['duration'])); ?> <span class="song-spec-muted">(<?php echo number_format((int)($song['duration'] ?? 0)); ?>초)</span></dd>
                </div>
                <div class="song-spec-row">
                    <dt>파일 형식</dt>
                    <dd><span class="file-ext-badge song-spec-format"><?php echo h(strtoupper((string)($song['extension'] ?? '-'))); ?></span></dd>
                </div>
                <div class="song-spec-row">
                    <dt>파일 크기</dt>
                    <dd><?php echo h(formatBytes($song['file_size'] ?? 0)); ?> <span class="song-spec-muted">(<?php echo number_format((int)($song['file_size'] ?? 0)); ?> 바이트)</span></dd>
                </div>
                <div class="song-spec-row">
                    <dt>누적 재생수</dt>
                    <dd class="song-spec-accent"><?php echo number_format((int)($song['play_count'] ?? 0)); ?>회</dd>
                </div>
                <div class="song-spec-row">
                    <dt>선호 여부</dt>
                    <dd class="<?php echo $song['is_liked'] ? 'song-spec-liked' : 'song-spec-muted'; ?>">
                        <i class="fas fa-heart" aria-hidden="true"></i> <?php echo $song['is_liked'] ? '좋아요 등록됨' : '좋아요 누르지 않음'; ?>
                    </dd>
                </div>
                <div class="song-spec-row">
                    <dt>최근 감상 여부</dt>
                    <dd class="<?php echo $isRecentlyPlayed ? 'song-spec-accent' : 'song-spec-muted'; ?>">
                        <i class="fas fa-clock" aria-hidden="true"></i> <?php echo $isRecentlyPlayed ? '최근 50곡 내 감상함' : '최근 감상 이력 없음'; ?>
                    </dd>
                </div>
            </dl>
            <div class="song-detail-stat-strip" aria-label="곡 요약">
                <span><i class="fa-solid fa-clock"></i><strong><?php echo h(formatDuration($song['duration'])); ?></strong>재생시간</span>
                <span><i class="fa-solid fa-play"></i><strong><?php echo number_format((int)($song['play_count'] ?? 0)); ?></strong>재생</span>
                <span><i class="fa-solid fa-star"></i><strong><?php echo $songRating > 0 ? h($songRating) : '-'; ?></strong>별점</span>
                <span><i class="fa-solid fa-heart"></i><strong><?php echo !empty($song['is_liked']) ? 'Y' : 'N'; ?></strong>좋아요</span>
            </div>
        </div>
    </div>

    <section class="home-section song-album-summary-card">
        <div class="section-heading-row">
            <h2 class="section-title">앨범 정보</h2>
            <?php if ($albumLabel !== ''): ?><a class="section-more-link" href="album.php?album=<?php echo rawurlencode($albumLabel); ?>&artist=<?php echo rawurlencode($artistLabel); ?>">앨범 보기</a><?php endif; ?>
        </div>
        <div class="song-album-summary-grid">
            <div>
                <span>앨범</span>
                <strong><a class="song-meta-link album-meta-link" href="album.php?album=<?php echo rawurlencode($displayAlbumLabel); ?>&artist=<?php echo rawurlencode($displayArtistLabel); ?>"><?php echo h($displayAlbumLabel); ?></a></strong>
            </div>
            <div>
                <span>앨범 아티스트</span>
                <strong><?php echo h(artistName($song['album_artist'] ?? $song['artist'] ?? '정보 없음')); ?></strong>
            </div>
            <div>
                <span>발매연도</span>
                <strong><?php echo h(trim((string)($song['year'] ?? '')) !== '' ? $song['year'] : '정보 없음'); ?></strong>
            </div>
            <div>
                <span>트랙</span>
                <strong><?php echo $song['track_no'] !== null ? h($song['track_no'] . '번') : '정보 없음'; ?></strong>
            </div>
        </div>
        <div class="song-album-description">
            <?php if ($albumDescriptionText !== ''): ?>
                <?php echo nl2br(h($albumDescriptionText)); ?>
            <?php else: ?>
                <p class="empty-text">등록된 앨범 소개가 없습니다. 앨범 화면에서 소개를 추가할 수 있습니다.</p>
            <?php endif; ?>
        </div>
    </section>

    <!-- 가사 보기 및 편집 카드 (3차/4차 가사 연동) -->
    <section class="home-section metadata-status-summary">
        <div class="section-heading-row">
            <h2 class="section-title">메타데이터 상태</h2>
            <a class="section-more-link" href="song_edit.php?id=<?php echo h($song['id']); ?>">수정</a>
        </div>
        <div class="metadata-status-panel">
            <span>출처: <?php echo h(metaValue($song['metadata_source'] ?? '', 'unknown')); ?></span>
            <span>수동 수정 보호: <?php echo !empty($song['is_manual_edited']) ? '켜짐' : '꺼짐'; ?></span>
            <span>마지막 스캔: <?php echo h($song['last_metadata_scan_at'] ?? '-'); ?></span>
            <span>앨범아트: <?php echo !empty($song['has_cover']) ? '있음' : '없음'; ?><?php echo !empty($song['cover_mime']) ? ' (' . h($song['cover_mime']) . ')' : ''; ?></span>
            <?php if (!empty($song['metadata_error'])): ?><p class="metadata-error"><?php echo h($song['metadata_error']); ?></p><?php endif; ?>
        </div>
        <?php if (!empty($metadataHints)): ?>
            <div class="metadata-hint-panel">
                <i class="fa-solid fa-circle-info" aria-hidden="true"></i>
                <div>
                    <strong>정보 보정이 필요할 수 있습니다.</strong>
                    <p><?php echo h(implode(' ', $metadataHints)); ?></p>
                    <button type="button"
                            class="btn btn-secondary btn-sm metadata-request-btn"
                            data-no-pjax
                            data-song-id="<?php echo h($song['id']); ?>"
                            data-song-title="<?php echo h($song['title']); ?>"
                            data-song-artist="<?php echo h($song['artist'] ?? ''); ?>"
                            data-song-album="<?php echo h($song['album'] ?? ''); ?>">
                        <i class="fa-solid fa-pen-to-square"></i> 정보 수정 요청
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </section>

    <section class="home-section tag-editor-card">
        <div class="section-heading-row">
            <h2 class="section-title">태그</h2>
            <a class="section-more-link" href="tags.php">태그 탐색</a>
        </div>
        <div class="song-tags-box" data-song-id="<?php echo h($song['id']); ?>">
            <?php renderTagBadges($songTags, './', $song['id']); ?>
        </div>
        <form class="song-tag-form" data-song-id="<?php echo h($song['id']); ?>">
            <input type="text" name="tag_name" maxlength="100" placeholder="예: 드라이브, 밤에 듣기, 운동">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fa-solid fa-plus"></i> 태그 추가</button>
        </form>
        <?php if (!empty($popularTags)): ?>
            <div class="tag-suggestion-row">
                <?php foreach ($popularTags as $tag): ?>
                    <button type="button" class="tag-suggestion-btn" data-tag-name="<?php echo h($tag['name']); ?>"><?php echo h($tag['name']); ?></button>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>

    <section class="home-section listening-note-card">
        <div class="section-heading-row">
            <h2 class="section-title">별점과 개인 메모</h2>
            <a class="section-more-link" href="listening_notes.php">감상 노트</a>
        </div>
        <div class="rating-panel">
            <span class="settings-muted">내 별점</span>
            <?php renderRatingStars($songRating, $song['id'], true); ?>
        </div>
        <div class="note-view-text" data-song-id="<?php echo h($song['id']); ?>">
            <?php if ($songNote && trim((string)$songNote['note_text']) !== ''): ?>
                <div class="note-text-block"><?php echo nl2br(h($songNote['note_text'])); ?></div>
            <?php else: ?>
                <p class="empty-text">작성된 메모가 없습니다.</p>
            <?php endif; ?>
        </div>
        <form class="song-note-form" data-song-id="<?php echo h($song['id']); ?>">
            <textarea name="note_text" maxlength="10000" placeholder="이 곡에 대한 개인 메모를 남겨보세요."><?php echo h($songNote['note_text'] ?? ''); ?></textarea>
            <div class="note-action-row">
                <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-save"></i> 메모 저장</button>
                <button type="button" class="btn btn-secondary btn-sm note-delete-btn" data-song-id="<?php echo h($song['id']); ?>"><i class="fas fa-trash-alt"></i> 메모 삭제</button>
            </div>
        </form>
    </section>

    <div class="song-lyrics-card">
        <div class="song-lyrics-header">
            <h3 class="song-lyrics-title">
                <i class="fas fa-music" style="color: var(--accent-color);"></i> 가사
            </h3>
            <a href="lyrics_edit.php?song_id=<?php echo $song['id']; ?>" class="btn btn-secondary btn-sm" style="border-radius: 6px; padding: 6px 12px;">
                <i class="fas fa-edit"></i> 가사 등록/수정
            </a>
        </div>
        
        <div class="lyrics-container" data-lyrics-song-id="<?php echo (int)$song['id']; ?>">
            <?php if (empty($lyricsText)): ?>
                <div class="detail-empty-state">
                    <i class="fa-regular fa-file-lines" aria-hidden="true"></i>
                    <p>등록된 가사가 없습니다. 가사 등록/수정 버튼을 눌러 첫 가사를 등록해 보세요.</p>
                </div>
            <?php else: ?>
                <div class="lyrics-text-block"><?php echo nl2br(h($lyricsText)); ?></div>
            <?php endif; ?>
        </div>
    </div>

    <div class="related-song-sections">
        <?php renderRelatedSongSection20('같은 아티스트의 다른 곡', $sameArtistSongs, '같은 아티스트의 다른 곡이 아직 없습니다.'); ?>
        <?php renderRelatedSongSection20('같은 앨범의 곡', $sameAlbumSongs, '같은 앨범의 다른 곡이 아직 없습니다.'); ?>
        <?php renderRelatedSongSection20('같은 장르의 곡', $sameGenreSongs, '같은 장르로 추천할 곡이 아직 없습니다.'); ?>
    </div>
     
    <div class="song-detail-bottom-actions" style="margin-top: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
        <a href="song_edit.php?id=<?php echo $song['id']; ?>" class="btn btn-primary" style="border-radius: 8px;"><i class="fas fa-edit"></i> 곡 정보 수정</a>
        <a href="index.php" class="btn btn-secondary" style="border-radius: 8px;"><i class="fas fa-arrow-left"></i> 음악 목록으로 가기</a>
    </div>
</div>

<?php
renderFooter();
?>
