<template>
  <div
    class="video-player"
    ref="playerRef"
    :class="{
      'is-fullscreen': isFullscreen,
      'is-web-fullscreen': isWebFullscreen,
      'controls-visible': showControls || !isPlaying
    }"
    @mousemove="handleMouseMove"
    @mouseleave="handleMouseLeave"
  >
    <!-- 视频容器 -->
    <div class="video-container" @click="togglePlay">
      <video
        ref="videoRef"
        :src="src"
        :poster="posterUrl"
        class="video-element"
        @loadedmetadata="onLoaded"
        @timeupdate="onTimeUpdate"
        @ended="onEnded"
        @play="isPlaying = true"
        @pause="isPlaying = false"
        @waiting="loading = true"
        @canplay="loading = false"
      />
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
    </div>

    <!-- 播放按钮（中央） -->
    <div v-if="!isPlaying && !loading" class="play-overlay" @click="togglePlay">
      <div class="play-btn">
        <Play :size="48" stroke-width="2" />
      </div>
      <div class="video-title" v-if="title">{{ title }}</div>
    </div>

    <!-- 控制栏 - 使用固定定位确保不被覆盖 -->
    <div class="controls-wrapper">
      <!-- 进度条 -->
      <div class="progress-container">
        <div class="progress-bar" @click="seekByClick" ref="progressRef">
          <div class="progress-buffered" :style="{ width: bufferedPercent + '%' }"></div>
          <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
          <div class="progress-thumb" :style="{ left: progressPercent + '%' }"></div>
        </div>
        <div class="time-tooltip" v-if="hoverTime !== null" :style="{ left: hoverPosition + '%' }">
          {{ formatTime(hoverTime) }}
        </div>
      </div>

      <!-- 控制按钮行 -->
      <div class="controls-row">
        <div class="controls-left">
          <!-- 播放/暂停 -->
          <button class="ctrl-btn" @click="togglePlay" :title="isPlaying ? '暂停 (空格)' : '播放 (空格)'">
            <Pause v-if="isPlaying" :size="22" />
            <Play v-else :size="22" />
          </button>

          <!-- 后退10秒 -->
          <button class="ctrl-btn" @click="skipBackward" title="后退10秒 (左箭头)">
            <RotateCcw :size="20" />
          </button>

          <!-- 前进10秒 -->
          <button class="ctrl-btn" @click="skipForward" title="前进10秒 (右箭头)">
            <RotateCw :size="20" />
          </button>

          <!-- 时间显示 -->
          <span class="time-display">
            {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
          </span>
        </div>

        <div class="controls-right">
          <!-- 播放速度 -->
          <div class="speed-control">
            <button class="ctrl-btn speed-btn" @click="toggleSpeedMenu">
              {{ playbackRate }}x
            </button>
            <div class="speed-menu" v-if="showSpeedMenu">
              <div
                v-for="speed in speedOptions"
                :key="speed"
                class="speed-option"
                :class="{ active: playbackRate === speed }"
                @click="setSpeed(speed)"
              >
                {{ speed }}x
              </div>
            </div>
          </div>

          <!-- 音量 -->
          <div class="volume-control">
            <button class="ctrl-btn" @click="toggleMute" title="静音 (M)">
              <Volume2 v-if="volume > 0.5" :size="20" />
              <Volume1 v-else-if="volume > 0" :size="20" />
              <VolumeX v-else :size="20" />
            </button>
            <div class="volume-slider-wrapper">
              <input
                type="range"
                class="volume-slider"
                :value="volume"
                min="0"
                max="1"
                step="0.05"
                @input="changeVolume"
              />
            </div>
          </div>

          <!-- 循环 -->
          <button
            class="ctrl-btn"
            :class="{ active: isLooping }"
            @click="toggleLoop"
            title="循环播放"
          >
            <Repeat :size="20" />
          </button>

          <!-- 画中画 -->
          <button
            v-if="supportsPiP"
            class="ctrl-btn"
            @click="togglePiP"
            title="画中画"
          >
            <PictureInPicture2 :size="20" />
          </button>

          <!-- 网页全屏 -->
          <button class="ctrl-btn" @click="toggleWebFullscreen" title="网页全屏">
            <Maximize2 v-if="!isWebFullscreen" :size="20" />
            <Minimize2 v-else :size="20" />
          </button>

          <!-- 系统全屏 -->
          <button class="ctrl-btn" @click="toggleFullscreen" title="系统全屏 (F)">
            <Expand v-if="!isFullscreen" :size="20" />
            <Minimize v-else :size="20" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import {
  Play,
  Pause,
  RotateCcw,
  RotateCw,
  Volume2,
  Volume1,
  VolumeX,
  Repeat,
  Maximize2,
  Minimize2,
  Expand,
  Minimize,
  PictureInPicture2,
} from 'lucide-vue-next';

interface Props {
  src: string;
  title?: string;
  poster?: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: 'ended'): void;
  (e: 'play'): void;
  (e: 'pause'): void;
}>();

// Refs
const playerRef = ref<HTMLElement>();
const videoRef = ref<HTMLVideoElement>();
const progressRef = ref<HTMLElement>();

// 状态
const loading = ref(true);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const bufferedEnd = ref(0);
const volume = ref(1);
const playbackRate = ref(1);
const isLooping = ref(false);
const isFullscreen = ref(false);
const isWebFullscreen = ref(false);
const showControls = ref(true);
const showSpeedMenu = ref(false);
const hoverTime = ref<number | null>(null);
const hoverPosition = ref(0);

const speedOptions = [0.5, 0.75, 1, 1.25, 1.5, 2];

// 检测画中画支持
const supportsPiP = ref(
  typeof document !== 'undefined' && 'pictureInPictureEnabled' in document
);

let hideControlsTimer: number | null = null;

// 计算属性
const progressPercent = computed(() => {
  if (duration.value === 0) return 0;
  return (currentTime.value / duration.value) * 100;
});

const bufferedPercent = computed(() => {
  if (duration.value === 0) return 0;
  return (bufferedEnd.value / duration.value) * 100;
});

const posterUrl = computed(() => props.poster || '');

// 方法
const formatTime = (seconds: number) => {
  if (isNaN(seconds) || !isFinite(seconds)) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
};

const togglePlay = () => {
  if (!videoRef.value) return;

  if (isPlaying.value) {
    videoRef.value.pause();
    emit('pause');
  } else {
    videoRef.value.play();
    emit('play');
  }
};

const onLoaded = () => {
  loading.value = false;
  if (videoRef.value) {
    duration.value = videoRef.value.duration;
  }
};

const onTimeUpdate = () => {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime;
    // 更新缓冲进度
    if (videoRef.value.buffered.length > 0) {
      bufferedEnd.value = videoRef.value.buffered.end(videoRef.value.buffered.length - 1);
    }
  }
};

const onEnded = () => {
  isPlaying.value = false;
  emit('ended');
};

const seekByClick = (e: MouseEvent) => {
  if (!progressRef.value || !videoRef.value) return;

  const rect = progressRef.value.getBoundingClientRect();
  const percent = (e.clientX - rect.left) / rect.width;
  const time = percent * duration.value;

  videoRef.value.currentTime = Math.max(0, Math.min(duration.value, time));
  currentTime.value = videoRef.value.currentTime;
};

const skipForward = () => {
  if (videoRef.value) {
    videoRef.value.currentTime = Math.min(duration.value, videoRef.value.currentTime + 10);
  }
};

const skipBackward = () => {
  if (videoRef.value) {
    videoRef.value.currentTime = Math.max(0, videoRef.value.currentTime - 10);
  }
};

const changeVolume = (e: Event) => {
  const target = e.target as HTMLInputElement;
  const vol = parseFloat(target.value);
  volume.value = vol;
  if (videoRef.value) {
    videoRef.value.volume = vol;
  }
};

const toggleMute = () => {
  if (videoRef.value) {
    if (volume.value > 0) {
      volume.value = 0;
      videoRef.value.volume = 0;
    } else {
      volume.value = 1;
      videoRef.value.volume = 1;
    }
  }
};

const toggleSpeedMenu = () => {
  showSpeedMenu.value = !showSpeedMenu.value;
};

const setSpeed = (speed: number) => {
  playbackRate.value = speed;
  if (videoRef.value) {
    videoRef.value.playbackRate = speed;
  }
  showSpeedMenu.value = false;
};

const toggleLoop = () => {
  isLooping.value = !isLooping.value;
  if (videoRef.value) {
    videoRef.value.loop = isLooping.value;
  }
};

const togglePiP = async () => {
  if (!videoRef.value) return;

  try {
    if (document.pictureInPictureElement) {
      await document.exitPictureInPicture();
    } else {
      await videoRef.value.requestPictureInPicture();
    }
  } catch (err) {
    console.warn('Picture-in-Picture not supported:', err);
  }
};

const toggleWebFullscreen = () => {
  isWebFullscreen.value = !isWebFullscreen.value;
  if (isWebFullscreen.value) {
    isFullscreen.value = false;
  }
};

const toggleFullscreen = async () => {
  if (!playerRef.value) return;

  try {
    if (!document.fullscreenElement) {
      await playerRef.value.requestFullscreen();
      isFullscreen.value = true;
      isWebFullscreen.value = false;
    } else {
      await document.exitFullscreen();
      isFullscreen.value = false;
    }
  } catch (err) {
    console.warn('Fullscreen not supported:', err);
  }
};

const handleMouseMove = () => {
  showControls.value = true;
  resetHideTimer();
};

const handleMouseLeave = () => {
  if (isPlaying.value) {
    showControls.value = false;
  }
};

const resetHideTimer = () => {
  if (hideControlsTimer) {
    clearTimeout(hideControlsTimer);
  }
  hideControlsTimer = setTimeout(() => {
    if (isPlaying.value) {
      showControls.value = false;
      showSpeedMenu.value = false;
    }
  }, 3000) as unknown as number;
};

// 键盘事件
const handleKeydown = (e: KeyboardEvent) => {
  // 如果在全屏模式下才响应
  if (!playerRef.value?.contains(document.activeElement) && !isFullscreen.value && !isWebFullscreen.value) {
    return;
  }

  switch (e.key) {
    case ' ':
      e.preventDefault();
      togglePlay();
      break;
    case 'ArrowLeft':
      e.preventDefault();
      skipBackward();
      break;
    case 'ArrowRight':
      e.preventDefault();
      skipForward();
      break;
    case 'ArrowUp':
      e.preventDefault();
      if (videoRef.value) {
        volume.value = Math.min(1, volume.value + 0.1);
        videoRef.value.volume = volume.value;
      }
      break;
    case 'ArrowDown':
      e.preventDefault();
      if (videoRef.value) {
        volume.value = Math.max(0, volume.value - 0.1);
        videoRef.value.volume = volume.value;
      }
      break;
    case 'f':
    case 'F':
      toggleFullscreen();
      break;
    case 'm':
    case 'M':
      toggleMute();
      break;
    case 'Escape':
      if (isWebFullscreen.value) {
        isWebFullscreen.value = false;
      }
      break;
  }
};

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement;
};

// 监听src变化
watch(() => props.src, () => {
  loading.value = true;
  currentTime.value = 0;
});

// 点击外部关闭速度菜单
const handleClickOutside = (e: MouseEvent) => {
  if (showSpeedMenu.value) {
    const target = e.target as HTMLElement;
    if (!target.closest('.speed-control')) {
      showSpeedMenu.value = false;
    }
  }
};

// 生命周期
onMounted(() => {
  document.addEventListener('keydown', handleKeydown);
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('click', handleClickOutside);
  resetHideTimer();
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('click', handleClickOutside);
  if (hideControlsTimer) {
    clearTimeout(hideControlsTimer);
  }
});
</script>

<style scoped lang="scss">
.video-player {
  width: 100%;
  height: 100%;
  position: relative;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  // 网页全屏模式
  &.is-web-fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    border-radius: 0;
  }

  // 系统全屏模式
  &.is-fullscreen {
    border-radius: 0;
  }

  // 控制栏显示状态
  &:not(.controls-visible) {
    cursor: none;

    .controls-wrapper {
      opacity: 0;
      transform: translateY(10px);
    }
  }
}

.video-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  cursor: pointer;
}

.video-element {
  max-width: 100%;
  max-height: 100%;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: #FF8C42;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 5;

  .play-btn {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: rgba(255, 140, 66, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    transition: all 0.3s;
    backdrop-filter: blur(8px);

    &:hover {
      transform: scale(1.1);
      background: rgba(255, 140, 66, 1);
    }
  }

  .video-title {
    margin-top: 20px;
    font-size: 18px;
    color: white;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
    text-align: center;
    padding: 0 20px;
  }
}

// 控制栏 - 固定在底部，使用 flex 确保不被覆盖
.controls-wrapper {
  flex-shrink: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));
  padding: 30px 16px 16px;
  transition: opacity 0.3s, transform 0.3s;
  z-index: 20;
}

.progress-container {
  position: relative;
  margin-bottom: 12px;
  padding: 4px 0;

  .progress-bar {
    height: 4px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 2px;
    cursor: pointer;
    position: relative;
    transition: height 0.2s;

    &:hover {
      height: 6px;

      .progress-thumb {
        transform: translateX(-50%) scale(1);
        opacity: 1;
      }
    }

    .progress-buffered {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      background: rgba(255, 255, 255, 0.3);
      border-radius: 2px;
    }

    .progress-fill {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      background: #FF8C42;
      border-radius: 2px;
      transition: width 0.1s linear;
    }

    .progress-thumb {
      position: absolute;
      top: 50%;
      width: 14px;
      height: 14px;
      background: #FF8C42;
      border-radius: 50%;
      transform: translateX(-50%) translateY(-50%) scale(0);
      opacity: 0;
      transition: transform 0.2s, opacity 0.2s;
      box-shadow: 0 2px 8px rgba(255, 140, 66, 0.5);
    }
  }

  .time-tooltip {
    position: absolute;
    bottom: 20px;
    background: rgba(0, 0, 0, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    transform: translateX(-50%);
    pointer-events: none;
  }
}

.controls-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.controls-left,
.controls-right {
  display: flex;
  align-items: center;
  gap: 4px;
}

.ctrl-btn {
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.9);
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: rgba(255, 255, 255, 0.15);
    color: white;
  }

  &.active {
    color: #FF8C42;
  }
}

.time-display {
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  font-variant-numeric: tabular-nums;
  min-width: 90px;
  margin-left: 8px;
}

.speed-control {
  position: relative;

  .speed-btn {
    font-size: 13px;
    min-width: 50px;
    justify-content: center;
  }

  .speed-menu {
    position: absolute;
    bottom: 100%;
    right: 0;
    background: rgba(30, 30, 30, 0.95);
    border-radius: 8px;
    padding: 4px 0;
    margin-bottom: 8px;
    min-width: 70px;
    backdrop-filter: blur(10px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);

    .speed-option {
      padding: 8px 16px;
      color: rgba(255, 255, 255, 0.8);
      cursor: pointer;
      text-align: center;
      font-size: 13px;
      transition: all 0.2s;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
        color: white;
      }

      &.active {
        color: #FF8C42;
      }
    }
  }
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 0;

  .volume-slider-wrapper {
    width: 0;
    overflow: hidden;
    transition: width 0.3s;
  }

  &:hover .volume-slider-wrapper {
    width: 80px;
    margin-left: 4px;
  }

  .volume-slider {
    width: 80px;
    height: 4px;
    -webkit-appearance: none;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 2px;
    cursor: pointer;

    &::-webkit-slider-thumb {
      -webkit-appearance: none;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: white;
      cursor: pointer;
      transition: transform 0.2s;
    }

    &:hover::-webkit-slider-thumb {
      transform: scale(1.2);
    }
  }
}
</style>
