import { css, LitElement, html } from "lit";
import { property, state, customElement } from "lit/decorators.js";
import { ifDefined } from "lit/directives/if-defined.js";
import { createRef, ref } from "lit/directives/ref.js";
import { Task } from "@lit/task";
import { v4 } from "uuid";
import { TEMPLATE_VERSION } from "@vouchfor/canvas-video";
import "@vouchfor/media-player";
import { styleMap } from "lit/directives/style-map.js";
import { classMap } from "lit/directives/class-map.js";
import "@a11y/focus-trap";
function forwardEvent(type, fromElement, toElement) {
  function forwarder(event) {
    toElement.dispatchEvent(new CustomEvent(event.type, event));
  }
  fromElement.addEventListener(type, forwarder);
  return () => {
    fromElement.removeEventListener(type, forwarder);
  };
}
class EventForwardController {
  constructor(host, events) {
    this._events = [];
    this._cleanup = [];
    this._forwardElementRef = createRef();
    this.host = host;
    this._events = events;
    host.addController(this);
  }
  register() {
    return ref(this._forwardElementRef);
  }
  hostConnected() {
    requestAnimationFrame(() => {
      this._events.forEach((event) => {
        if (this._forwardElementRef.value) {
          this._cleanup.push(forwardEvent(event, this._forwardElementRef.value, this.host));
        }
      });
    });
  }
  hostDisconnected() {
    this._cleanup.forEach((fn) => {
      fn();
    });
    this._cleanup = [];
  }
}
const devVideoUrl = "https://d2rxhdlm2q91uk.cloudfront.net";
const stagingVideoUrl = "https://d1ix11aj5kfygl.cloudfront.net";
const prodVideoUrl = "https://d157jlwnudd93d.cloudfront.net";
const devPublicApiUrl = "https://bshyfw4h5a.execute-api.ap-southeast-2.amazonaws.com/dev";
const stagingPublicApiUrl = "https://gyzw7rpbq3.execute-api.ap-southeast-2.amazonaws.com/staging";
const prodPublicApiUrl = "https://vfcjuim1l3.execute-api.ap-southeast-2.amazonaws.com/prod";
const localEmbedApiUrl = "http://localhost:6060/v2";
const devEmbedApiUrl = "https://embed-dev.vouchfor.com/v2";
const stagingEmbedApiUrl = "https://embed-staging.vouchfor.com/v2";
const prodEmbedApiUrl = "https://embed.vouchfor.com/v2";
function getEnvUrls(env) {
  if (!["local", "dev", "staging", "prod"].includes(env)) {
    throw new Error(`Unknown environment: ${env}`);
  }
  if (env === "local") {
    return {
      videoUrl: devVideoUrl,
      publicApiUrl: devPublicApiUrl,
      embedApiUrl: localEmbedApiUrl
    };
  }
  if (env === "dev") {
    return {
      videoUrl: devVideoUrl,
      publicApiUrl: devPublicApiUrl,
      embedApiUrl: devEmbedApiUrl
    };
  }
  if (env === "staging") {
    return {
      videoUrl: stagingVideoUrl,
      publicApiUrl: stagingPublicApiUrl,
      embedApiUrl: stagingEmbedApiUrl
    };
  }
  if (env === "prod") {
    return {
      videoUrl: prodVideoUrl,
      publicApiUrl: prodPublicApiUrl,
      embedApiUrl: prodEmbedApiUrl
    };
  }
}
class FetcherController {
  constructor(host) {
    this._fetching = false;
    this.getVouch = async (env, apiKey, vouchId) => {
      var _a;
      const { embedApiUrl } = getEnvUrls(env);
      const cacheCheck = v4();
      const res = await fetch(`${embedApiUrl}/vouches/${vouchId}`, {
        method: "GET",
        headers: [
          ["X-Api-Key", apiKey],
          ["X-Cache-Check", cacheCheck]
        ]
      });
      const vouch = await res.json();
      this.host.dispatchEvent(new CustomEvent("vouch:loaded", { detail: vouch == null ? void 0 : vouch.id }));
      const resCacheCheck = (_a = res == null ? void 0 : res.headers) == null ? void 0 : _a.get("X-Cache-Check");
      if (resCacheCheck !== cacheCheck) {
        fetch(`${embedApiUrl}/vouches/${vouchId}`, {
          method: "GET",
          headers: [
            ["X-Api-Key", apiKey],
            ["Cache-Control", "max-age=0"]
          ]
        });
      }
      return vouch;
    };
    this.getTemplate = async (env, apiKey, templateId) => {
      var _a;
      const { embedApiUrl } = getEnvUrls(env);
      const cacheCheck = v4();
      const res = await fetch(`${embedApiUrl}/templates/${templateId}`, {
        method: "GET",
        headers: [
          ["X-Api-Key", apiKey],
          ["X-Cache-Check", cacheCheck]
        ]
      });
      const template = await res.json();
      const resCacheCheck = (_a = res == null ? void 0 : res.headers) == null ? void 0 : _a.get("X-Cache-Check");
      if (resCacheCheck !== cacheCheck) {
        fetch(`${embedApiUrl}/templates/${templateId}`, {
          method: "GET",
          headers: [
            ["X-Api-Key", apiKey],
            ["Cache-Control", "max-age=0"]
          ]
        });
      }
      return template;
    };
    this.host = host;
    new Task(
      this.host,
      async ([env, apiKey, data, vouchId, templateId]) => {
        var _a, _b, _c, _d;
        try {
          host.vouch = void 0;
          host.template = void 0;
          if (data) {
            let template;
            if (templateId) {
              this.fetching = true;
              template = await this.getTemplate(env, apiKey, templateId);
            }
            this._vouch = data;
            host.template = template ?? ((_b = (_a = data == null ? void 0 : data.settings) == null ? void 0 : _a.template) == null ? void 0 : _b.instance);
          } else if (vouchId) {
            this.fetching = true;
            const [vouch, template] = await Promise.all([
              this.getVouch(env, apiKey, vouchId),
              templateId ? this.getTemplate(env, apiKey, templateId) : null
            ]);
            this._vouch = vouch;
            host.template = template ?? ((_d = (_c = vouch == null ? void 0 : vouch.settings) == null ? void 0 : _c.template) == null ? void 0 : _d.instance);
          }
        } finally {
          this.fetching = false;
        }
      },
      () => [host.env, host.apiKey, host.data, host.vouchId, host.templateId]
    );
    new Task(
      this.host,
      ([vouch, questions]) => {
        host.vouch = vouch ? {
          ...vouch,
          questions: {
            items: vouch == null ? void 0 : vouch.questions.items.filter((_, index) => !(questions == null ? void 0 : questions.length) || (questions == null ? void 0 : questions.includes(index + 1)))
          }
        } : void 0;
      },
      () => [this._vouch, host.questions]
    );
  }
  set fetching(value) {
    if (this._fetching !== value) {
      this._fetching = value;
      this.host.requestUpdate();
    }
  }
  get fetching() {
    return this._fetching;
  }
}
const version = "4.4.1";
const packageJson = {
  version
};
function createVisitor(env) {
  const { publicApiUrl } = getEnvUrls(env);
  const visitorId = v4();
  navigator.sendBeacon(`${publicApiUrl}/api/visitor`, JSON.stringify({ visitorId }));
  return visitorId;
}
function getUids(env) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
  if (typeof window === "undefined") {
    return {
      client: null,
      tab: null,
      request: v4()
    };
  }
  let visitorId = (_b = (_a = window.localStorage) == null ? void 0 : _a.getItem) == null ? void 0 : _b.call(_a, "vouch-uid-visitor");
  let clientId = (_d = (_c = window.localStorage) == null ? void 0 : _c.getItem) == null ? void 0 : _d.call(_c, "vouch-uid-client");
  let tabId = (_f = (_e = window.sessionStorage) == null ? void 0 : _e.getItem) == null ? void 0 : _f.call(_e, "vouch-uid-tab");
  const requestId = v4();
  if (!visitorId) {
    visitorId = createVisitor(env);
    (_h = (_g = window.localStorage) == null ? void 0 : _g.setItem) == null ? void 0 : _h.call(_g, "vouch-uid-visitor", visitorId);
  }
  if (!clientId) {
    clientId = v4();
    (_j = (_i = window.localStorage) == null ? void 0 : _i.setItem) == null ? void 0 : _j.call(_i, "vouch-uid-client", clientId);
  }
  if (!tabId) {
    tabId = v4();
    (_l = (_k = window.sessionStorage) == null ? void 0 : _k.setItem) == null ? void 0 : _l.call(_k, "vouch-uid-tab", tabId);
  }
  return {
    client: clientId,
    tab: tabId,
    request: requestId,
    visitor: visitorId
  };
}
function findVouchId(payload, vouch) {
  if (payload && "vouchId" in payload) {
    return payload.vouchId;
  }
  return (vouch == null ? void 0 : vouch.id) ?? null;
}
function getReportingMetadata(source = "embedded_player") {
  var _a, _b;
  const [country, region] = ((_b = (_a = Intl.DateTimeFormat().resolvedOptions().timeZone) == null ? void 0 : _a.split) == null ? void 0 : _b.call(_a, "/")) ?? [];
  const utmParams = {};
  [...new URLSearchParams(location.search).entries()].forEach(([key, value]) => {
    if (/utm/.test(key)) {
      const param = key.toLowerCase().replace(/[-_][a-z0-9]/g, (group) => group.slice(-1).toUpperCase());
      utmParams[param] = value;
    }
  });
  return {
    source,
    time: /* @__PURE__ */ new Date(),
    region,
    country,
    screenHeight: window.screen.height,
    screenWidth: window.screen.width,
    referrer: document.referrer,
    currentUrl: location.href,
    embedType: "media-player-embed",
    embedVersion: packageJson.version,
    templateVersion: TEMPLATE_VERSION,
    ...utmParams
  };
}
const MINIMUM_SEND_THRESHOLD = 1;
class TrackingController {
  constructor(host) {
    this._batchedEvents = [];
    this._hasPlayed = false;
    this._hasLoaded = {};
    this._answersViewed = {};
    this._streamStartTime = {};
    this._streamLatestTime = {};
    this._currentlyPlayingVideo = null;
    this._createTrackingEvent = (event, payload) => {
      const vouchId = findVouchId(payload, this.host.vouch);
      if (!vouchId || this.host.disableTracking) {
        return;
      }
      this._batchedEvents.push({
        event,
        payload: {
          ...payload,
          vouchId,
          time: (/* @__PURE__ */ new Date()).toISOString()
        }
      });
    };
    this._sendTrackingEvent = () => {
      if (this._batchedEvents.length <= 0) {
        return;
      }
      const { publicApiUrl } = getEnvUrls(this.host.env);
      const { client, tab, request, visitor } = getUids(this.host.env);
      navigator.sendBeacon(
        `${publicApiUrl}/api/batchevents`,
        JSON.stringify({
          payload: {
            events: this._batchedEvents
          },
          context: {
            "x-uid-client": client,
            "x-uid-tab": tab,
            "x-uid-request": request,
            "x-uid-visitor": visitor,
            "x-reporting-metadata": getReportingMetadata(this.host.trackingSource)
          }
        })
      );
      this._batchedEvents = [];
    };
    this._streamEnded = () => {
      if (this._currentlyPlayingVideo) {
        const { id, key } = this._currentlyPlayingVideo;
        if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
          this._createTrackingEvent("VIDEO_STREAMED", {
            answerId: id,
            streamStart: this._streamStartTime[key],
            streamEnd: this._streamLatestTime[key]
          });
        }
        delete this._streamStartTime[key];
        delete this._streamLatestTime[key];
      }
    };
    this._handleVouchLoaded = ({ detail: vouchId }) => {
      if (!vouchId) {
        return;
      }
      if (!this._hasLoaded[vouchId]) {
        this._createTrackingEvent("VOUCH_LOADED", { vouchId });
        this._hasLoaded[vouchId] = true;
      }
    };
    this._handlePlay = () => {
      if (!this._hasPlayed) {
        this._createTrackingEvent("VIDEO_PLAYED", {
          streamStart: this.host.currentTime
        });
        this._hasPlayed = true;
      }
    };
    this._handleVideoPlay = ({ detail: { id, key } }) => {
      if (!this._answersViewed[key]) {
        this._createTrackingEvent("VOUCH_RESPONSE_VIEWED", {
          answerId: id
        });
        this._answersViewed[key] = true;
      }
    };
    this._handleVideoTimeUpdate = ({ detail: { id, key, node } }) => {
      if (
        // We only want to count any time that the video is actually playing
        !this.host.paused
      ) {
        this._currentlyPlayingVideo = { id, key, node };
        this._streamLatestTime[key] = node.currentTime;
        if (!this._streamStartTime[key]) {
          this._streamStartTime[key] = node.currentTime;
          this._streamLatestTime[key] = node.currentTime;
        }
      }
    };
    this._handleVideoPause = ({ detail: { id, key } }) => {
      if (this._streamLatestTime[key] > this._streamStartTime[key] + MINIMUM_SEND_THRESHOLD) {
        this._createTrackingEvent("VIDEO_STREAMED", {
          answerId: id,
          streamStart: this._streamStartTime[key],
          streamEnd: this._streamLatestTime[key]
        });
      }
      delete this._streamStartTime[key];
      delete this._streamLatestTime[key];
    };
    this._pageUnloading = () => {
      this._streamEnded();
      this._sendTrackingEvent();
    };
    this._handleVisibilityChange = () => {
      if (document.visibilityState === "hidden") {
        this._pageUnloading();
      }
    };
    this._handlePageHide = () => {
      this._pageUnloading();
    };
    this.host = host;
    host.addController(this);
  }
  hostConnected() {
    requestAnimationFrame(() => {
      var _a, _b, _c, _d;
      if ("onvisibilitychange" in document) {
        document.addEventListener("visibilitychange", this._handleVisibilityChange);
      } else {
        window.addEventListener("pagehide", this._handlePageHide);
      }
      this.host.addEventListener("vouch:loaded", this._handleVouchLoaded);
      (_a = this.host.mediaPlayer) == null ? void 0 : _a.addEventListener("play", this._handlePlay);
      (_b = this.host.mediaPlayer) == null ? void 0 : _b.addEventListener("video:play", this._handleVideoPlay);
      (_c = this.host.mediaPlayer) == null ? void 0 : _c.addEventListener("video:pause", this._handleVideoPause);
      (_d = this.host.mediaPlayer) == null ? void 0 : _d.addEventListener("video:timeupdate", this._handleVideoTimeUpdate);
    });
  }
  hostDisconnected() {
    var _a, _b, _c, _d;
    this._pageUnloading();
    if ("onvisibilitychange" in document) {
      document.removeEventListener("visibilitychange", this._handleVisibilityChange);
    } else {
      window.removeEventListener("pagehide", this._handlePageHide);
    }
    this.host.removeEventListener("vouch:loaded", this._handleVouchLoaded);
    (_a = this.host.mediaPlayer) == null ? void 0 : _a.removeEventListener("play", this._handlePlay);
    (_b = this.host.mediaPlayer) == null ? void 0 : _b.removeEventListener("video:play", this._handleVideoPlay);
    (_c = this.host.mediaPlayer) == null ? void 0 : _c.removeEventListener("video:pause", this._handleVideoPause);
    (_d = this.host.mediaPlayer) == null ? void 0 : _d.removeEventListener("video:timeupdate", this._handleVideoTimeUpdate);
  }
}
var __defProp$3 = Object.defineProperty;
var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
var __decorateClass$3 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$3(target, key, result);
  return result;
};
let PlayerEmbed = class extends LitElement {
  constructor() {
    super(...arguments);
    this.env = "prod";
    this.apiKey = "";
    this.disableTracking = false;
    this.trackingSource = "embedded_player";
    this.preload = "auto";
    this.autoplay = false;
    this.aspectRatio = 0;
    this.eventController = new EventForwardController(this, [
      "durationchange",
      "ended",
      "error",
      "loadeddata",
      "pause",
      "stalled",
      "play",
      "playing",
      "ratechange",
      "scenechange",
      "scenesupdate",
      "seeking",
      "seeked",
      "timeupdate",
      "volumechange",
      "processing",
      "waiting",
      "video:loadeddata",
      "video:seeking",
      "video:seeked",
      "video:play",
      "video:playing",
      "video:pause",
      "video:stalled",
      "video:timeupdate",
      "video:ended",
      "video:error"
    ]);
    this._fetcherController = new FetcherController(this);
    this._trackingController = new TrackingController(this);
    this._mediaPlayerRef = createRef();
  }
  get fetching() {
    return this._fetcherController.fetching;
  }
  get waiting() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.waiting;
  }
  get initialised() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.initialised;
  }
  get seeking() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.seeking;
  }
  get paused() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.paused;
  }
  get captions() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.captions;
  }
  get fullscreen() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.fullscreen;
  }
  get duration() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.duration;
  }
  set currentTime(value) {
    if (this._mediaPlayerRef.value) {
      this._mediaPlayerRef.value.currentTime = value;
    }
  }
  get currentTime() {
    var _a;
    return ((_a = this._mediaPlayerRef.value) == null ? void 0 : _a.currentTime) ?? 0;
  }
  set playbackRate(value) {
    if (this._mediaPlayerRef.value) {
      this._mediaPlayerRef.value.playbackRate = value;
    }
  }
  get playbackRate() {
    var _a;
    return ((_a = this._mediaPlayerRef.value) == null ? void 0 : _a.playbackRate) ?? 1;
  }
  set volume(value) {
    if (this._mediaPlayerRef.value) {
      this._mediaPlayerRef.value.volume = value;
    }
  }
  get volume() {
    var _a;
    return ((_a = this._mediaPlayerRef.value) == null ? void 0 : _a.volume) ?? 1;
  }
  set muted(value) {
    if (this._mediaPlayerRef.value) {
      this._mediaPlayerRef.value.muted = value;
    }
  }
  get muted() {
    var _a;
    return ((_a = this._mediaPlayerRef.value) == null ? void 0 : _a.muted) ?? false;
  }
  // get scene(): Scene | null {
  //   return this._mediaPlayerRef.value?.scene ?? null;
  // }
  // get scenes(): Scene[] {
  //   return this._mediaPlayerRef.value?.scenes ?? [];
  // }
  // get sceneConfig(): Scenes | null {
  //   return this._mediaPlayerRef.value?.sceneConfig ?? null;
  // }
  get mediaState() {
    var _a;
    return (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.mediaState;
  }
  get mediaPlayer() {
    return this._mediaPlayerRef.value;
  }
  play() {
    var _a;
    (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.play();
  }
  pause() {
    var _a;
    (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.pause();
  }
  reset(time = 0, play = false) {
    var _a;
    (_a = this._mediaPlayerRef.value) == null ? void 0 : _a.reset(time, play);
  }
  // setScene(index: number) {
  //   this._mediaPlayerRef.value?.setScene(index);
  // }
  _renderStyles() {
    if (!this.aspectRatio) {
      return html`
        <style>
          :host {
            width: 100%;
            height: 100%;
          }
        </style>
      `;
    }
    if (typeof this.aspectRatio === "number") {
      return html`
        <style>
          :host {
            aspect-ratio: ${this.aspectRatio};
          }
        </style>
      `;
    }
    return null;
  }
  willUpdate(changedProperties) {
    if (changedProperties.has("vouchId") && this.vouchId !== changedProperties.get("vouchId")) {
      this.reset(0, false);
    }
  }
  render() {
    return html`
      ${this._renderStyles()}
      <vmp-media-player
        ${ref(this._mediaPlayerRef)}
        ${this.eventController.register()}
        ?autoplay=${this.autoplay}
        ?loading=${this.fetching}
        aspectRatio=${ifDefined(this.aspectRatio)}
        preload=${ifDefined(this.preload)}
        language=${ifDefined(this.language)}
        .controls=${this.controls}
      ></vmp-media-player>
    `;
  }
};
PlayerEmbed.styles = [
  css`
      :host {
        display: flex;
      }
    `
];
__decorateClass$3([
  property({ type: Object })
], PlayerEmbed.prototype, "data", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "vouchId", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "templateId", 2);
__decorateClass$3([
  property({ type: Array })
], PlayerEmbed.prototype, "questions", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "env", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "apiKey", 2);
__decorateClass$3([
  property({ type: Boolean })
], PlayerEmbed.prototype, "disableTracking", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "trackingSource", 2);
__decorateClass$3([
  property({ type: Array })
], PlayerEmbed.prototype, "controls", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "preload", 2);
__decorateClass$3([
  property({ type: Boolean })
], PlayerEmbed.prototype, "autoplay", 2);
__decorateClass$3([
  property({ type: Number })
], PlayerEmbed.prototype, "aspectRatio", 2);
__decorateClass$3([
  property({ type: String })
], PlayerEmbed.prototype, "language", 2);
__decorateClass$3([
  state()
], PlayerEmbed.prototype, "vouch", 2);
__decorateClass$3([
  state()
], PlayerEmbed.prototype, "template", 2);
PlayerEmbed = __decorateClass$3([
  customElement("vouch-embed-player")
], PlayerEmbed);
var __defProp$2 = Object.defineProperty;
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
var __decorateClass$2 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$2(target, key, result);
  return result;
};
let DialogOverlay = class extends LitElement {
  constructor() {
    super(...arguments);
    this.open = false;
    this.aspectRatio = 0;
  }
  render() {
    return html`
      <div
        class=${classMap({
      container: true,
      hidden: !this.open
    })}
      >
        <div
          class="background"
          @click=${() => this.dispatchEvent(new CustomEvent("overlay:click", { bubbles: true, composed: true }))}
        ></div>
        <focus-trap>
          <div
            class=${classMap({
      "video-frame": true,
      grow: this.aspectRatio === 0
    })}
            style=${styleMap({
      aspectRatio: this.aspectRatio
    })}
          >
            <slot></slot>
            <vmp-icon-button
              icon="close"
              rounded="full"
              weight="heavy"
              @click=${() => this.dispatchEvent(new CustomEvent("close:click", { bubbles: true, composed: true }))}
            ></vmp-icon-button>
          </div>
        </focus-trap>
      </div>
    `;
  }
};
DialogOverlay.styles = [
  css`
      :host {
        --vouch-media-player-border-radius: var(--vu-media-player-border-radius, 12px);
        --overlay-background-color: var(--vu-overlay-background-color, black);
        --overlay-background-opacity: var(--vu-overlay-background-opacity, 0.4);

        --dialog-width: var(--vu-dialog-width, 890px);
        --dialog-height: var(--vu-dialog-height, 500px);
      }

      .container {
        position: fixed;
        display: flex;
        inset: 0;
        opacity: 1;
        z-index: 2147483647;
        align-items: center;
        justify-content: center;
        transition: opacity 100ms ease-in;
      }

      .hidden {
        opacity: 0;
        pointer-events: none;
      }

      .background {
        position: absolute;
        inset: 0;
        opacity: var(--overlay-background-opacity);
        background-color: var(--overlay-background-color);
      }

      focus-trap {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 40px;
        width: var(--dialog-width);
        height: var(--dialog-height);
        max-width: calc(100% - 80px);
        max-height: calc(100% - 80px);
      }

      .video-frame {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        max-width: 100%;
        max-height: 100%;
      }

      .video-frame.grow {
        width: 100%;
        height: 100%;
      }

      vmp-icon-button {
        position: absolute;
        top: 0;
        right: 0;
        margin: 10px;
      }
    `
];
__decorateClass$2([
  property({ type: Boolean })
], DialogOverlay.prototype, "open", 2);
__decorateClass$2([
  property({ type: Number })
], DialogOverlay.prototype, "aspectRatio", 2);
DialogOverlay = __decorateClass$2([
  customElement("vouch-embed-dialog-overlay")
], DialogOverlay);
var __defProp$1 = Object.defineProperty;
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
var __decorateClass$1 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$1(target, key, result);
  return result;
};
let DialogPortal = class extends LitElement {
  constructor() {
    super(...arguments);
    this.env = "prod";
    this.apiKey = "";
    this.disableTracking = false;
    this.trackingSource = "embedded_player";
    this.preload = "none";
    this.disableAutoplay = false;
    this.aspectRatio = 0;
    this._mediaPlayerRef = createRef();
    this.open = false;
    this._handleToggle = ({ detail }) => {
      var _a, _b, _c;
      if (this.id === detail) {
        this.open = !this.open;
        if (this.open) {
          if (!this.disableAutoplay && ((_a = this._mediaPlayerRef) == null ? void 0 : _a.value)) {
            this._mediaPlayerRef.value.muted = false;
            this._mediaPlayerRef.value.play();
          }
        } else {
          (_c = (_b = this._mediaPlayerRef) == null ? void 0 : _b.value) == null ? void 0 : _c.pause();
        }
      }
    };
    this._handleClose = () => {
      var _a, _b;
      this.open = false;
      (_b = (_a = this._mediaPlayerRef) == null ? void 0 : _a.value) == null ? void 0 : _b.pause();
    };
    this._handleDocumentKeyUp = (e) => {
      if (e.key === "Escape") {
        this._handleClose();
      }
    };
  }
  connectedCallback() {
    super.connectedCallback();
    document.addEventListener("dialogembed:click", this._handleToggle);
    document.addEventListener("keyup", this._handleDocumentKeyUp);
    document.addEventListener("close:click", this._handleClose);
    document.addEventListener("overlay:click", this._handleClose);
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    document.removeEventListener("dialogembed:click", this._handleToggle);
    document.removeEventListener("keyup", this._handleDocumentKeyUp);
    document.removeEventListener("close:click", this._handleClose);
    document.removeEventListener("overlay:click", this._handleClose);
  }
  createRenderRoot() {
    const newNode = document.createElement("div");
    document.body.appendChild(newNode);
    return newNode;
  }
  render() {
    return html`
      <vouch-embed-dialog-overlay ?open=${this.open} aspectRatio=${this.aspectRatio}>
        <vouch-embed-player
          ${ref(this._mediaPlayerRef)}
          style=${styleMap({
      maxWidth: "100%",
      maxHeight: "100%"
    })}
          ?autoplay=${false}
          vouchId=${ifDefined(this.vouchId)}
          templateId=${ifDefined(this.templateId)}
          .questions=${this.questions}
          .controls=${this.controls}
          env=${ifDefined(this.env)}
          apiKey=${ifDefined(this.apiKey)}
          ?disableTracking=${this.disableTracking}
          trackingSource=${ifDefined(this.trackingSource)}
          preload=${ifDefined(this.preload)}
          aspectRatio=${this.aspectRatio}
        ></vouch-embed-player>
      </vouch-embed-dialog-overlay>
    `;
  }
};
__decorateClass$1([
  property({ type: String })
], DialogPortal.prototype, "vouchId", 2);
__decorateClass$1([
  property({ type: String })
], DialogPortal.prototype, "templateId", 2);
__decorateClass$1([
  property({ type: Array })
], DialogPortal.prototype, "questions", 2);
__decorateClass$1([
  property({ type: String })
], DialogPortal.prototype, "env", 2);
__decorateClass$1([
  property({ type: String })
], DialogPortal.prototype, "apiKey", 2);
__decorateClass$1([
  property({ type: Boolean })
], DialogPortal.prototype, "disableTracking", 2);
__decorateClass$1([
  property({ type: String })
], DialogPortal.prototype, "trackingSource", 2);
__decorateClass$1([
  property({ type: Array })
], DialogPortal.prototype, "controls", 2);
__decorateClass$1([
  property({ type: String })
], DialogPortal.prototype, "preload", 2);
__decorateClass$1([
  property({ type: Boolean })
], DialogPortal.prototype, "disableAutoplay", 2);
__decorateClass$1([
  property({ type: Number })
], DialogPortal.prototype, "aspectRatio", 2);
__decorateClass$1([
  state()
], DialogPortal.prototype, "open", 2);
DialogPortal = __decorateClass$1([
  customElement("vouch-embed-dialog-portal")
], DialogPortal);
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
let DialogEmbed = class extends LitElement {
  constructor() {
    super(...arguments);
    this.env = "prod";
    this.apiKey = "";
    this.disableTracking = false;
    this.trackingSource = "embedded_player";
    this.preload = "none";
    this.disableAutoplay = false;
    this.aspectRatio = 0;
    this._id = v4();
    this._handleRootClick = () => {
      this.dispatchEvent(new CustomEvent("dialogembed:click", { detail: this._id, bubbles: true, composed: true }));
    };
  }
  connectedCallback() {
    super.connectedCallback();
    this.addEventListener("click", this._handleRootClick);
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeEventListener("click", this._handleRootClick);
  }
  render() {
    return html`
      <slot>
        <vmp-button size="large">Play</vmp-button>
      </slot>
      <vouch-embed-dialog-portal
        id=${this._id}
        ?autoplay=${false}
        vouchId=${ifDefined(this.vouchId)}
        templateId=${ifDefined(this.templateId)}
        .questions=${this.questions}
        .controls=${this.controls}
        env=${ifDefined(this.env)}
        apiKey=${ifDefined(this.apiKey)}
        ?disableTracking=${this.disableTracking}
        trackingSource=${ifDefined(this.trackingSource)}
        preload=${ifDefined(this.preload)}
        aspectRatio=${this.aspectRatio}
      ></vouch-embed-dialog-portal>
    `;
  }
};
DialogEmbed.styles = [
  css`
      :host {
        --vu-button-padding: 10px 20px;
        --vu-button-background: #287179;
        --vu-button-background-hover: #4faab2;

        display: flex;
        width: fit-content;
        height: fit-content;
      }
    `
];
__decorateClass([
  property({ type: String })
], DialogEmbed.prototype, "vouchId", 2);
__decorateClass([
  property({ type: String })
], DialogEmbed.prototype, "templateId", 2);
__decorateClass([
  property({ type: Array })
], DialogEmbed.prototype, "questions", 2);
__decorateClass([
  property({ type: String })
], DialogEmbed.prototype, "env", 2);
__decorateClass([
  property({ type: String })
], DialogEmbed.prototype, "apiKey", 2);
__decorateClass([
  property({ type: Boolean })
], DialogEmbed.prototype, "disableTracking", 2);
__decorateClass([
  property({ type: String })
], DialogEmbed.prototype, "trackingSource", 2);
__decorateClass([
  property({ type: Array })
], DialogEmbed.prototype, "controls", 2);
__decorateClass([
  property({ type: String })
], DialogEmbed.prototype, "preload", 2);
__decorateClass([
  property({ type: Boolean })
], DialogEmbed.prototype, "disableAutoplay", 2);
__decorateClass([
  property({ type: Number })
], DialogEmbed.prototype, "aspectRatio", 2);
DialogEmbed = __decorateClass([
  customElement("vouch-embed-dialog")
], DialogEmbed);
export {
  DialogEmbed,
  PlayerEmbed
};
//# sourceMappingURL=embeds.js.map
