import { ref, onMounted } from "vue";
import { useStorage } from "./useStorage.js";

const STORAGE_KEY = "favorites_data";

// 全局状态
const favorites = ref(new Set());
let initialized = false;
let loadPromise = null;

export function useFavorites() {
  const storage = useStorage();

  // 加载收藏（从 useStorage）
  const loadFavorites = async () => {
    if (loadPromise) return loadPromise;
    
    loadPromise = (async () => {
      try {
        const saved = await storage.get(STORAGE_KEY);
        if (saved) {
          favorites.value = new Set(saved);
        }
      } catch (e) {
        console.error("加载收藏失败:", e);
      }
      initialized = true;
    })();
    
    return loadPromise;
  };

  // 保存收藏（到 useStorage）
  const saveFavorites = async () => {
    try {
      await storage.set(STORAGE_KEY, [...favorites.value]);
    } catch (e) {
      console.error("保存收藏失败:", e);
    }
  };

  // 切换收藏状态
  const toggleFavorite = async (channelId) => {
    if (!channelId) return;
    if (favorites.value.has(channelId)) {
      favorites.value.delete(channelId);
    } else {
      favorites.value.add(channelId);
    }
    await saveFavorites();
  };

  // 检查是否已收藏
  const isFavorite = (channelId) => {
    return favorites.value.has(channelId);
  };

  // 获取所有收藏
  const getFavorites = () => {
    return [...favorites.value];
  };

  // 初始化加载
  onMounted(() => {
    if (!initialized) {
      loadFavorites();
    }
  });

  return {
    favorites,
    toggleFavorite,
    isFavorite,
    getFavorites,
  };
}
