<?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_search.php';
require_once __DIR__ . '/includes/layout.php';

$filters = searchFilterState();
$query = $filters['q'];
$sortOptions = searchSortOptions();
$searchResult = ['songs' => [], 'total' => 0, 'page' => 1, 'page_size' => searchPageSize(), 'pages' => 1];
$categories = ['artists' => [], 'albums' => [], 'genres' => [], 'playlists' => [], 'tags' => []];
$lyricsResult = ['items' => [], 'total' => 0];
$recentFallback = [];
$popularFallback = [];
$availableTags = [];
$errorMessage = '';
$allowedSearchTabs = ['all', 'songs', 'artists', 'albums', 'genres', 'playlists', 'lyrics'];
$activeTab = in_array((string)($_GET['tab'] ?? 'all'), $allowedSearchTabs, true) ? (string)($_GET['tab'] ?? 'all') : 'all';
$hasSearchInput = $query !== '' || $filters['tag_id'] > 0 || $filters['min_rating'] > 0 || $filters['liked'] !== '' || $filters['has_note'] !== '' || $filters['has_lyrics'] !== '' || $filters['artist'] !== '' || $filters['album'] !== '' || $filters['genre'] !== '' || $filters['playlist_id'] > 0 || $filters['popular_only'] || $filters['manual_only'] || $filters['hide_missing_meta'];

try {
    ensureTagTables();
    $availableTags = getPopularTags(60);
    if ($hasSearchInput) {
        $searchResult = searchSongsAdvanced($filters);
        if ($query !== '') {
            $categories = searchCategoryResults($query);
            $lyricsResult = searchLyricsResults($query, 12);
        }
    } else {
        $recentFallback = searchRecentFallbackSongs(12);
        $popularFallback = searchPopularFallbackSongs(12);
    }
} catch (Throwable $e) {
    $errorMessage = '검색 중 오류가 발생했습니다.';
    if (function_exists('writeAppLog')) writeAppLog('error', 'search_error', 'Search page failed', ['error' => $e->getMessage(), 'query' => $query]);
}

function searchSelected($a, $b) {
    return (string)$a === (string)$b ? 'selected' : '';
}

function searchChecked($value) {
    return !empty($value) ? 'checked' : '';
}

function renderSearchPager($result) {
    if (($result['pages'] ?? 1) <= 1) return;
    $page = (int)$result['page'];
    $pages = (int)$result['pages'];
    $start = max(1, $page - 2);
    $end = min($pages, $page + 2);
    ?>
    <nav class="search-pagination" aria-label="검색 페이지">
        <?php if ($page > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(searchUrlWith(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
        <?php for ($i = $start; $i <= $end; $i++): ?>
            <a class="pager-link <?php echo $i === $page ? 'active' : ''; ?>" href="<?php echo h(searchUrlWith(['page' => $i])); ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
        <?php if ($page < $pages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(searchUrlWith(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
    </nav>
    <?php
}

function renderFilterBadges($filters, $tags) {
    $badges = [];
    foreach (['artist' => '아티스트', 'album' => '앨범', 'genre' => '장르'] as $key => $label) {
        if ($filters[$key] !== '') $badges[] = [$label, $filters[$key], searchUrlWith([$key => null, 'page' => 1])];
    }
    if ($filters['tag_id'] > 0) {
        $name = '태그 #' . $filters['tag_id'];
        foreach ($tags as $tag) {
            if ((int)$tag['id'] === (int)$filters['tag_id']) {
                $name = $tag['name'];
                break;
            }
        }
        $badges[] = ['태그', $name, searchUrlWith(['tag_id' => null, 'page' => 1])];
    }
    if ($filters['min_rating'] > 0) $badges[] = ['별점', $filters['min_rating'] . '점 이상', searchUrlWith(['min_rating' => null, 'page' => 1])];
    if ($filters['liked'] !== '') $badges[] = ['좋아요', $filters['liked'] === '1' ? '좋아요만' : '좋아요 제외', searchUrlWith(['liked' => null, 'page' => 1])];
    if ($filters['has_note'] !== '') $badges[] = ['메모', $filters['has_note'] === '1' ? '있음' : '없음', searchUrlWith(['has_note' => null, 'page' => 1])];
    if ($filters['has_lyrics'] !== '') $badges[] = ['가사', $filters['has_lyrics'] === '1' ? '있음' : '없음', searchUrlWith(['has_lyrics' => null, 'page' => 1])];
    if ($filters['popular_only']) $badges[] = ['재생', '재생 기록 있음', searchUrlWith(['popular_only' => null, 'page' => 1])];
    if ($filters['manual_only']) $badges[] = ['수동 수정', '보호됨', searchUrlWith(['manual_only' => null, 'page' => 1])];
    if ($filters['hide_missing_meta']) $badges[] = ['메타데이터', '누락 제외', searchUrlWith(['hide_missing_meta' => null, 'page' => 1])];
    if (empty($badges)) return;
    ?>
    <div class="active-filter-badges">
        <?php foreach ($badges as $badge): ?>
            <a class="filter-badge" href="<?php echo h($badge[2]); ?>"><span><?php echo h($badge[0]); ?></span><?php echo h($badge[1]); ?><i class="fa-solid fa-xmark"></i></a>
        <?php endforeach; ?>
    </div>
    <?php
}

function renderSearchOverviewTabs($activeTab, $counts) {
    $labels = [
        'all' => '전체',
        'songs' => '곡',
        'artists' => '아티스트',
        'albums' => '앨범',
        'genres' => '장르',
        'playlists' => '플레이리스트',
        'lyrics' => '가사',
    ];
    $total = 0;
    foreach (['songs', 'artists', 'albums', 'genres', 'playlists', 'lyrics'] as $key) {
        $total += (int)($counts[$key] ?? 0);
    }
    ?>
    <section class="search-result-overview" aria-label="검색 결과 요약">
        <div class="search-result-summary">
            <strong>검색 결과</strong>
            <span>곡, 아티스트, 앨범, 장르, 플레이리스트, 가사를 유형별로 정리했습니다.</span>
            <em><?php echo number_format($total); ?>개 결과</em>
        </div>
        <nav class="search-result-tabs" aria-label="검색 결과 탭">
            <?php foreach ($labels as $key => $label): ?>
                <?php $count = $key === 'all' ? $total : (int)($counts[$key] ?? 0); ?>
                <a class="search-tab-btn <?php echo $activeTab === $key ? 'active' : ''; ?>" href="<?php echo h(searchUrlWith(['tab' => $key === 'all' ? null : $key, 'page' => 1])); ?>">
                    <span><?php echo h($label); ?></span>
                    <small><?php echo number_format($count); ?></small>
                </a>
            <?php endforeach; ?>
        </nav>
    </section>
    <?php
}

renderHeader('통합 검색', 'search');
?>
<div class="search-page enhanced-search-page" data-search-page>
    <div class="page-title-section">
        <h1 class="page-main-title">통합 검색</h1>
        <p class="page-subtitle">곡, 아티스트, 앨범, 장르, 태그, 가사, 메모, 플레이리스트를 한 번에 찾습니다.</p>
    </div>

    <?php if ($errorMessage !== ''): ?>
        <div class="notice notice-danger"><?php echo h($errorMessage); ?></div>
    <?php endif; ?>

    <form action="search.php" method="GET" class="search-page-form enhanced-search-form" data-search-form>
        <i class="fas fa-search"></i>
        <input type="text" name="q" value="<?php echo h($query); ?>" maxlength="120" autocomplete="off" placeholder="곡, 아티스트, 태그, 가사, 메모 검색">
        <button type="submit" class="btn btn-primary">검색</button>
    </form>

    <div class="search-recent-panel" data-recent-search-panel hidden>
        <div class="section-heading-row">
            <h2 class="section-title">최근 검색어</h2>
            <button type="button" class="btn btn-secondary btn-sm" data-clear-recent-searches>전체 삭제</button>
        </div>
        <div class="recent-search-list" data-recent-search-list></div>
    </div>

    <section class="filter-preset-panel" data-filter-preset-panel data-filter-preset-source="search" aria-label="고급 필터 프리셋">
        <div class="filter-preset-head">
            <div>
                <h2 class="section-title">자주 쓰는 필터</h2>
                <p class="settings-muted">현재 검색어와 고급 필터 조건을 저장해 다시 실행할 수 있습니다.</p>
            </div>
            <div class="filter-preset-save">
                <input type="text" class="form-control" data-filter-preset-name maxlength="40" placeholder="예: 좋아요한 발라드">
                <button type="button" class="btn btn-primary" data-save-filter-preset><i class="fa-solid fa-bookmark"></i> 저장</button>
            </div>
        </div>
        <div class="filter-preset-list" data-filter-preset-list></div>
        <p class="empty-text filter-preset-empty" data-filter-preset-empty>저장된 필터가 없습니다.</p>
    </section>

    <details class="advanced-filter-panel" <?php echo $hasSearchInput ? 'open' : ''; ?>>
        <summary><i class="fa-solid fa-sliders"></i> 고급 필터 / 정렬</summary>
        <form action="search.php" method="GET" class="advanced-filter-form">
            <input type="hidden" name="q" value="<?php echo h($query); ?>">
            <?php if ($activeTab !== 'all'): ?><input type="hidden" name="tab" value="<?php echo h($activeTab); ?>"><?php endif; ?>
            <div class="filter-grid">
                <label>아티스트<input class="form-control" type="text" name="artist" value="<?php echo h($filters['artist']); ?>"></label>
                <label>앨범<input class="form-control" type="text" name="album" value="<?php echo h($filters['album']); ?>"></label>
                <label>장르<input class="form-control" type="text" name="genre" value="<?php echo h($filters['genre']); ?>"></label>
                <label>태그
                    <select class="form-control" name="tag_id">
                        <option value="">전체 태그</option>
                        <?php foreach ($availableTags as $tag): ?>
                            <option value="<?php echo h($tag['id']); ?>" <?php echo searchSelected($filters['tag_id'], $tag['id']); ?>><?php echo h($tag['name']); ?> (<?php echo number_format((int)$tag['song_count']); ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>별점
                    <select class="form-control" name="min_rating">
                        <option value="">전체</option>
                        <?php for ($i = 1; $i <= 5; $i++): ?><option value="<?php echo $i; ?>" <?php echo searchSelected($filters['min_rating'], $i); ?>><?php echo $i; ?>점 이상</option><?php endfor; ?>
                    </select>
                </label>
                <label>좋아요
                    <select class="form-control" name="liked">
                        <option value="">전체</option>
                        <option value="1" <?php echo searchSelected($filters['liked'], '1'); ?>>좋아요만</option>
                        <option value="0" <?php echo searchSelected($filters['liked'], '0'); ?>>좋아요 제외</option>
                    </select>
                </label>
                <label>메모
                    <select class="form-control" name="has_note">
                        <option value="">전체</option>
                        <option value="1" <?php echo searchSelected($filters['has_note'], '1'); ?>>메모 있음</option>
                        <option value="0" <?php echo searchSelected($filters['has_note'], '0'); ?>>메모 없음</option>
                    </select>
                </label>
                <label>가사
                    <select class="form-control" name="has_lyrics">
                        <option value="">전체</option>
                        <option value="1" <?php echo searchSelected($filters['has_lyrics'], '1'); ?>>가사 있음</option>
                        <option value="0" <?php echo searchSelected($filters['has_lyrics'], '0'); ?>>가사 없음</option>
                    </select>
                </label>
                <label>정렬
                    <select class="form-control" name="sort">
                        <?php foreach ($sortOptions as $key => $label): ?><option value="<?php echo h($key); ?>" <?php echo searchSelected($filters['sort'], $key); ?>><?php echo h($label); ?></option><?php endforeach; ?>
                    </select>
                </label>
            </div>
            <div class="filter-check-row">
                <label><input type="checkbox" name="recent_played" value="1" <?php echo searchChecked($filters['recent_played'] === '1'); ?>> 최근 재생 있음</label>
                <label><input type="checkbox" name="popular_only" value="1" <?php echo searchChecked($filters['popular_only']); ?>> 재생 기록 있음</label>
                <label><input type="checkbox" name="manual_only" value="1" <?php echo searchChecked($filters['manual_only']); ?>> 수동 수정 보호</label>
                <label><input type="checkbox" name="hide_missing_meta" value="1" <?php echo searchChecked($filters['hide_missing_meta']); ?>> 메타데이터 누락 제외</label>
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-primary">필터 적용</button>
                <a href="search.php<?php echo $query !== '' ? '?q=' . urlencode($query) : ''; ?>" class="btn btn-secondary">필터 초기화</a>
            </div>
        </form>
    </details>

    <?php renderFilterBadges($filters, $availableTags); ?>
    <?php
    $tabCounts = [
        'songs' => (int)$searchResult['total'],
        'artists' => count($categories['artists']),
        'albums' => count($categories['albums']),
        'genres' => count($categories['genres']) + count($categories['tags']),
        'playlists' => count($categories['playlists']),
        'lyrics' => (int)($lyricsResult['total'] ?? 0),
    ];
    $showSongs = $activeTab === 'all' || $activeTab === 'songs';
    $showArtists = $activeTab === 'all' || $activeTab === 'artists';
    $showAlbums = $activeTab === 'all' || $activeTab === 'albums';
    $showGenres = $activeTab === 'all' || $activeTab === 'genres';
    $showPlaylists = $activeTab === 'all' || $activeTab === 'playlists';
    $showLyrics = $activeTab === 'all' || $activeTab === 'lyrics';
    if ($hasSearchInput) renderSearchOverviewTabs($activeTab, $tabCounts);
    ?>

    <?php if (!$hasSearchInput): ?>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">최근 추가 음악</h2></div>
            <?php renderSongList($recentFallback, ['show_play_actions' => false]); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">많이 들은 곡</h2></div>
            <?php renderSongList($popularFallback, ['show_play_actions' => false]); ?>
        </section>
    <?php else: ?>
        <?php if ($showSongs): ?>
        <section class="home-section">
            <div class="section-heading-row">
                <h2 class="section-title">곡 검색 결과</h2>
                <span class="settings-muted"><?php echo number_format((int)$searchResult['total']); ?>곡 · <?php echo number_format((int)$searchResult['page']); ?>/<?php echo number_format((int)$searchResult['pages']); ?>페이지</span>
            </div>
            <?php renderSongList($searchResult['songs']); ?>
            <?php renderSearchPager($searchResult); ?>
        </section>
        <?php endif; ?>

        <?php if ($query !== '' && ($showArtists || $showAlbums || $showGenres || $showPlaylists)): ?>
            <div class="search-category-grid">
                <?php if ($showArtists): ?>
                <section class="home-section">
                    <h2 class="section-title">아티스트</h2>
                    <div class="explore-card-grid">
                        <?php foreach ($categories['artists'] as $artist): ?>
                            <a class="explore-card media-explore-card" href="artist.php?name=<?php echo urlencode($artist['artist_name']); ?>">
                                <img src="<?php echo h(coverUrl($artist['cover_song_id'])); ?>" alt="" loading="lazy" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <strong><?php echo h($artist['artist_name']); ?></strong>
                                <span><?php echo number_format((int)$artist['song_count']); ?>곡 · <?php echo number_format((int)$artist['album_count']); ?>앨범</span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($categories['artists'])): ?><p class="empty-text">아티스트 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>
                <?php endif; ?>

                <?php if ($showAlbums): ?>
                <section class="home-section">
                    <h2 class="section-title">앨범</h2>
                    <div class="album-card-grid">
                        <?php foreach ($categories['albums'] as $album): ?>
                            <a class="album-card" href="album.php?album=<?php echo urlencode($album['album_name']); ?>&artist=<?php echo urlencode($album['artist_name']); ?>">
                                <img src="<?php echo h(coverUrl($album['cover_song_id'])); ?>" alt="" class="album-card-cover" loading="lazy" width="120" height="120" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <strong><?php echo h($album['album_name']); ?></strong>
                                <span><?php echo h($album['artist_name']); ?> · <?php echo number_format((int)$album['song_count']); ?>곡</span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($categories['albums'])): ?><p class="empty-text">앨범 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>
                <?php endif; ?>

                <?php if ($showGenres): ?>
                <section class="home-section">
                    <h2 class="section-title">장르 / 태그</h2>
                    <div class="tag-cloud">
                        <?php foreach ($categories['genres'] as $genre): ?>
                            <a class="tag-badge" href="genre.php?name=<?php echo urlencode($genre['genre_name']); ?>"><?php echo h($genre['genre_name']); ?> <small><?php echo number_format((int)$genre['song_count']); ?></small></a>
                        <?php endforeach; ?>
                        <?php foreach ($categories['tags'] 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; ?>
                        <?php if (empty($categories['genres']) && empty($categories['tags'])): ?><p class="empty-text">장르/태그 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>
                <?php endif; ?>

                <?php if ($showPlaylists): ?>
                <section class="home-section">
                    <h2 class="section-title">플레이리스트</h2>
                    <div class="explore-card-grid">
                        <?php foreach ($categories['playlists'] 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']); ?>곡</span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($categories['playlists'])): ?><p class="empty-text">플레이리스트 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($query !== '' && $showLyrics): ?>
            <section class="home-section search-lyrics-section">
                <div class="section-heading-row">
                    <h2 class="section-title">가사 검색 결과</h2>
                    <span class="settings-muted"><?php echo number_format((int)($lyricsResult['total'] ?? 0)); ?>개</span>
                </div>
                <?php if (!empty($lyricsResult['items'])): ?>
                    <div class="lyrics-result-grid">
                        <?php foreach ($lyricsResult['items'] as $item): ?>
                            <?php $song = $item['song']; ?>
                            <article class="lyrics-result-card song-item"
                                     data-id="<?php echo h($song['id']); ?>"
                                     data-title="<?php echo h($song['title']); ?>"
                                     data-artist="<?php echo h(artistName($song['artist'] ?? '')); ?>"
                                     data-album="<?php echo h(albumName($song['album'] ?? '')); ?>"
                                     data-duration="<?php echo h($song['duration'] ?? 0); ?>"
                                     data-cover-url="<?php echo h(coverUrl($song)); ?>">
                                <a class="lyrics-result-cover" href="song.php?id=<?php echo h($song['id']); ?>">
                                    <img src="<?php echo h(coverUrl($song['id'])); ?>" alt="" loading="lazy" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                </a>
                                <div class="lyrics-result-body">
                                    <a class="lyrics-result-title" href="song.php?id=<?php echo h($song['id']); ?>"><?php echo h($song['title']); ?></a>
                                    <p class="lyrics-result-meta"><?php echo h($song['artist'] ?: '알 수 없는 아티스트'); ?> · <?php echo h($song['album'] ?: '알 수 없는 앨범'); ?></p>
                                    <p class="lyrics-result-snippet"><?php echo h($item['snippet']); ?></p>
                                    <div class="lyrics-result-actions">
                                        <button type="button" class="btn btn-primary btn-sm play-row-btn" aria-label="바로 재생"><i class="fa-solid fa-play"></i> 재생</button>
                                        <button type="button" class="btn btn-secondary btn-sm add-playlist-btn" aria-label="플레이리스트에 추가"><i class="fa-solid fa-plus"></i> 추가</button>
                                        <a class="btn btn-secondary btn-sm" href="song.php?id=<?php echo h($song['id']); ?>"><i class="fa-solid fa-circle-info"></i> 상세</a>
                                    </div>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state search-empty-state">
                        <strong>가사에서 일치하는 결과가 없습니다.</strong>
                        <span>다른 단어로 검색하거나 곡 제목, 아티스트명으로 다시 찾아보세요.</span>
                    </div>
                <?php endif; ?>
            </section>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
