import { defineStore } from "pinia";

export const useLoadingStore = defineStore("loadingStore", () => {
  // 글로벌 로딩 표기
  const fullLoading = ref(false);
  // 컴포넌트별 로딩 표기 - Map 대신 일반 객체 사용
  const localLoadings = ref<Record<string, { active: boolean }>>({});
  // 로딩 상태만 표기
  const isLoading = ref(false);

  /**
   * 모든 로딩 상태 초기화
   */
  const initializeStore = () => {
    fullLoading.value = false;
    localLoadings.value = {};
  };

  /**
   * Full 로딩
   */
  const startFullLoading = () => {
    fullLoading.value = true;
  };

  const stopFullLoading = () => {
    fullLoading.value = false;
  };

  /**
   * Local 로딩
   */
  const startLocalLoading = (localId: string) => {
    localLoadings.value[localId] = { active: true };
  };

  const stopLocalLoading = (localId: string) => {
    delete localLoadings.value[localId];
  };

  const isLocalLoading = (localId: string) => {
    return localLoadings.value[localId]?.active || false;
  };

  /**
   * 로딩 상태 변경
   */
  const setLoading = (state: boolean) => {
    isLoading.value = state;
  };

  return {
    fullLoading,
    localLoadings,
    isLoading,

    initializeStore,
    startFullLoading,
    stopFullLoading,
    startLocalLoading,
    stopLocalLoading,
    isLocalLoading,
    setLoading,
  };
});
