import { ref, computed } from "vue";

export function useChannelFilter() {
  const selectedChannel = ref(null);
  const allChannels = ref([]);
  const selectedGroup = ref("");
  const favorites = ref(new Set());
  const validityMap = ref(new Map());

  // 过滤后的频道
  const filteredChannels = computed(() => {
    if (!selectedGroup.value) return allChannels.value;

    // 置顶分组特殊处理
    if (selectedGroup.value === "recent") {
      // TODO: 返回最近播放
      return [];
    }
    if (selectedGroup.value === "favorite") {
      return allChannels.value.filter((c) => favorites.value.has(c.id));
    }

    return allChannels.value.filter((c) => c.group === selectedGroup.value);
  });

  // 获取频道 LOGO（取前两个字符）
  function getChannelLogo(name) {
    return name?.slice(0, 2) || "--";
  }

  // 检查是否收藏
  function isFavorite(channelId) {
    return favorites.value.has(channelId);
  }

  // 获取有效线路数
  function getValidCount(channel) {
    if (!channel?.urls) return 0;
    return channel.urls.filter((url) => {
      const validity = validityMap.value.get(url);
      return validity?.status === "online";
    }).length;
  }

  // 选择频道
  function selectChannel(channel) {
    selectedChannel.value = channel;
    return channel;
  }

  // 设置数据源
  function setChannels(channels) {
    allChannels.value = channels;
  }

  function setSelectedGroup(group) {
    selectedGroup.value = group;
  }

  function setFavorites(favSet) {
    favorites.value = favSet;
  }

  function setValidityMap(map) {
    validityMap.value = map;
  }

  // 根据当前频道初始化
  function initSelectedChannel(channel) {
    if (channel) {
      selectedChannel.value = channel;
    }
  }

  // 获取第一个频道（用于分组切换时自动选中）
  function getFirstChannel() {
    return filteredChannels.value[0] || null;
  }

  return {
    selectedChannel,
    filteredChannels,
    selectChannel,
    setChannels,
    setSelectedGroup,
    setFavorites,
    setValidityMap,
    initSelectedChannel,
    getFirstChannel,
    getChannelLogo,
    isFavorite,
    getValidCount,
  };
}
