import * as React from "react";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
const dealDataCache = /* @__PURE__ */ new Map();
function fetchDealData(id, errorMessage, useCache) {
  const url = `/api/customers/deals/${encodeURIComponent(id)}?include=stages&view=lite`;
  const cached = dealDataCache.get(url);
  if (useCache && cached) return cached.promise;
  const entry = {
    promise: readApiResultOrThrow(
      url,
      void 0,
      { errorMessage }
    )
  };
  if (useCache) dealDataCache.set(url, entry);
  return entry.promise.finally(() => {
    if (dealDataCache.get(url) === entry) dealDataCache.delete(url);
  });
}
function useDealData(id) {
  const t = useT();
  const [data, setData] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const initialLoadDoneRef = React.useRef(false);
  const loadData = React.useCallback(async (options = {}) => {
    if (!id) {
      setIsNotFound(true);
      setIsLoading(false);
      return;
    }
    if (!initialLoadDoneRef.current) {
      setIsLoading(true);
    }
    setError(null);
    try {
      const payload = await fetchDealData(
        id,
        t("customers.deals.detail.error.load", "Failed to load deal."),
        options.cache === true
      );
      setData(payload);
    } catch (loadError) {
      if (loadError.status === 404) {
        setIsNotFound(true);
      } else {
        const message = loadError instanceof Error ? loadError.message : t("customers.deals.detail.error.load", "Failed to load deal.");
        setError(message);
      }
      if (!initialLoadDoneRef.current) setData(null);
    } finally {
      setIsLoading(false);
      initialLoadDoneRef.current = true;
    }
  }, [id, t]);
  return { data, setData, isLoading, error, isNotFound, loadData };
}
export {
  useDealData
};
//# sourceMappingURL=useDealData.js.map
