<template>
  <transition name="fade-slide">
    <div class="fullscreen-player" v-if="isPlayerFullScreen" @click.self="handleClose">
      <!-- 顶部拖拽条 -->
      <div class="top-bar">
        <button class="close-btn" @click="handleClose" title="收起 (Esc)">
          <Icon icon="lucide:chevron-down" />
        </button>
      </div>

      <!-- 背景模糊层 -->
      <div class="background-blur" v-if="currentSong?.picUrl" :style="{ backgroundImage: `url(${currentSong.picUrl})` }"></div>
      <div class="background-overlay"></div>

      <div class="content-wrapper">
        <!-- 左侧：封面 + 歌曲信息 -->
        <div class="left-section">
          <div class="cover-wrapper" :class="{ 'cover-spinning': isPlaying }">
            <img v-if="currentSong?.picUrl" :src="currentSong.picUrl" class="cover-image" alt="封面" />
            <div v-else class="cover-placeholder">
              <Icon icon="lucide:disc" class="placeholder-icon" />
            </div>
          </div>

          <div class="song-info">
            <div class="song-title">{{ currentSong?.name || '未在播放' }}</div>
            <div class="song-artist">{{ currentSong?.artist || '—' }}</div>
            <div v-if="currentSong?.source" class="song-source">来源：{{ currentSong.source }}</div>
          </div>
        </div>

        <!-- 右侧：歌词 + 控制 -->
        <div class="right-section">
          <!-- 歌词区 -->
          <div class="lyric-container" ref="lyricContainer" @click="handleLyricClick">
            <div v-if="lyricLines.length > 0" class="lyric-scroll">
              <div class="lyric-spacer"></div>
              <div
                v-for="(line, idx) in lyricLines"
                :key="idx"
                class="lyric-line"
                :class="{ active: idx === currentLyricIndex }"
                :data-time="line.time"
              >
                {{ line.text || '♪' }}
              </div>
              <div class="lyric-spacer"></div>
            </div>
            <div v-else class="no-lyric">
              <Icon icon="lucide:music" class="no-lyric-icon" />
              <p>暂无歌词</p>
            </div>
          </div>

          <!-- 进度条 -->
          <div class="progress-section">
            <span class="time">{{ formatTime(currentTime) }}</span>
            <input
              type="range"
              class="progress-slider"
              :min="0"
              :max="Math.max(duration, 1)"
              :value="currentTime"
              @input="onSeekInput"
              @change="onSeekChange"
            />
            <span class="time">{{ formatTime(duration) }}</span>
          </div>

          <!-- 控制按钮 -->
          <div class="controls-section">
            <button class="ctrl-btn" @click="toggleMode" :title="modeTitle">
              <Icon :icon="modeIcon" />
            </button>

            <button class="ctrl-btn" @click="prev" title="上一首">
              <Icon icon="lucide:skip-back" />
            </button>

            <button class="ctrl-btn play-btn" @click="togglePlay" :title="isPlaying ? '暂停' : '播放'">
              <Icon :icon="isPlaying ? 'lucide:pause' : 'lucide:play'" />
            </button>

            <button class="ctrl-btn" @click="next" title="下一首">
              <Icon icon="lucide:skip-forward" />
            </button>

            <button class="ctrl-btn" @click="toggleMute" :title="volume === 0 ? '开启声音' : '静音'">
              <Icon :icon="volumeIcon" />
            </button>

            <div class="volume-wrapper">
              <input
                type="range"
                class="volume-slider"
                min="0"
                max="100"
                :value="volume"
                @input="onVolumeInput"
              />
            </div>
          </div>

          <!-- 上下键提示 -->
          <div class="keyboard-hint">
            <kbd>Space</kbd> 播放/暂停 ·
            <kbd>←</kbd><kbd>→</kbd> 切换 ·
            <kbd>↑</kbd><kbd>↓</kbd> 调音量 ·
            <kbd>Esc</kbd> 收起
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { Icon } from '@iconify/vue';
import { usePlayerStore, PlayMode } from '../stores/player';
import { storeToRefs } from 'pinia';

const playerStore = usePlayerStore();
const { isPlaying, currentSong, currentTime, duration, volume, playMode, isPlayerFullScreen } = storeToRefs(playerStore);

const lyricContainer = ref<HTMLElement | null>(null);

// 播放模式图标与标题
const modeIcon = computed(() => {
  switch (playMode.value) {
    case PlayMode.Single: return 'lucide:repeat-1';
    case PlayMode.Random: return 'lucide:shuffle';
    default: return 'lucide:repeat';
  }
});

const modeTitle = computed(() => {
  switch (playMode.value) {
    case PlayMode.Single: return '单曲循环';
    case PlayMode.Random: return '随机播放';
    default: return '列表循环';
  }
});

const volumeIcon = computed(() => {
  if (volume.value === 0) return 'lucide:volume-x';
  if (volume.value < 50) return 'lucide:volume-1';
  return 'lucide:volume-2';
});

// 歌词：从 playerStore 解析出来做简单展示
const lyricLines = computed(() => {
  const lyrics = (playerStore as any).lyrics;
  if (!lyrics || !lyrics.lines || !Array.isArray(lyrics.lines)) return [];
  return lyrics.lines.map((l: any) => ({
    time: typeof l === 'object' ? (l.startTime ?? l.time ?? 0) : l,
    text: typeof l === 'object' ? (l.text ?? l.content ?? String(l)) : String(l),
  })).filter((l: any) => l.text && l.text.trim() !== '');
});

// 当前高亮歌词行
const currentLyricIndex = computed(() => {
  if (lyricLines.value.length === 0) return -1;
  const t = currentTime.value;
  let idx = 0;
  for (let i = 0; i < lyricLines.value.length; i++) {
    if (lyricLines.value[i].time <= t) idx = i;
    else break;
  }
  return idx;
});

// 滚动到当前歌词
watch(currentLyricIndex, () => {
  if (!lyricContainer.value) return;
  const activeEl = lyricContainer.value.querySelector('.lyric-line.active') as HTMLElement | null;
  if (activeEl) {
    const container = lyricContainer.value;
    const offset = activeEl.offsetTop - container.clientHeight / 2 + activeEl.clientHeight / 2;
    container.scrollTo({ top: offset, behavior: 'smooth' });
  }
});

// 点击歌词跳转
const handleLyricClick = (e: MouseEvent) => {
  const target = (e.target as HTMLElement).closest('.lyric-line') as HTMLElement | null;
  if (target && target.dataset.time) {
    const t = Number(target.dataset.time);
    if (!isNaN(t)) playerStore.seek(t);
  }
};

// 控制动作
const togglePlay = () => playerStore.togglePlay();
const next = () => playerStore.next();
const prev = () => playerStore.prev();
const toggleMode = () => playerStore.toggleMode();
const handleClose = () => playerStore.toggleFullScreen();

// 进度/音量拖拽
const onSeekInput = (e: Event) => {
  const val = Number((e.target as HTMLInputElement).value);
  playerStore.seek(val);
};
const onSeekChange = onSeekInput;

const onVolumeInput = (e: Event) => {
  const val = Number((e.target as HTMLInputElement).value);
  playerStore.setVolume(val);
};

const toggleMute = () => {
  if (volume.value > 0) playerStore.setVolume(0);
  else playerStore.setVolume(50);
};

// 工具函数
const formatTime = (ms: number) => {
  if (!ms || isNaN(ms)) return '00:00';
  const seconds = Math.floor(ms / 1000);
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
};

// 键盘快捷键
const handleKeydown = (e: KeyboardEvent) => {
  if (!isPlayerFullScreen.value) return;
  // 如果焦点在输入框内，不拦截
  const target = e.target as HTMLElement;
  if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;

  switch (e.key) {
    case ' ':
      e.preventDefault();
      togglePlay();
      break;
    case 'ArrowRight':
      e.preventDefault();
      next();
      break;
    case 'ArrowLeft':
      e.preventDefault();
      prev();
      break;
    case 'ArrowUp':
      e.preventDefault();
      playerStore.setVolume(Math.min(100, volume.value + 5));
      break;
    case 'ArrowDown':
      e.preventDefault();
      playerStore.setVolume(Math.max(0, volume.value - 5));
      break;
    case 'Escape':
      handleClose();
      break;
  }
};

onMounted(() => {
  window.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown);
});

// 全屏切换时滚动歌词容器到当前行
watch(isPlayerFullScreen, (val) => {
  if (val) {
    nextTick(() => {
      if (currentLyricIndex.value >= 0 && lyricContainer.value) {
        const activeEl = lyricContainer.value.querySelector('.lyric-line.active') as HTMLElement | null;
        if (activeEl) {
          const container = lyricContainer.value;
          const offset = activeEl.offsetTop - container.clientHeight / 2 + activeEl.clientHeight / 2;
          container.scrollTop = offset;
        }
      }
    });
  }
});
</script>

<style scoped>
.fullscreen-player {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  overflow: hidden;
  color: #fff;
}

.top-bar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 16px 24px;
  display: flex;
  justify-content: center;
  z-index: 10;
}

.close-btn {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: background 0.2s, transform 0.2s;
}
.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.background-blur {
  position: absolute;
  top: -10%;
  left: -10%;
  width: 120%;
  height: 120%;
  background-size: cover;
  background-position: center;
  filter: blur(50px) brightness(0.45) saturate(1.2);
  z-index: 0;
}

.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, rgba(10, 10, 20, 0.2) 0%, rgba(10, 10, 20, 0.7) 100%);
  z-index: 1;
}

.content-wrapper {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  padding: 60px 80px 40px;
  box-sizing: border-box;
}

/* 左侧 */
.left-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 32px;
}

.cover-wrapper {
  width: min(40vh, 38vw, 400px);
  height: min(40vh, 38vw, 400px);
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
  position: relative;
  transition: transform 0.3s;
}

.cover-wrapper.cover-spinning {
  animation: slow-spin 40s linear infinite;
}

@keyframes slow-spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #2a2a40, #1a1a2e);
  display: flex;
  align-items: center;
  justify-content: center;
}
.placeholder-icon {
  font-size: 120px;
  opacity: 0.3;
}

.song-info {
  text-align: center;
  max-width: 100%;
}

.song-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

.song-artist {
  font-size: 18px;
  opacity: 0.75;
  margin-bottom: 4px;
}

.song-source {
  font-size: 13px;
  opacity: 0.5;
  margin-top: 8px;
  padding: 4px 12px;
  display: inline-block;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
}

/* 右侧 */
.right-section {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 24px;
  min-width: 0;
}

.lyric-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
  max-height: 50vh;
}
.lyric-container::-webkit-scrollbar { width: 4px; }
.lyric-container::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2); border-radius: 2px; }

.lyric-spacer {
  height: 20vh;
}

.lyric-line {
  padding: 12px 0;
  font-size: 16px;
  line-height: 1.6;
  opacity: 0.4;
  transition: opacity 0.3s, transform 0.3s, font-size 0.3s;
  cursor: pointer;
}

.lyric-line.active {
  opacity: 1;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
}

.no-lyric {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  opacity: 0.4;
  gap: 16px;
}

.no-lyric-icon {
  font-size: 80px;
}

/* 进度 */
.progress-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time {
  font-size: 12px;
  opacity: 0.7;
  font-variant-numeric: tabular-nums;
  min-width: 44px;
  text-align: center;
}

.progress-slider {
  flex: 1;
  appearance: none;
  height: 4px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.2);
  outline: none;
  cursor: pointer;
}

.progress-slider::-webkit-slider-thumb {
  appearance: none;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.progress-slider::-moz-range-thumb {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
  border: none;
}

/* 控制 */
.controls-section {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: center;
}

.ctrl-btn {
  background: rgba(255, 255, 255, 0.08);
  border: none;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  transition: background 0.2s, transform 0.2s;
}

.ctrl-btn:hover {
  background: rgba(255, 255, 255, 0.18);
  transform: scale(1.08);
}

.ctrl-btn:active {
  transform: scale(0.95);
}

.ctrl-btn.play-btn {
  width: 64px;
  height: 64px;
  font-size: 28px;
  background: rgba(99, 102, 241, 0.85);
}
.ctrl-btn.play-btn:hover {
  background: rgba(99, 102, 241, 1);
}

.volume-wrapper {
  width: 100px;
}

.volume-slider {
  width: 100%;
  appearance: none;
  height: 3px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.2);
  outline: none;
  cursor: pointer;
}

.volume-slider::-webkit-slider-thumb {
  appearance: none;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}

.keyboard-hint {
  text-align: center;
  font-size: 12px;
  opacity: 0.45;
  padding-top: 8px;
}

.keyboard-hint kbd {
  display: inline-block;
  padding: 2px 8px;
  margin: 0 2px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  font-family: inherit;
  font-size: 11px;
}

/* 响应式 */
@media (max-width: 900px) {
  .content-wrapper {
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr;
    padding: 60px 24px 24px;
    gap: 24px;
  }
  .cover-wrapper {
    width: 200px;
    height: 200px;
  }
  .song-title { font-size: 20px; }
  .song-artist { font-size: 14px; }
  .lyric-line { font-size: 14px; }
  .lyric-line.active { font-size: 16px; }
  .ctrl-btn { width: 40px; height: 40px; font-size: 18px; }
  .ctrl-btn.play-btn { width: 52px; height: 52px; font-size: 22px; }
}

/* 过渡 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}
.fade-slide-enter-from,
.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
