<template>
  <div class="iptv-app">
    <!-- 全屏视频播放器 -->
    <VideoPlayer ref="playerRef" :url="currentUrl" @error="handlePlayError" />

    <!-- 左侧面板（四栏） -->
    <LeftPanel
      :current-channel="currentChannel"
      :validity-map="validityMap"
      @play="handlePlay"
    />

    <!-- 底部信息栏 -->
    <BottomPanel
      :channel="currentChannel"
      :current-source-index="currentSourceIndex"
      :current-program="currentProgramTitle"
      :progress="programProgress"
      :current-time="currentTime"
      :total-time="totalTime"
      :is-favorite="isFavorite(currentChannel?.id)"
      @favorite="toggleFavorite(currentChannel?.id)"
      @switch-source="showSourceSelector = true"
      @settings="showSettings = true"
    />

    <!-- 线路选择弹窗 -->
    <SourceModal
      v-if="showSourceSelector"
      :channel="currentChannel"
      :current-url="currentUrl"
      :validity-map="validityMap"
      @switch="switchSource"
      @close="showSourceSelector = false"
    />

    <!-- 设置弹窗 -->
    <SettingsModal
      v-if="showSettings"
      @close="showSettings = false"
      @reload="reloadChannels"
    />

    <!-- 遥控数字输入显示 -->
    <InputPanel @complete="handleRemoteInputComplete" />

    <!-- 调试面板 -->
    <DebugPanel />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useStorage } from "./composables/useStorage.js";
import { useUI } from "./composables/useUI.js";
import { useFavorites } from "./composables/useFavorites.js";
import { useHistory } from "./composables/useHistory.js";
import { useChannels } from "./composables/useChannels.js";
import DebugPanel from "./components/Layout/DebugPanel.vue";
import VideoPlayer from "./components/VideoPlayer.vue";
import LeftPanel from "./components/Layout/LeftPanel.vue";
import InputPanel from "./components/Layout/InputPanel.vue";
import BottomPanel from "./components/Layout/BottomPanel.vue";
import SourceModal from "./components/Modals/SourceModal.vue";
import SettingsModal from "./components/Modals/SettingsModal.vue";
import { useKeyEvent } from "./composables/useEvent.js";

// Storage（底层存储接口，只负责数据存取）
const storage = useStorage();

// UI 状态
const { showLeftPanel, showBottomPanel, hideLeftPanel } = useUI();

// 业务逻辑 hooks（内部使用 useStorage 持久化）
const { toggleFavorite, isFavorite } = useFavorites();
const { addToHistory } = useHistory();
const { channels, loadChannels } = useChannels();

const showSourceSelector = ref(false);
const showSettings = ref(false);

// 播放器
const playerRef = ref(null);
const currentUrl = ref("");
const currentSourceIndex = ref(0);

// 播放状态
const currentChannel = ref(null);

// 播放频道
async function handlePlay(channel) {
  if (!channel || !channel.urls || channel.urls.length === 0) return;

  currentChannel.value = channel;

  // 测速排序后选择最佳线路
  // const sortedUrls = await sortUrlsBySpeed(channel.urls);
  // currentUrl.value = sortedUrls[0] || channel.urls[0];
  currentUrl.value = channel.urls[0];
  currentSourceIndex.value = 0;

  showBottomPanel();
  hideLeftPanel();

  // 添加到播放历史
  await addToHistory(channel);
}

// 测速排序
async function sortUrlsBySpeed(urls) {
  if (!urls || urls.length === 0) return [];

  const results = await Promise.all(
    urls.map(async (url) => {
      // 检查缓存
      const cached = validityMap.value.get(url);
      if (cached && Date.now() - cached.checkedAt < 60 * 60 * 1000) {
        // 1小时内缓存有效
        return { url, ...cached };
      }

      // HTTP HEAD 测速
      const startTime = Date.now();
      try {
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), 5000);

        const response = await fetch(url, {
          method: "HEAD",
          signal: controller.signal,
          mode: "no-cors", // 允许跨域
        });

        clearTimeout(timeout);
        const latency = Date.now() - startTime;

        const validity = {
          status: "online",
          checkedAt: Date.now(),
          latency,
          failCount: 0,
        };

        validityMap.value.set(url, validity);
        await storage.setValidity(url, validity);

        return { url, ...validity };
      } catch (error) {
        // 测速失败
        const cached = validityMap.value.get(url);
        const failCount = (cached?.failCount || 0) + 1;

        const validity = {
          status: failCount >= 3 ? "offline" : "unknown",
          checkedAt: Date.now(),
          latency: Infinity,
          failCount,
        };

        validityMap.value.set(url, validity);
        await storage.setValidity(url, validity);

        return { url, ...validity };
      }
    }),
  );

  // 排序：在线的按延迟排序，离线的放最后
  results.sort((a, b) => {
    if (a.status === "offline" && b.status !== "offline") return 1;
    if (a.status !== "offline" && b.status === "offline") return -1;
    return a.latency - b.latency;
  });

  return results.map((r) => r.url);
}

// 切换线路
function switchSource(source, index) {
  currentUrl.value = source.url;
  currentSourceIndex.value = index;
  playerRef.value?.play(source.url);
  showSourceSelector.value = false;
}

// 播放失败处理
async function handlePlayError() {
  if (!currentChannel.value) return;

  const urls = currentChannel.value.urls;
  if (urls.length <= 1) return; // 只有一个线路，无法切换

  // 尝试下一个线路
  const nextIndex = (currentSourceIndex.value + 1) % urls.length;
  if (nextIndex === 0) {
    // 所有线路都试过了
    console.error("所有线路都失败");
    return;
  }

  currentSourceIndex.value = nextIndex;
  currentUrl.value = urls[nextIndex];

  // 标记当前线路失败
  const url = urls[currentSourceIndex.value];
  const cached = validityMap.value.get(url) || {};
  validityMap.value.set(url, {
    ...cached,
    status: "offline",
    failCount: (cached.failCount || 0) + 1,
  });
}

// 重新加载频道（供设置面板调用）
async function reloadChannels() {
  await loadChannels(true);
}

// 节目信息（TODO: 实际从 EPG 获取）
const currentProgramTitle = ref("精彩节目");
const programProgress = ref(0);
const currentTime = ref("--:--");
const totalTime = ref("--:--");

// 更新节目信息
function updateProgramInfo() {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
  });
  // TODO: 从 EPG 获取当前节目
}

// 线路有效性缓存
const validityMap = ref(new Map());
async function loadValidityCache() {
  const all = await storage.getAllValidity();
  for (const v of all) {
    validityMap.value.set(v.url, v);
  }
}

// 初始化
onMounted(async () => {
  await loadValidityCache();
  // 频道数据由 useChannels 自动加载

  // 定时更新节目信息
  setInterval(updateProgramInfo, 60000);
  updateProgramInfo();
});

// 监听当前频道变化，更新线路有效性
watch(currentChannel, async (channel) => {
  if (!channel || !channel.urls) return;

  // 检查是否需要测速
  const needCheck = channel.urls.some((url) => {
    const cached = validityMap.value.get(url);
    return !cached || Date.now() - cached.checkedAt > 60 * 60 * 1000;
  });

  if (needCheck) {
    // 后台测速
    sortUrlsBySpeed(channel.urls);
  }
});

// 遥控输入完成处理
function handleRemoteInputComplete(value) {
  console.log("遥控输入完成:", value);
  // 根据输入值跳转到对应频道
  const channelIndex = parseInt(value, 10) - 1;
  if (channelIndex >= 0 && channelIndex < channels.value.length) {
    handlePlay(channels.value[channelIndex]);
  }
}

useKeyEvent("Enter", showLeftPanel);
useKeyEvent("Escape", showBottomPanel);
</script>

<style scoped>
.iptv-app {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #000;
  overflow: hidden;
}
</style>
