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

const STORAGE_KEY = "play_history";
const MAX_HISTORY = 20;

// 全局状态
const history = ref([]);
let initialized = false;
let loadPromise = null;

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

  // 加载历史（从 useStorage）
  const loadHistory = async () => {
    if (loadPromise) return loadPromise;

    loadPromise = (async () => {
      try {
        const saved = await storage.get(STORAGE_KEY);
        if (saved) {
          history.value = saved;
        }
      } catch (e) {
        console.error("加载历史失败:", e);
      }
      initialized = true;
    })();

    return loadPromise;
  };

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

  // 添加到历史
  const addToHistory = async (channel) => {
    if (!channel) return;
    // 移除重复项
    history.value = history.value.filter((h) => h.id !== channel.id);
    // 添加到开头
    history.value.unshift({
      ...channel,
      playedAt: Date.now(),
    });
    // 限制数量
    if (history.value.length > MAX_HISTORY) {
      history.value = history.value.slice(0, MAX_HISTORY);
    }
    await saveHistory();
  };

  // 清空历史
  const clearHistory = async () => {
    history.value = [];
    await saveHistory();
  };

  // 获取历史列表
  const getHistory = () => {
    return [...history.value];
  };

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

  return {
    history,
    addToHistory,
    clearHistory,
    getHistory,
  };
}
