import { jsx as p } from "react/jsx-runtime";
import { Box as I } from "@mui/material";
import { memo as v, useRef as w, useId as S, useEffect as A, useImperativeHandle as L } from "react";
import { withQuery as R } from "ufo";
import { useReactive as b, useMemoizedFn as x } from "ahooks";
import y from "lodash/noop";
import { mergeSx as E } from "../Util/style.js";
import { callIframe as i, getCallbackAction as d } from "../Util/iframe.js";
function B({
  ref: c = void 0,
  src: t,
  onClick: s,
  onLoad: u = y,
  sx: f = {},
  ...m
}) {
  const o = w(null), a = `shared-bridge_${S()}`, r = b({
    hasInited: void 0,
    open: !1,
    hasStorageAccess: !1,
    containerEl: null,
    get origin() {
      try {
        return new URL(t).origin;
      } catch {
        return t;
      }
    },
    get host() {
      try {
        return new URL(t).host;
      } catch {
        return t;
      }
    }
  });
  A(() => {
    async function e(g) {
      const { data: n } = g;
      if (n.action === d(a, "requestStorageAccess")) {
        if (r.open = !1, !n.value) {
          s(n);
          return;
        }
        const { value: h } = await i(o.current, "getVisitorId");
        s({ ...n, visitorId: h });
      } else n.action === d(a, "preRequestStorageAccess") && (r.open = !0);
    }
    return window.addEventListener("message", e), () => {
      window.removeEventListener("message", e);
    };
  }, [s, a, o?.current]);
  const l = x(() => {
    i(o.current, "hasStorageAccess").then(({ value: e }) => {
      r.hasStorageAccess = e, r.hasInited = !0;
    }), setTimeout(() => {
      r.hasInited === void 0 && (r.hasInited = !1);
    }, 1e3), u();
  });
  return L(c, () => ({
    callIframe(e) {
      return i(o.current, e);
    }
  })), /* @__PURE__ */ p(
    I,
    {
      ...m,
      component: "iframe",
      ref: o,
      onLoad: l,
      "data-id": a,
      src: R(t, { id: a }),
      sx: E(
        {
          border: 0,
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          cursor: "pointer",
          backgroundColor: "transparent"
        },
        f
      )
    }
  );
}
const T = v(B);
export {
  T as default
};
