import { useState, useRef, useCallback, useEffect } from "react";
let globalConfig = { credits: 0 };
const subscribers = /* @__PURE__ */ new Set();
let fetchPromise = null;
let intervalId = null;
let isInitialized = false;
async function fetchConfig() {
  const url = "/editor/config";
  try {
    const result = await fetch(url);
    if (result.status === 200 && result.headers.get("content-type")?.startsWith("application/json")) {
      const data = await result.json();
      return data ?? {};
    } else {
      console.warn("useConfig: ignoring invalid response");
      return {};
    }
  } catch (error) {
    console.error("useConfig: fetch error", error);
    return {};
  }
}
async function loadConfigGlobally() {
  const fetchedConfig = await fetchConfig();
  globalConfig = {
    ...globalConfig,
    ...fetchedConfig
  };
  subscribers.forEach((callback) => callback(globalConfig));
}
function startPolling() {
  if (intervalId) return;
  intervalId = setInterval(() => {
    loadConfigGlobally().catch((error) => {
      console.error("useConfig: polling error", error);
    });
  }, 2e4);
}
function stopPolling() {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
}
function useUserConfig() {
  const [config, setConfig] = useState(globalConfig);
  const subscriberRef = useRef(null);
  const updateConfig = useCallback((newConfig) => {
    setConfig(newConfig);
  }, []);
  useEffect(() => {
    if (!subscriberRef.current) {
      subscriberRef.current = updateConfig;
    }
    subscribers.add(subscriberRef.current);
    if (!isInitialized) {
      isInitialized = true;
      if (!fetchPromise) {
        fetchPromise = loadConfigGlobally().finally(() => {
          fetchPromise = null;
        });
      }
      startPolling();
    }
    return () => {
      if (subscriberRef.current) {
        subscribers.delete(subscriberRef.current);
      }
      if (subscribers.size === 0) {
        stopPolling();
        isInitialized = false;
      }
    };
  }, [updateConfig]);
  return config;
}
export {
  useUserConfig
};
//# sourceMappingURL=use-user-config.js.map
