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

const STORAGE_KEY = "user_settings";

// 默认设置
const defaultSettings = {
  autoPlay: true,
  defaultVolume: 0.8,
  showEpg: true,
  theme: "dark",
  checkTimeout: 2000, // 检测超时时间(ms)
  checkConcurrency: 5, // 并发数
};

// 全局状态
const settings = ref({ ...defaultSettings });
let initialized = false;
let loadPromise = null;

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

  // 加载设置（从 useStorage）
  const loadSettings = async () => {
    if (loadPromise) return loadPromise;
    
    loadPromise = (async () => {
      try {
        const saved = await storage.get(STORAGE_KEY);
        if (saved) {
          settings.value = { ...defaultSettings, ...saved };
        }
      } catch (e) {
        console.error("加载设置失败:", e);
      }
      initialized = true;
    })();
    
    return loadPromise;
  };

  // 保存设置（到 useStorage）
  const saveSettings = async () => {
    try {
      await storage.set(STORAGE_KEY, settings.value);
    } catch (e) {
      console.error("保存设置失败:", e);
    }
  };

  // 更新单个设置
  const updateSetting = async (key, value) => {
    if (key in settings.value) {
      settings.value[key] = value;
      await saveSettings();
    }
  };

  // 更新多个设置
  const updateSettings = async (newSettings) => {
    settings.value = { ...settings.value, ...newSettings };
    await saveSettings();
  };

  // 重置设置为默认值
  const resetSettings = async () => {
    settings.value = { ...defaultSettings };
    await saveSettings();
  };

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

  return {
    settings,
    updateSetting,
    updateSettings,
    resetSettings,
  };
}
