"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PaymentContext = void 0;
exports.PaymentProvider = PaymentProvider;
exports.SettingsConsumer = void 0;
exports.usePaymentContext = usePaymentContext;
var _jsxRuntime = require("react/jsx-runtime");
var _material = require("@mui/material");
var _ahooks = require("ahooks");
var _react = require("react");
var _axios = _interopRequireDefault(require("axios"));
var _ufo = require("ufo");
var _useBus = _interopRequireDefault(require("use-bus"));
var _api = _interopRequireDefault(require("../libs/api"));
var _util = require("../libs/util");
var _cachedRequest = require("../libs/cached-request");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const formatData = data => {
  if (!data) {
    return {
      paymentMethods: [],
      baseCurrency: {}
    };
  }
  return {
    ...data,
    paymentMethods: data.paymentMethods || [],
    baseCurrency: data.baseCurrency || {}
  };
};
const PaymentContext = exports.PaymentContext = (0, _react.createContext)({
  api: _api.default
});
const {
  Provider,
  Consumer
} = PaymentContext;
exports.SettingsConsumer = Consumer;
const getSettings = (forceRefresh = false) => {
  const livemode = localStorage.getItem("livemode") !== "false";
  const cacheKey = `payment-settings-${window.location.pathname}-${livemode}`;
  const cachedRequest = new _cachedRequest.CachedRequest(cacheKey, () => _api.default.get("/api/settings", {
    params: {
      livemode
    }
  }));
  return cachedRequest.fetch(forceRefresh);
};
const getCurrency = (currencyId, methods) => {
  const currencies = methods.reduce((acc, x) => acc.concat(x.payment_currencies), []);
  return currencies.find(x => x.id === currencyId);
};
const getMethod = (methodId, methods) => {
  return methods.find(x => x.id === methodId);
};
const syncToSpaceRequest = (userDid, spaceDid) => {
  const cacheKey = `sync-space-${userDid}-${spaceDid}`;
  const cachedRequest = new _cachedRequest.CachedRequest(cacheKey, () => _api.default.post("/api/customers/sync-to-space"), {
    ttl: 1e3 * 60 * 60
    // 1 hour
  });
  return cachedRequest.fetch(false).then(res => {
    if (!res.success) {
      cachedRequest.clearCache();
    }
    return res;
  });
};
function PaymentProvider({
  session,
  connect,
  children,
  baseUrl = void 0,
  authToken = void 0
}) {
  const [crossOriginLoading, setCrossOriginLoading] = (0, _react.useState)(false);
  if (authToken) {
    window.__PAYMENT_KIT_AUTH_TOKEN = authToken;
  } else {
    window.__PAYMENT_KIT_AUTH_TOKEN = "";
  }
  (0, _react.useEffect)(() => {
    const fetchCrossOriginBlockletInfo = async () => {
      if (!baseUrl) {
        window.__PAYMENT_KIT_BASE_URL = "";
        setCrossOriginLoading(false);
        return;
      }
      const tmp = new URL(baseUrl);
      if (tmp.origin === window.location.origin) {
        window.__PAYMENT_KIT_BASE_URL = "";
        setCrossOriginLoading(false);
        return;
      }
      setCrossOriginLoading(true);
      try {
        const scriptUrl = (0, _ufo.joinURL)(tmp.origin, "__blocklet__.js?type=json");
        const cacheKey = `cross-origin-blocklet-${tmp.origin}`;
        const cachedRequest = new _cachedRequest.CachedRequest(cacheKey, () => _axios.default.get(scriptUrl).then(res => ({
          data: res.data
        })), {
          strategy: "session",
          ttl: 10 * 60 * 1e3
          // 10 minutes TTL
        });
        const blockletInfo = await cachedRequest.fetch();
        const componentId = (blockletInfo?.componentId || "").split("/").pop();
        if (componentId === _util.PAYMENT_KIT_DID) {
          window.__PAYMENT_KIT_BASE_URL = (0, _ufo.joinURL)(tmp.origin, blockletInfo.prefix || "/");
        } else {
          const component = (blockletInfo?.componentMountPoints || []).find(x => x?.did === _util.PAYMENT_KIT_DID);
          window.__PAYMENT_KIT_BASE_URL = component ? (0, _ufo.joinURL)(tmp.origin, component.mountPoint) : baseUrl;
        }
      } catch (err) {
        console.warn(`Failed to fetch blocklet json from ${baseUrl}:`, err);
        window.__PAYMENT_KIT_BASE_URL = baseUrl;
      } finally {
        setCrossOriginLoading(false);
      }
    };
    fetchCrossOriginBlockletInfo();
  }, [baseUrl]);
  const [livemode, setLivemode] = (0, _ahooks.useLocalStorageState)("livemode", {
    defaultValue: true
  });
  const {
    data = {
      paymentMethods: [],
      baseCurrency: {}
    },
    error,
    run,
    loading
  } = (0, _ahooks.useRequest)(getSettings, {
    refreshDeps: [livemode]
  });
  (0, _useBus.default)(
  // @ts-ignore
  ["paymentMethod.created", "paymentMethod.updated", "paymentCurrency.added", "paymentCurrency.updated"], () => run(true), [run]);
  (0, _react.useEffect)(() => {
    const didSpace = session?.user?.didSpace;
    const userDid = session?.user?.did;
    if (userDid && didSpace && didSpace.endpoint && didSpace.did) {
      syncToSpaceRequest(userDid, didSpace.did);
    }
  }, [session?.user]);
  const prefix = (0, _util.getPrefix)();
  const [payable, setPayable] = (0, _react.useState)(true);
  const [paymentState, setPaymentState] = (0, _react.useState)({
    paying: false,
    stripePaying: false
  });
  const updatePaymentState = state => {
    setPaymentState(prev => ({
      ...prev,
      ...state
    }));
  };
  if (error) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Alert, {
      severity: "error",
      children: error.message
    });
  }
  if (loading || crossOriginLoading) {
    return null;
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(Provider, {
    value: {
      session,
      connect,
      prefix,
      livemode: !!livemode,
      settings: formatData(data),
      getCurrency: currencyId => getCurrency(currencyId, data?.paymentMethods || []),
      getMethod: methodId => getMethod(methodId, data?.paymentMethods || []),
      refresh: run,
      setLivemode,
      api: _api.default,
      payable,
      setPayable,
      paymentState,
      setPaymentState: updatePaymentState
    },
    children
  });
}
function usePaymentContext() {
  const context = (0, _react.useContext)(PaymentContext);
  return context;
}