import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 收藏 & 历史记录 状态管理
export const useStore = defineStore('iptv', () => {
  // ============ 收藏 ============
  const favorites = ref(new Set())
  
  const loadFavorites = () => {
    try {
      const saved = localStorage.getItem('iptv_favorites')
      if (saved) {
        favorites.value = new Set(JSON.parse(saved))
      }
    } catch (e) {
      console.error('加载收藏失败:', e)
    }
  }
  
  const saveFavorites = () => {
    localStorage.setItem('iptv_favorites', JSON.stringify([...favorites.value]))
  }
  
  const toggleFavorite = (channelId) => {
    if (favorites.value.has(channelId)) {
      favorites.value.delete(channelId)
    } else {
      favorites.value.add(channelId)
    }
    saveFavorites()
  }
  
  const isFavorite = (channelId) => favorites.value.has(channelId)
  
  // ============ 播放历史 ============
  const history = ref([])
  const MAX_HISTORY = 10
  
  const loadHistory = () => {
    try {
      const saved = localStorage.getItem('iptv_history')
      if (saved) {
        history.value = JSON.parse(saved)
      }
    } catch (e) {
      console.error('加载历史失败:', e)
    }
  }
  
  const saveHistory = () => {
    localStorage.setItem('iptv_history', JSON.stringify(history.value.slice(0, MAX_HISTORY)))
  }
  
  const addToHistory = (channel) => {
    // 移除重复项
    history.value = history.value.filter(h => h.id !== channel.id)
    // 添加到开头
    history.value.unshift({
      ...channel,
      playedAt: Date.now()
    })
    saveHistory()
  }
  
  const clearHistory = () => {
    history.value = []
    saveHistory()
  }
  
  // ============ 设置 ============
  const settings = ref({
    autoPlay: true,
    defaultVolume: 0.8,
    showEpg: true,
    theme: 'dark',
    checkTimeout: 2000,  // 检测超时时间(ms)
    checkConcurrency: 5  // 并发数
  })
  
  const loadSettings = () => {
    try {
      const saved = localStorage.getItem('iptv_settings')
      if (saved) {
        settings.value = { ...settings.value, ...JSON.parse(saved) }
      }
    } catch (e) {
      console.error('加载设置失败:', e)
    }
  }
  
  const saveSettings = () => {
    localStorage.setItem('iptv_settings', JSON.stringify(settings.value))
  }
  
  const updateSetting = (key, value) => {
    settings.value[key] = value
    saveSettings()
  }
  
  // 初始化
  loadFavorites()
  loadHistory()
  loadSettings()
  
  return {
    // 收藏
    favorites,
    toggleFavorite,
    isFavorite,
    // 历史
    history,
    addToHistory,
    clearHistory,
    // 设置
    settings,
    updateSetting
  }
})
