import { jsx as n, jsxs as I } from "react/jsx-runtime";
import { c as K, i as V, s as p, e as x, f as F, j as M, a as _, u as j, b as q, h as z } from "./provider.js";
import { useRef as L, useCallback as C, useState as R, useEffect as b, Component as G } from "react";
import { c as N } from "./vast-client.min-B0NUra1B.js";
const H = {}, O = new N(), w = V(H), E = K("ui:gam-static"), U = (r) => new Promise((e, a) => {
  const s = new Image();
  s.onload = () => e(r), s.onerror = () => a(), s.src = r;
}), D = () => {
  const r = L(0);
  return [C(async (e) => {
    var a, s, c, o, l, t, u, i, f, m, h;
    if ((a = w.get()[e]) != null && a.imageSrc)
      return { success: !0 };
    const v = Date.now();
    r.current = v, w.setKey(e, { url: e });
    try {
      const d = await O.get(e);
      if (E.debug(d, "parsedVAST"), r.current === v && w.get()[e].url) {
        const y = d.ads.find((g) => g.creatives.length > 0);
        if (y) {
          E.debug(y, "validAd");
          const g = y.creatives.find((S) => S.type === "nonlinear");
          if (g) {
            E.debug(g, "nonlinear");
            const S = (c = (s = g.variations) == null ? void 0 : s[0]) == null ? void 0 : c.staticResource, B = (l = (o = g.variations) == null ? void 0 : o[0]) == null ? void 0 : l.nonlinearClickThroughURLTemplate;
            if (S)
              return await U(S), w.setKey(e, { url: e, imageSrc: S, adUrl: B }), { success: !0 };
          }
          const A = y.creatives.find((S) => S.type === "companion");
          E.debug(A, "companion");
          const T = (f = (i = (u = (t = A == null ? void 0 : A.variations) == null ? void 0 : t[0]) == null ? void 0 : u.staticResources) == null ? void 0 : i[0]) == null ? void 0 : f.url, P = (h = (m = A == null ? void 0 : A.variations) == null ? void 0 : m[0]) == null ? void 0 : h.companionClickThroughURLTemplate;
          if (T)
            return await U(T), w.setKey(e, { url: e, imageSrc: T, adUrl: P }), { success: !0 };
        }
      }
    } catch (d) {
      console.error("Error parsing VAST", d);
    }
    return { success: !1 };
  }, []), w];
}, J = /* @__PURE__ */ p("div")({
  name: "PauseAdOverlay",
  class: "pw9gih8",
  propsAsIs: !1
}), Q = /* @__PURE__ */ p("div")({
  name: "PauseAdContent",
  class: "p8lpomy",
  propsAsIs: !1
}), W = /* @__PURE__ */ p("div")({
  name: "PauseAdGradientLeft",
  class: "pv7u167",
  propsAsIs: !1
}), X = /* @__PURE__ */ p("div")({
  name: "PauseAdGradientRight",
  class: "p1kh2yb0",
  propsAsIs: !1
}), Y = /* @__PURE__ */ p("div")({
  name: "PauseAdGradientBottom",
  class: "pl8f94x",
  propsAsIs: !1
}), Z = /* @__PURE__ */ p("div")({
  name: "PauseAdTopLeft",
  class: "p1m6zmrt",
  propsAsIs: !1
}), $ = /* @__PURE__ */ p("h2")({
  name: "PauseAdTitle",
  class: "pm3vwfa",
  propsAsIs: !1
}), ee = /* @__PURE__ */ p("p")({
  name: "PauseAdCaption",
  class: "p1tibuhw",
  propsAsIs: !1
}), re = /* @__PURE__ */ p("div")({
  name: "PauseAdBottomLeft",
  class: "ptqqrqd",
  propsAsIs: !1
}), se = /* @__PURE__ */ p("button")({
  name: "PauseAdPlayButton",
  class: "p14estxv",
  propsAsIs: !1
}), te = /* @__PURE__ */ p("div")({
  name: "PauseAdSidebar",
  class: "p1dpvfl1",
  propsAsIs: !1
}), k = /* @__PURE__ */ p("img")({
  name: "ExternalAdContainer",
  class: "ezfmabr",
  propsAsIs: !1
}), ne = ({ vastUrl: r }) => {
  var e;
  const [, a] = D(), s = _(a, { keys: [r] });
  return (e = s == null ? void 0 : s[r]) != null && e.imageSrc ? s[r].adUrl ? /* @__PURE__ */ n("a", { href: s[r].adUrl, target: "_blank", rel: "noopener noreferrer", children: /* @__PURE__ */ n(k, { src: s[r].imageSrc }) }) : /* @__PURE__ */ n(k, { src: s[r].imageSrc }) : null;
}, ae = ({ isClosing: r, title: e, caption: a, onPlay: s, onClose: c, vastUrl: o, options: l }) => {
  const t = (l == null ? void 0 : l.showPauseButton) ?? !0, { ref: u, focusSelf: i } = F.useFocusable({
    focusKey: "sl-pause-ad-play",
    onEnterRelease: s,
    isFocusBoundary: !0,
    forceFocus: !0
  });
  return b(() => {
    u.current && i();
  }, [u, i]), b(() => {
    const f = (m) => {
      const h = m.keyCode;
      if (h === 461 || h === 10009 || h === 27) {
        m.preventDefault(), m.stopPropagation(), m.stopImmediatePropagation(), c == null || c();
        return;
      }
    };
    return window.addEventListener("keydown", f, { capture: !0 }), () => window.removeEventListener("keydown", f, { capture: !0 });
  }, [c]), /* @__PURE__ */ n(J, { className: M(r && "pause-ad-closing"), children: /* @__PURE__ */ I(Q, { children: [
    /* @__PURE__ */ n(W, {}),
    /* @__PURE__ */ n(X, {}),
    /* @__PURE__ */ n(Y, {}),
    /* @__PURE__ */ I(Z, { children: [
      /* @__PURE__ */ n($, { children: e }),
      /* @__PURE__ */ n(ee, { children: a })
    ] }),
    t && /* @__PURE__ */ n(re, { children: /* @__PURE__ */ n(
      se,
      {
        ref: u,
        onClick: s,
        onMouseEnter: () => u.current.focus(),
        "aria-label": "Resume playback"
      }
    ) }),
    /* @__PURE__ */ I(te, { children: [
      o && /* @__PURE__ */ n(ne, { vastUrl: o }),
      /* @__PURE__ */ n("span", { children: "ADVERTISEMENT" })
    ] })
  ] }) });
}, oe = ({
  showPauseAd: r,
  vastUrls: e,
  title: a,
  caption: s,
  onPlay: c,
  onClose: o,
  onRender: l,
  options: t
}) => {
  const u = (t == null ? void 0 : t.pauseAdDelay) ?? 5e3, [i, f] = R(!1), [m, h] = R(!1), v = L(), d = e == null ? void 0 : e[0].url, y = L(d);
  y.current = d;
  const [g, A] = D();
  return b(() => {
    if (r && d) {
      x.emit("exposedPauseAd", {
        action: "enabled",
        payload: {}
      }), g(d).then((P) => {
        y.current === d && (P == null ? void 0 : P.success) !== !0 && (clearTimeout(v.current), o == null || o());
      }).catch(() => {
        y.current === d && (clearTimeout(v.current), o == null || o());
      });
      const T = () => {
        var P;
        (P = A.get()[y.current]) != null && P.imageSrc ? (clearTimeout(v.current), h(!1), f(!0), x.emit("exposedPauseAd", {
          action: "rendered",
          payload: {}
        })) : v.current = setTimeout(() => {
          T();
        }, 200);
      };
      v.current = setTimeout(() => {
        T();
      }, u);
    } else
      x.emit("exposedPauseAd", {
        action: "disabled",
        payload: {}
      }), h(!0), v.current = setTimeout(() => {
        f(!1);
      }, 400);
    return () => {
      v.current && clearTimeout(v.current);
    };
  }, [A, g, o, u, r, d]), b(() => {
    l == null || l({ rendered: i });
  }, [i, l]), b(() => () => {
    l == null || l({ rendered: !1 });
  }, [l]), i ? /* @__PURE__ */ n(
    ae,
    {
      onClose: o,
      isClosing: m,
      title: a,
      caption: s,
      onPlay: c,
      vastUrl: d,
      options: t
    }
  ) : null;
}, le = ({
  showPauseAd: r,
  pauseAdVastUrl: e,
  videoPlayerController: a,
  onRenderPauseAd: s,
  onClosePauseAd: c,
  children: o,
  options: l
}) => {
  const t = j(), u = q(), i = L(), f = C(() => {
    c == null || c();
  }, [c]), m = C(() => {
    t == null || t.controlVideoPlayer({ play: !0 });
  }, [t]);
  return b(() => t ? (a && (i.current = a, t.addVideoPlayerController(i.current)), () => {
    i.current && t.removeVideoPlayerController(i.current);
  }) : () => {
  }, [t, a]), t ? /* @__PURE__ */ n("div", { className: "StreamLayerSDK", children: /* @__PURE__ */ I(
    z,
    {
      style: { position: "relative" },
      customTheme: u.theme,
      themeMode: u.themeMode,
      children: [
        o,
        e && /* @__PURE__ */ n(
          oe,
          {
            showPauseAd: r,
            vastUrls: e,
            onClose: f,
            onRender: s,
            onPlay: m,
            options: l
          }
        )
      ]
    }
  ) }) : o;
};
class pe extends G {
  constructor(e) {
    super(e), this.state = { hasError: !1 };
  }
  static getDerivedStateFromError() {
    return { hasError: !0 };
  }
  componentDidCatch(e, a) {
    console.error(e, a.componentStack);
  }
  render() {
    return this.state.hasError ? this.props.children : /* @__PURE__ */ n(le, { ...this.props });
  }
}
export {
  pe as StreamLayerPauseAd
};
