<template>
  <div class="view-container home-view">
    <div class="content-wrapper">
      <!-- Search bar -->
      <div class="search-section" @click="focusSearch">
        <div class="search-bar" :class="{ focused: searchFocused }">
          <Icon icon="lucide:search" class="search-icon" />
          <input
            ref="searchInput"
            v-model="searchQuery"
            type="text"
            placeholder="搜索歌曲、歌手、专辑..."
            class="search-input"
            @focus="searchFocused = true"
            @blur="searchFocused = false"
            @keydown.enter="doSearch"
          />
          <button class="search-btn" @click.stop="doSearch">搜索</button>
        </div>
      </div>

      <!-- Hot search terms -->
      <div class="section" v-if="hotTerms.length > 0">
        <div class="section-header">
          <h3 class="section-title">热门搜索</h3>
        </div>
        <div class="hot-tags">
          <span
            v-for="(term, idx) in hotTerms"
            :key="idx"
            class="hot-tag"
            :class="{ 'top-three': idx < 3 }"
            @click="searchTerm(term)"
          >
            <span class="tag-rank">{{ idx + 1 }}</span>
            {{ term }}
          </span>
        </div>
      </div>

      <!-- Leaderboard -->
      <div class="section" v-if="rankCategories.length > 0">
        <div class="section-header">
          <h3 class="section-title">排行榜</h3>
        </div>
        <div class="rank-tabs">
          <button
            v-for="cat in rankCategories"
            :key="cat.rankid"
            class="rank-tab"
            :class="{ active: activeRankId === cat.rankid }"
            @click="selectRank(cat.rankid)"
          >
            {{ cat.rankname }}
          </button>
        </div>

        <div class="song-list" v-if="rankSongs.length > 0">
          <div
            v-for="(song, idx) in rankSongs"
            :key="song.hash || idx"
            class="song-item"
            @dblclick="playRankSong(idx)"
          >
            <div class="song-rank-badge" :class="{ 'top-three': idx < 3 }">{{ idx + 1 }}</div>
            <div class="song-cover" v-if="song.imgUrl || song.album_img">
              <img :src="song.imgUrl || song.album_img" :alt="song.songname" loading="lazy" />
            </div>
            <div class="song-cover placeholder" v-else>
              <Icon icon="lucide:music" />
            </div>
            <div class="song-info">
              <h4 class="song-title">{{ song.songname || song.filename }}</h4>
              <p class="song-artist">{{ song.singername || '未知歌手' }}</p>
            </div>
            <span class="song-duration">{{ formatDuration(song.duration! || (song.second ?? 0) * 1000) }}</span>
            <button class="play-btn" @click.stop="playRankSong(idx)" title="播放">
              <Icon icon="lucide:play" width="16" height="16" />
            </button>
          </div>
        </div>
        <div class="loading-state" v-else-if="loadingRank">
          <Icon icon="lucide:loader-2" class="spin" width="24" height="24" />
          <span>加载中...</span>
        </div>
        <div class="empty-state" v-else-if="rankError">
          <Icon icon="lucide:alert-circle" width="24" height="24" />
          <span>{{ rankError }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Icon } from '@iconify/vue';
import { useRouter } from 'vue-router';
import { usePlayerStore } from '../stores/player';
import { transformSearchSong } from '../utils/songUtils';
import type { Song } from '../types/song';

const router = useRouter();
const player = usePlayerStore();

const searchInput = ref<HTMLInputElement | null>(null);
const searchQuery = ref('');
const searchFocused = ref(false);

const hotTerms = ref<string[]>([]);

interface RankCategory {
  rankid: number;
  rankname: string;
  imgUrl?: string;
}

interface RankSong {
  hash: string;
  songname: string;
  singername: string;
  album_name?: string;
  album_img?: string;
  imgUrl?: string;
  filename?: string;
  duration?: number;
  second?: number;
}

const rankCategories = ref<RankCategory[]>([]);
const activeRankId = ref<number>(0);
const rankSongs = ref<RankSong[]>([]);
const loadingRank = ref(false);
const rankError = ref('');

function formatDuration(ms: number): string {
  if (!ms || ms <= 0) return '0:00';
  const totalSec = Math.floor(ms / 1000);
  const min = Math.floor(totalSec / 60);
  const sec = totalSec % 60;
  return `${min}:${sec.toString().padStart(2, '0')}`;
}

function focusSearch() {
  searchInput.value?.focus();
}

function doSearch() {
  const q = searchQuery.value.trim();
  if (q) {
    router.push({ path: '/search', query: { q } });
  }
}

function searchTerm(term: string) {
  searchQuery.value = term;
  router.push({ path: '/search', query: { q: term } });
}

async function fetchHotSearch() {
  try {
    const url = 'https://msearchcdn.kugou.com/api/v3/search/hot';
    const resp = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' } });
    if (!resp.ok) return;
    const data = await resp.json();
    const list = data?.data?.info;
    if (Array.isArray(list)) {
      hotTerms.value = list.slice(0, 15).map((item: any) => item.keyword || item.word || '');
    }
  } catch { /* ignore */ }
}

async function fetchRankList() {
  try {
    const url = 'https://mobilecdnbj.kugou.com/api/v3/rank/list';
    const resp = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' } });
    if (!resp.ok) return;
    const data = await resp.json();
    const ranks = data?.data?.info || data?.data?.list || [];
    if (Array.isArray(ranks)) {
      rankCategories.value = ranks.slice(0, 20).map((r: any) => ({
        rankid: r.rankid || r.id,
        rankname: r.rankname || r.name,
        imgUrl: r.imgUrl || r.img,
      }));
      if (rankCategories.value.length > 0 && !activeRankId.value) {
        activeRankId.value = rankCategories.value[0].rankid;
        fetchRankSongs(activeRankId.value);
      }
    }
  } catch { /* ignore */ }
}

async function fetchRankSongs(rankid: number) {
  loadingRank.value = true;
  rankError.value = '';
  rankSongs.value = [];
  try {
    const url = `https://mobilecdnbj.kugou.com/api/v3/rank/info?rankid=${rankid}&page=1&pagesize=30`;
    const resp = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' } });
    if (!resp.ok) { rankError.value = '加载失败'; loadingRank.value = false; return; }
    const data = await resp.json();
    const list = data?.data?.info || data?.data?.songs || [];
    if (Array.isArray(list)) {
      rankSongs.value = list.map((s: any) => ({
        hash: s.hash || s.songhash || '',
        songname: s.songname || s.name || s.title || '',
        singername: s.singername || s.singer || s.artist || '',
        album_name: s.album_name || s.album || '',
        album_img: s.album_img || s.img || '',
        imgUrl: s.imgUrl || s.img || '',
        filename: s.filename || '',
        duration: s.duration ? Number(s.duration) * 1000 : (s.second ? Number(s.second) * 1000 : 0),
        second: s.second ? Number(s.second) : 0,
      }));
    } else {
      rankError.value = '暂无数据';
    }
  } catch { rankError.value = '网络请求失败'; }
  loadingRank.value = false;
}

function selectRank(rankid: number) {
  activeRankId.value = rankid;
  fetchRankSongs(rankid);
}

function playRankSong(idx: number) {
  const rs = rankSongs.value[idx];
  if (!rs) return;
  const song: Song = transformSearchSong({
    songmid: rs.hash,
    hash: rs.hash,
    name: rs.songname || rs.filename,
    singer: rs.singername,
    img: rs.imgUrl || rs.album_img,
    interval: rs.duration || (rs.second ? rs.second * 1000 : 0),
    source: 'kugou',
    albumName: rs.album_name,
  });
  const list: Song[] = rankSongs.value.map((s) =>
    transformSearchSong({
      songmid: s.hash,
      hash: s.hash,
      name: s.songname || s.filename,
      singer: s.singername,
      img: s.imgUrl || s.album_img,
      interval: s.duration || (s.second ? s.second * 1000 : 0),
      source: 'kugou',
      albumName: s.album_name,
    })
  );
  player.playFromList(song, list);
}

onMounted(() => {
  fetchHotSearch();
  fetchRankList();
});
</script>

<style scoped>
.home-view {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

.content-wrapper {
  box-sizing: border-box;
  padding: 24px;
  max-width: 1100px;
  margin: 0 auto;
}

/* Search */
.search-section {
  margin-bottom: 32px;
}

.search-bar {
  display: flex;
  align-items: center;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border-light);
  border-radius: var(--radius-full);
  padding: 8px 8px 8px 20px;
  transition: all 0.2s;
}

.search-bar.focused {
  border-color: var(--color-accent);
  box-shadow: 0 0 0 3px var(--color-accent-soft);
}

.search-icon {
  width: 20px;
  height: 20px;
  color: var(--color-text-muted);
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  background: none;
  border: none;
  outline: none;
  padding: 8px 12px;
  font-size: var(--font-size-base);
  color: var(--color-text-primary);
}

.search-btn {
  background: var(--color-accent);
  color: var(--color-bg-primary);
  border: none;
  border-radius: var(--radius-full);
  padding: 8px 24px;
  font-weight: 600;
  cursor: pointer;
  transition: opacity 0.2s;
  flex-shrink: 0;
}

.search-btn:hover {
  opacity: 0.85;
}

/* Hot tags */
.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.hot-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 6px 14px;
  background: var(--color-bg-secondary);
  border-radius: var(--radius-full);
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: all 0.15s;
  border: 1px solid transparent;
}

.hot-tag:hover {
  border-color: var(--color-accent);
  color: var(--color-accent);
}

.hot-tag.top-three {
  background: var(--color-accent-soft);
  color: var(--color-accent);
  font-weight: 600;
}

.tag-rank {
  width: 16px;
  text-align: center;
  font-size: 12px;
}

/* Section */
.section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--color-text-primary);
}

/* Rank tabs */
.rank-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  overflow-x: auto;
  padding-bottom: 8px;
  -webkit-overflow-scrolling: touch;
}

.rank-tab {
  flex-shrink: 0;
  padding: 8px 18px;
  background: var(--color-bg-secondary);
  border: 1px solid transparent;
  border-radius: var(--radius-full);
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: all 0.15s;
  white-space: nowrap;
}

.rank-tab:hover {
  border-color: var(--color-border-light);
}

.rank-tab.active {
  background: var(--color-accent);
  color: var(--color-bg-primary);
  font-weight: 600;
}

/* Song list */
.song-list {
  background: var(--color-bg-secondary);
  border-radius: var(--radius-xl);
  padding: 8px;
}

.song-item {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: background 0.15s;
  gap: 12px;
}

.song-item:hover {
  background: var(--color-bg-tertiary);
}

.song-rank-badge {
  width: 28px;
  text-align: center;
  font-size: var(--font-size-sm);
  font-weight: 600;
  color: var(--color-text-muted);
  flex-shrink: 0;
}

.song-rank-badge.top-three {
  color: var(--color-accent);
}

.song-cover {
  width: 44px;
  height: 44px;
  border-radius: var(--radius-md);
  overflow: hidden;
  flex-shrink: 0;
  background: var(--color-bg-tertiary);
}

.song-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.song-cover.placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text-muted);
  font-size: 20px;
}

.song-info {
  flex: 1;
  min-width: 0;
}

.song-title {
  font-size: var(--font-size-base);
  font-weight: 500;
  color: var(--color-text-primary);
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-artist {
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-duration {
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
  flex-shrink: 0;
}

.play-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-text-muted);
  padding: 6px;
  border-radius: var(--radius-sm);
  transition: all 0.15s;
  flex-shrink: 0;
}

.play-btn:hover {
  color: var(--color-accent);
  background: var(--color-bg-tertiary);
}

.loading-state, .empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 60px 0;
  color: var(--color-text-muted);
  font-size: var(--font-size-sm);
}

.spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
