import { ref, computed } from "vue";

// 置顶分组配置
const PINNED_GROUPS = [
  { id: "recent", name: "最近播放", icon: "⏱" },
  { id: "favorite", name: "收藏", icon: "❤️" },
];

// 分组图标映射
const GROUP_ICONS = {
  央视: "📺",
  卫视: "📡",
  体育: "⚽",
  电影: "🎬",
  少儿: "👶",
};

export function useGroups() {
  const selectedGroup = ref("");
  const rawGroups = ref([]);

  // 计算置顶分组（带数量）
  const pinnedGroups = computed(() => {
    return PINNED_GROUPS.map((g) => ({
      ...g,
      count: 0, // TODO: 实际数量从外部传入
    }));
  });

  // 计算普通分组（带图标和数量）
  const normalGroups = computed(() => {
    return rawGroups.value.map((group) => ({
      id: group,
      name: group,
      icon: getGroupIcon(group),
      count: 0, // TODO: 实际数量从外部传入
    }));
  });

  // 所有分组
  const allGroups = computed(() => [...pinnedGroups.value, ...normalGroups.value]);

  // 获取分组图标
  function getGroupIcon(groupName) {
    for (const [key, icon] of Object.entries(GROUP_ICONS)) {
      if (groupName.includes(key)) return icon;
    }
    return "📺";
  }

  // 选择分组
  function selectGroup(groupId) {
    selectedGroup.value = groupId;
  }

  // 设置原始分组数据
  function setGroups(groups) {
    rawGroups.value = groups;
  }

  // 根据当前频道初始化选中分组
  function initSelectedGroup(channel, defaultGroup = "") {
    if (channel?.group) {
      selectedGroup.value = channel.group;
    } else if (defaultGroup) {
      selectedGroup.value = defaultGroup;
    } else if (rawGroups.value.length > 0) {
      selectedGroup.value = rawGroups.value[0];
    }
  }

  return {
    selectedGroup,
    pinnedGroups,
    normalGroups,
    allGroups,
    selectGroup,
    setGroups,
    initSelectedGroup,
    getGroupIcon,
  };
}
