"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
module.exports = CheckoutV2;
var _jsxRuntime = require("react/jsx-runtime");
var _react = require("react");
var _ahooks = require("ahooks");
var _ufo = require("ufo");
var _material = require("@mui/material");
var _paymentReactHeadless = require("@blocklet/payment-react-headless");
var _api = _interopRequireDefault(require("../libs/api"));
var _util = require("../libs/util");
var _theme = require("../theme");
var _mobile = require("../hooks/mobile");
var _checkoutLayout = _interopRequireDefault(require("./layouts/checkout-layout"));
var _scenarioRouter = _interopRequireDefault(require("./panels/left/scenario-router"));
var _paymentPanel = _interopRequireDefault(require("./panels/right/payment-panel"));
var _checkoutDialogs = _interopRequireDefault(require("./components/dialogs/checkout-dialogs"));
var _loadingView = _interopRequireDefault(require("./views/loading-view"));
var _errorView = _interopRequireDefault(require("./views/error-view"));
var _successView = _interopRequireDefault(require("./views/success-view"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const plinkPromises = {};
function startFromPaymentLink(id, params) {
  if (!plinkPromises[id]) {
    plinkPromises[id] = _api.default.post(`/api/checkout-sessions/start/${id}?${(0, _util.mergeExtraParams)(params)}`).then(res => res?.data).finally(() => {
      setTimeout(() => {
        delete plinkPromises[id];
      }, 3e3);
    });
  }
  return plinkPromises[id];
}
function CheckoutRouter({
  onPaid = void 0,
  onError = void 0,
  mode = "inline"
}) {
  const {
    isLoading,
    error,
    errorCode,
    session
  } = (0, _paymentReactHeadless.useSessionContext)();
  const submit = (0, _paymentReactHeadless.useSubmitFeature)();
  const {
    isMobile
  } = (0, _mobile.useMobile)();
  (0, _react.useEffect)(() => {
    if (error && onError) {
      onError(new Error(error));
    }
  }, [error, onError]);
  (0, _react.useEffect)(() => {
    if (submit.status === "completed" && submit.result && onPaid) {
      onPaid(submit.result);
    }
  }, [submit.status, submit.result, onPaid]);
  if (isLoading) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_loadingView.default, {
      mode
    });
  }
  if (error) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_errorView.default, {
      error,
      errorCode,
      mode
    });
  }
  const isCompleted = submit.status === "completed";
  const mobileCompleted = isCompleted && isMobile;
  return /* @__PURE__ */(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_checkoutLayout.default, {
      left: mobileCompleted ? null : /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Box, {
        sx: {
          flex: 1,
          display: "flex",
          flexDirection: "column",
          ...(isCompleted ? {
            opacity: 0.45,
            pointerEvents: "none",
            filter: "grayscale(0.3)",
            transition: "all 0.5s ease"
          } : {})
        },
        children: /* @__PURE__ */(0, _jsxRuntime.jsx)(_scenarioRouter.default, {})
      }),
      right: isCompleted ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_successView.default, {
        submit,
        session
      }) : /* @__PURE__ */(0, _jsxRuntime.jsx)(_paymentPanel.default, {}),
      mode
    }), !isCompleted && /* @__PURE__ */(0, _jsxRuntime.jsx)(_checkoutDialogs.default, {})]
  });
}
function CheckoutV2({
  id,
  onPaid,
  onError,
  theme = "default",
  mode = "inline",
  extraParams = {}
}) {
  if (!id.startsWith("plink_") && !id.startsWith("cs_")) {
    throw new Error("Either a checkoutSession or a paymentLink id is required.");
  }
  const isPaymentLink = id.startsWith("plink_");
  const [resolvedSessionId, setResolvedSessionId] = (0, _react.useState)(isPaymentLink ? null : id);
  (0, _ahooks.useRequest)(async () => {
    if (!isPaymentLink) return null;
    const data = await startFromPaymentLink(id, extraParams);
    const csId = data?.checkoutSession?.id;
    if (csId) {
      setResolvedSessionId(csId);
      if (mode === "standalone") {
        window.history.replaceState(null, "", (0, _ufo.joinURL)((0, _util.getPrefix)(), `/checkout/pay/${csId}?${(0, _util.mergeExtraParams)(extraParams)}`));
      }
    }
    return data;
  }, {
    ready: isPaymentLink
  });
  if (!resolvedSessionId) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_loadingView.default, {
      mode
    });
  }
  const content = /* @__PURE__ */(0, _jsxRuntime.jsx)(_paymentReactHeadless.CheckoutProvider, {
    sessionId: resolvedSessionId,
    children: /* @__PURE__ */(0, _jsxRuntime.jsx)(CheckoutRouter, {
      onPaid,
      onError,
      mode
    })
  });
  if (theme === "inherit") {
    return content;
  }
  if (theme && typeof theme === "object") {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_theme.PaymentThemeProvider, {
      theme,
      children: content
    });
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(_theme.PaymentThemeProvider, {
    children: content
  });
}