var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellAdyenDashboard/index.tsx
var pisellAdyenDashboard_exports = {};
__export(pisellAdyenDashboard_exports, {
  default: () => pisellAdyenDashboard_default
});
module.exports = __toCommonJS(pisellAdyenDashboard_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_utils = require("@pisell/utils");
var import_adyen_platform_experience_web = require("@adyen/adyen-platform-experience-web");
var import_adyen_platform_experience_web2 = require("@adyen/adyen-platform-experience-web/dist/adyen-platform-experience-web.css");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_utils2 = require("../../utils");
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var DEFAULT_SESSION_ENDPOINT = "/shop/adyen/platform/session";
var DEFAULT_ADYEN_ENVIRONMENT = "test";
var ADYEN_DASHBOARD_TABS = [
  {
    key: "transactions",
    labelKey: "pisell-adyen-dashboard.menu.transactions",
    components: ["transactions"],
    createElement: ({ core, onError }) => new import_adyen_platform_experience_web.TransactionsOverview({ core, onError })
  },
  {
    key: "reports",
    labelKey: "pisell-adyen-dashboard.menu.reports",
    components: ["reports"],
    createElement: ({ core, onError }) => new import_adyen_platform_experience_web.ReportsOverview({ core, onError })
  },
  {
    key: "payouts",
    labelKey: "pisell-adyen-dashboard.menu.payouts",
    components: ["payouts"],
    createElement: ({ core, onError }) => new import_adyen_platform_experience_web.PayoutsOverview({ core, onError })
  },
  {
    key: "disputes",
    labelKey: "pisell-adyen-dashboard.menu.disputes",
    components: ["disputes"],
    createElement: ({ core, onError }) => new import_adyen_platform_experience_web.DisputesOverview({ core, onError })
  }
  // {
  //   key: 'payment-links',
  //   labelKey: 'pisell-adyen-dashboard.menu.paymentLinks',
  //   components: ['pay_by_link'],
  //   createElement: ({ core, onError }) =>
  //     new PaymentLinksOverview({ core, onError }),
  // },
];
var SESSION_COMPONENTS = Array.from(
  new Set(ADYEN_DASHBOARD_TABS.flatMap((tab) => tab.components))
);
var LOADING_FALLBACK_TIMEOUT = 15e3;
var unwrapSessionResponse = (response) => {
  var _a, _b;
  const wrappedResponse = response;
  return ((_a = wrappedResponse.data) == null ? void 0 : _a.id) && ((_b = wrappedResponse.data) == null ? void 0 : _b.token) ? wrappedResponse.data : response;
};
var isAbortError = (error) => {
  const message = error.message.toLowerCase();
  return error.name === "AbortError" || message.includes("abort");
};
var hasRenderedContent = (node) => {
  var _a;
  return node.children.length > 0 || Boolean((_a = node.textContent) == null ? void 0 : _a.trim());
};
var PisellAdyenDashboard = (props) => {
  var _a, _b;
  const {
    className,
    style,
    environment = DEFAULT_ADYEN_ENVIRONMENT,
    ...others
  } = props;
  const context = (0, import_useEngineContext.default)();
  const language = ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en";
  import_utils.locales.init(import_locales.default, language);
  const containerRef = (0, import_react.useRef)(null);
  const elementRef = (0, import_react.useRef)(null);
  const [activeTabKey, setActiveTabKey] = (0, import_react.useState)(
    ADYEN_DASHBOARD_TABS[0].key
  );
  const [core, setCore] = (0, import_react.useState)(null);
  const [errorMessage, setErrorMessage] = (0, import_react.useState)("");
  const [isLoading, setIsLoading] = (0, import_react.useState)(true);
  const activeTab = (0, import_react.useMemo)(
    () => ADYEN_DASHBOARD_TABS.find((tab) => tab.key === activeTabKey) || ADYEN_DASHBOARD_TABS[0],
    [activeTabKey]
  );
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    import_utils2.request.setRequest((_b2 = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.request);
  }, [context]);
  const handleError = (0, import_react.useCallback)((error) => {
    if (isAbortError(error)) return;
    setIsLoading(false);
    setErrorMessage(error.message);
  }, []);
  const handleSessionCreate = (0, import_react.useCallback)(async () => {
    const requestClient = import_utils2.request.getRequest();
    const response = await requestClient.post(DEFAULT_SESSION_ENDPOINT, {
      components: SESSION_COMPONENTS
    });
    return unwrapSessionResponse(response);
  }, []);
  (0, import_react.useEffect)(() => {
    let disposed = false;
    const createAdyenCore = async () => {
      setIsLoading(true);
      setErrorMessage("");
      try {
        const nextCore = await (0, import_adyen_platform_experience_web.AdyenPlatformExperience)({
          environment,
          onError: handleError,
          onSessionCreate: handleSessionCreate
        });
        if (!disposed) {
          setCore(nextCore);
        }
      } catch (error) {
        handleError(error);
      }
    };
    createAdyenCore();
    return () => {
      disposed = true;
    };
  }, [environment, handleError, handleSessionCreate]);
  (0, import_react.useEffect)(() => {
    if (!core || !containerRef.current) return;
    const container = containerRef.current;
    let fallbackTimer;
    let observer;
    setIsLoading(true);
    setErrorMessage("");
    container.innerHTML = "";
    try {
      const element = activeTab.createElement({
        core,
        onError: handleError
      });
      elementRef.current = element;
      element.mount(container);
      const finishLoading = () => {
        if (hasRenderedContent(container)) {
          setIsLoading(false);
          observer == null ? void 0 : observer.disconnect();
          if (fallbackTimer) {
            clearTimeout(fallbackTimer);
          }
        }
      };
      observer = new MutationObserver(finishLoading);
      observer.observe(container, {
        childList: true,
        subtree: true,
        characterData: true
      });
      finishLoading();
      fallbackTimer = setTimeout(() => {
        setIsLoading(false);
        observer == null ? void 0 : observer.disconnect();
      }, LOADING_FALLBACK_TIMEOUT);
    } catch (error) {
      handleError(error);
    }
    return () => {
      observer == null ? void 0 : observer.disconnect();
      if (fallbackTimer) {
        clearTimeout(fallbackTimer);
      }
      if (elementRef.current) {
        elementRef.current.remove();
        elementRef.current = null;
      }
    };
  }, [activeTab, core, handleError]);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ...others,
      className: (0, import_classnames.default)("pisell-adyen-dashboard", className),
      style
    },
    /* @__PURE__ */ import_react.default.createElement("aside", { className: "pisell-adyen-dashboard-menu", role: "tablist" }, ADYEN_DASHBOARD_TABS.map((tab) => /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        key: tab.key,
        className: (0, import_classnames.default)("pisell-adyen-dashboard-menu-item", {
          "pisell-adyen-dashboard-menu-item-active": tab.key === activeTabKey
        }),
        onClick: () => setActiveTabKey(tab.key)
      },
      import_utils.locales.getText(tab.labelKey)
    ))),
    /* @__PURE__ */ import_react.default.createElement("main", { className: "pisell-adyen-dashboard-main" }, errorMessage ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-adyen-dashboard-error" }, errorMessage) : null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-adyen-dashboard-content" }, isLoading ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-adyen-dashboard-loading" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-adyen-dashboard-loading-spinner" }), /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell-adyen-dashboard.loading"))) : null, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "pisell-adyen-dashboard-container",
        ref: containerRef
      }
    )))
  );
};
var pisellAdyenDashboard_default = import_react.default.memo(PisellAdyenDashboard);
