'use strict';

const domContextHooks_module = require('./dom-context-hooks.module-e7b6727c.js');
const index_module = require('./index.module-f8c8495f.js');

const TAX_FORM_UPDATED_EVENT_KEY = "sqm:tax-form-updated";

var toArray = function toArray(a) {
  var ret = Array(a.length);
  for (var i = 0; i < a.length; ++i) {
    ret[i] = a[i];
  }
  return ret;
};

var arrayFind = function arrayFind(array, search) {
  return array.filter(function (a) {
    return a === search;
  })[0];
};

var asArray = function asArray(a) {
  return Array.isArray(a) ? a : [a];
};

var tabSort = function tabSort(a, b) {
  var tabDiff = a.tabIndex - b.tabIndex;
  var indexDiff = a.index - b.index;

  if (tabDiff) {
    if (!a.tabIndex) return 1;
    if (!b.tabIndex) return -1;
  }

  return tabDiff || indexDiff;
};

var orderByTabIndex = function orderByTabIndex(nodes, filterNegative, keepGuards) {
  return toArray(nodes).map(function (node, index) {
    return {
      node: node,
      index: index,
      tabIndex: keepGuards && node.tabIndex === -1 ? (node.dataset || {}).focusGuard ? 0 : -1 : node.tabIndex
    };
  }).filter(function (data) {
    return !filterNegative || data.tabIndex >= 0;
  }).sort(tabSort);
};

const tabbables = ['button:enabled:not([readonly])', 'select:enabled:not([readonly])', 'textarea:enabled:not([readonly])', 'input:enabled:not([readonly])', 'a[href]', 'area[href]', 'iframe', 'object', 'embed', '[tabindex]', '[contenteditable]', '[autofocus]'];

var FOCUS_GROUP = 'data-focus-lock';
var FOCUS_DISABLED = 'data-focus-lock-disabled';
var FOCUS_ALLOW = 'data-no-focus-lock';
var FOCUS_AUTO = 'data-autofocus-inside';

var queryTabbables = tabbables.join(',');
var queryGuardTabbables = queryTabbables + ', [data-focus-guard]';

var getFocusables = function getFocusables(parents, withGuards) {
  return parents.reduce(function (acc, parent) {
    return acc.concat(
    // add all tabbables inside
    toArray(parent.querySelectorAll(withGuards ? queryGuardTabbables : queryTabbables)),
    // add if node is tabble itself
    parent.parentNode ? toArray(parent.parentNode.querySelectorAll(tabbables.join(','))).filter(function (node) {
      return node === parent;
    }) : []);
  }, []);
};

var getParentAutofocusables = function getParentAutofocusables(parent) {
  var parentFocus = parent.querySelectorAll('[' + FOCUS_AUTO + ']');
  return toArray(parentFocus).map(function (node) {
    return getFocusables([node]);
  }).reduce(function (acc, nodes) {
    return acc.concat(nodes);
  }, []);
};

var isElementHidden = function isElementHidden(computedStyle) {
  if (!computedStyle || !computedStyle.getPropertyValue) {
    return false;
  }
  return computedStyle.getPropertyValue('display') === 'none' || computedStyle.getPropertyValue('visibility') === 'hidden';
};

var isVisible = function isVisible(node) {
  return !node || node === document || node.nodeType === Node.DOCUMENT_NODE || !isElementHidden(window.getComputedStyle(node, null)) && isVisible(node.parentNode);
};

var notHiddenInput = function notHiddenInput(node) {
  return !((node.tagName === 'INPUT' || node.tagName === 'BUTTON') && (node.type === 'hidden' || node.disabled));
};

var getParents = function getParents(node) {
  var parents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  parents.push(node);
  if (node.parentNode) {
    getParents(node.parentNode, parents);
  }
  return parents;
};

var getCommonParent = function getCommonParent(nodea, nodeb) {
  var parentsA = getParents(nodea);
  var parentsB = getParents(nodeb);

  for (var i = 0; i < parentsA.length; i += 1) {
    var currentParent = parentsA[i];
    if (parentsB.indexOf(currentParent) >= 0) {
      return currentParent;
    }
  }
  return false;
};

var filterFocusable = function filterFocusable(nodes) {
  return toArray(nodes).filter(function (node) {
    return isVisible(node);
  }).filter(function (node) {
    return notHiddenInput(node);
  });
};

var getTabbableNodes = function getTabbableNodes(topNodes, withGuards) {
  return orderByTabIndex(filterFocusable(getFocusables(topNodes, withGuards)), true, withGuards);
};

var getAllTabbableNodes = function getAllTabbableNodes(topNodes) {
  return orderByTabIndex(filterFocusable(getFocusables(topNodes)), false);
};

var parentAutofocusables = function parentAutofocusables(topNode) {
  return filterFocusable(getParentAutofocusables(topNode));
};

var isRadio = function isRadio(node) {
  return node.tagName === 'INPUT' && node.type === 'radio';
};

var findSelectedRadio = function findSelectedRadio(node, nodes) {
  return nodes.filter(isRadio).filter(function (el) {
    return el.name === node.name;
  }).filter(function (el) {
    return el.checked;
  })[0] || node;
};

var pickFirstFocus = function pickFirstFocus(nodes) {
  if (nodes[0] && nodes.length > 1) {
    if (isRadio(nodes[0]) && nodes[0].name) {
      return findSelectedRadio(nodes[0], nodes);
    }
  }
  return nodes[0];
};

var pickFocusable = function pickFocusable(nodes, index) {
  if (nodes.length > 1) {
    if (isRadio(nodes[index]) && nodes[index].name) {
      return nodes.indexOf(findSelectedRadio(nodes[index], nodes));
    }
  }
  return index;
};

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var filterNested = function filterNested(nodes) {
  var l = nodes.length;
  for (var i = 0; i < l; i += 1) {
    var _loop = function _loop(j) {
      if (i !== j) {
        if (nodes[i].contains(nodes[j])) {
          return {
            v: filterNested(nodes.filter(function (x) {
              return x !== nodes[j];
            }))
          };
        }
      }
    };

    for (var j = 0; j < l; j += 1) {
      var _ret = _loop(j);

      if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
    }
  }
  return nodes;
};

var getTopParent = function getTopParent(node) {
  return node.parentNode ? getTopParent(node.parentNode) : node;
};

var getAllAffectedNodes = function getAllAffectedNodes(node) {
  var nodes = asArray(node);
  return nodes.filter(Boolean).reduce(function (acc, currentNode) {
    var group = currentNode.getAttribute(FOCUS_GROUP);
    acc.push.apply(acc, group ? filterNested(toArray(getTopParent(currentNode).querySelectorAll('[' + FOCUS_GROUP + '="' + group + '"]:not([' + FOCUS_DISABLED + '="disabled"])'))) : [currentNode]);
    return acc;
  }, []);
};

var findAutoFocused = function findAutoFocused(autoFocusables) {
  return function (node) {
    return !!node.autofocus || node.dataset && !!node.dataset.autofocus || autoFocusables.indexOf(node) >= 0;
  };
};

var isGuard = function isGuard(node) {
  return node && node.dataset && node.dataset.focusGuard;
};
var notAGuard = function notAGuard(node) {
  return !isGuard(node);
};

var newFocus = function newFocus(innerNodes, outerNodes, activeElement, lastNode, autoFocused) {
  var cnt = innerNodes.length;
  var firstFocus = innerNodes[0];
  var lastFocus = innerNodes[cnt - 1];
  var isOnGuard = isGuard(activeElement);

  // focus is inside
  if (innerNodes.indexOf(activeElement) >= 0) {
    return undefined;
  }

  var activeIndex = outerNodes.indexOf(activeElement);
  var lastIndex = outerNodes.indexOf(lastNode || activeIndex);
  var lastNodeInside = innerNodes.indexOf(lastNode);
  var indexDiff = activeIndex - lastIndex;
  var firstNodeIndex = outerNodes.indexOf(firstFocus);
  var lastNodeIndex = outerNodes.indexOf(lastFocus);

  var returnFirstNode = pickFocusable(innerNodes, 0);
  var returnLastNode = pickFocusable(innerNodes, cnt - 1);

  // new focus
  if (activeIndex === -1 || lastNodeInside === -1) {
    return innerNodes.indexOf(autoFocused && autoFocused.length ? pickFirstFocus(autoFocused) : pickFirstFocus(innerNodes));
  }
  // old focus
  if (!indexDiff && lastNodeInside >= 0) {
    return lastNodeInside;
  }
  // first element
  if (activeIndex <= firstNodeIndex && isOnGuard && Math.abs(indexDiff) > 1) {
    return returnLastNode;
  }
  // last element
  if (activeIndex >= firstNodeIndex && isOnGuard && Math.abs(indexDiff) > 1) {
    return returnFirstNode;
  }
  // jump out, but not on the guard
  if (indexDiff && Math.abs(indexDiff) > 1) {
    return lastNodeInside;
  }
  // focus above lock
  if (activeIndex <= firstNodeIndex) {
    return returnLastNode;
  }
  // focus below lock
  if (activeIndex > lastNodeIndex) {
    return returnFirstNode;
  }
  // index is inside tab order, but outside Lock
  if (indexDiff) {
    if (Math.abs(indexDiff) > 1) {
      return lastNodeInside;
    }
    return (cnt + lastNodeInside + indexDiff) % cnt;
  }
  // do nothing
  return undefined;
};

var getTopCommonParent = function getTopCommonParent(baseActiveElement, leftEntry, rightEntries) {
  var activeElements = asArray(baseActiveElement);
  var leftEntries = asArray(leftEntry);
  var activeElement = activeElements[0];
  var topCommon = null;
  leftEntries.filter(Boolean).forEach(function (entry) {
    topCommon = getCommonParent(topCommon || entry, entry) || topCommon;
    rightEntries.filter(Boolean).forEach(function (subEntry) {
      var common = getCommonParent(activeElement, subEntry);
      if (common) {
        if (!topCommon || common.contains(topCommon)) {
          topCommon = common;
        } else {
          topCommon = getCommonParent(common, topCommon);
        }
      }
    });
  });
  return topCommon;
};

var allParentAutofocusables = function allParentAutofocusables(entries) {
  return entries.reduce(function (acc, node) {
    return acc.concat(parentAutofocusables(node));
  }, []);
};

var reorderNodes = function reorderNodes(srcNodes, dstNodes) {
  var remap = new Map();
  // no Set(dstNodes) for IE11 :(
  dstNodes.forEach(function (entity) {
    return remap.set(entity.node, entity);
  });
  // remap to dstNodes
  return srcNodes.map(function (node) {
    return remap.get(node);
  }).filter(Boolean);
};

var getFocusMerge = function getFocusMerge(topNode, lastNode) {
  var activeElement = document && document.activeElement;
  var entries = getAllAffectedNodes(topNode).filter(notAGuard);

  var commonParent = getTopCommonParent(activeElement || topNode, topNode, entries);

  var innerElements = getTabbableNodes(entries).filter(function (_ref4) {
    var node = _ref4.node;
    return notAGuard(node);
  });

  if (!innerElements[0]) {
    innerElements = getAllTabbableNodes(entries).filter(function (_ref5) {
      var node = _ref5.node;
      return notAGuard(node);
    });
    if (!innerElements[0]) {
      return undefined;
    }
  }

  var outerNodes = getTabbableNodes([commonParent]).map(function (_ref6) {
    var node = _ref6.node;
    return node;
  });
  var orderedInnerElements = reorderNodes(outerNodes, innerElements);
  var innerNodes = orderedInnerElements.map(function (_ref7) {
    var node = _ref7.node;
    return node;
  });

  var newId = newFocus(innerNodes, outerNodes, activeElement, lastNode, innerNodes.filter(findAutoFocused(allParentAutofocusables(entries))));

  if (newId === undefined) {
    return newId;
  }
  return orderedInnerElements[newId];
};

var focusInFrame = function focusInFrame(frame) {
  return frame === document.activeElement;
};

var focusInsideIframe = function focusInsideIframe(topNode) {
  return !!arrayFind(toArray(topNode.querySelectorAll('iframe')), focusInFrame);
};

var focusInside = function focusInside(topNode) {
  var activeElement = document && document.activeElement;

  if (!activeElement || activeElement.dataset && activeElement.dataset.focusGuard) {
    return false;
  }
  return getAllAffectedNodes(topNode).reduce(function (result, node) {
    return result || node.contains(activeElement) || focusInsideIframe(node);
  }, false);
};

var focusIsHidden = function focusIsHidden() {
  return document && toArray(document.querySelectorAll('[' + FOCUS_ALLOW + ']')).some(function (node) {
    return node.contains(document.activeElement);
  });
};

var focusOn = function focusOn(target) {
  target.focus();
  if (target.contentWindow) {
    target.contentWindow.focus();
  }
};

var guardCount = 0;
var lockDisabled = false;

const setFocus = (function (topNode, lastNode) {
  var focusable = getFocusMerge(topNode, lastNode);

  if (lockDisabled) {
    return;
  }

  if (focusable) {
    if (guardCount > 2) {
      // eslint-disable-next-line no-console
      console.error('FocusLock: focus-fighting detected. Only one focus management system could be active. ' + 'See https://github.com/theKashey/focus-lock/#focus-fighting');
      lockDisabled = true;
      setTimeout(function () {
        lockDisabled = false;
      }, 1);
      return;
    }
    guardCount++;
    focusOn(focusable.node);
    guardCount--;
  }
});

var lastActiveTrap = 0;
var lastActiveFocus = null;

var focusOnBody = function focusOnBody() {
  return document && document.activeElement === document.body;
};

var isFreeFocus = function isFreeFocus() {
  return focusOnBody() || focusIsHidden();
};

var activateTrap = function activateTrap() {
  var result = false;

  if (lastActiveTrap) {
    var observed = lastActiveTrap;

    if (!isFreeFocus()) {
      if (observed && !focusInside(observed)) {
        result = setFocus(observed, lastActiveFocus);
      }

      lastActiveFocus = document.activeElement;
    }
  }

  return result;
};

var reducePropsToState = function reducePropsToState(propsList) {
  return propsList.filter(function (node) {
    return node;
  }).slice(-1)[0];
};

var handleStateChangeOnClient = function handleStateChangeOnClient(trap) {
  lastActiveTrap = trap;

  if (trap) {
    activateTrap();
  }
};

var instances = [];

var emitChange = function emitChange(event) {
  if (handleStateChangeOnClient(reducePropsToState(instances))) {
    event && event.preventDefault();
    return true;
  }

  return false;
};

var attachHandler = function attachHandler() {
  document.addEventListener('focusin', emitChange);
};

var detachHandler = function detachHandler() {
  document.removeEventListener('focusin', emitChange);
};

var focusLock = {
  on: function on(domNode) {
    if (instances.length === 0) {
      attachHandler();
    }

    if (instances.indexOf(domNode) < 0) {
      instances.push(domNode);
      emitChange();
    }
  },
  off: function off(domNode) {
    instances = instances.filter(function (node) {
      return node !== domNode;
    });
    emitChange();

    if (instances.length === 0) {
      detachHandler();
    }
  }
};

/**
 * tua-body-scroll-lock v1.2.1
 * (c) 2021 Evinma, BuptStEve
 * @license MIT
 */

var isServer = function isServer() {
  return typeof window === 'undefined';
};
var detectOS = function detectOS(ua) {
  ua = ua || navigator.userAgent;
  var ipad = /(iPad).*OS\s([\d_]+)/.test(ua);
  var iphone = !ipad && /(iPhone\sOS)\s([\d_]+)/.test(ua);
  var android = /(Android);?[\s/]+([\d.]+)?/.test(ua);
  var ios = iphone || ipad;
  return {
    ios: ios,
    android: android
  };
};
function getEventListenerOptions(options) {
  /* istanbul ignore if */
  if (isServer()) return false;

  if (!options) {
    throw new Error('options must be provided');
  }

  var isSupportOptions = false;
  var listenerOptions = {
    get passive() {
      isSupportOptions = true;
      return;
    }

  };
  /* istanbul ignore next */

  var noop = function noop() {};

  var testEvent = '__TUA_BSL_TEST_PASSIVE__';
  window.addEventListener(testEvent, noop, listenerOptions);
  window.removeEventListener(testEvent, noop, listenerOptions);
  var capture = options.capture;
  /* istanbul ignore next */

  return isSupportOptions ? options : typeof capture !== 'undefined' ? capture : false;
}

var lockedNum = 0;
var initialClientY = 0;
var initialClientX = 0;
var unLockCallback = null;
var documentListenerAdded = false;
var lockedElements = [];
var eventListenerOptions = getEventListenerOptions({
  passive: false
});
var supportsNativeSmoothScroll = !isServer() && 'scrollBehavior' in document.documentElement.style;

var setOverflowHiddenPc = function setOverflowHiddenPc() {
  var $body = document.body;
  var bodyStyle = Object.assign({}, $body.style);
  var scrollBarWidth = window.innerWidth - $body.clientWidth;
  $body.style.overflow = 'hidden';
  $body.style.boxSizing = 'border-box';
  $body.style.paddingRight = "".concat(scrollBarWidth, "px");
  return function () {
    ['overflow', 'boxSizing', 'paddingRight'].forEach(function (x) {
      $body.style[x] = bodyStyle[x] || '';
    });
  };
};

var setOverflowHiddenMobile = function setOverflowHiddenMobile() {
  var $html = document.documentElement;
  var $body = document.body;
  var scrollTop = $html.scrollTop || $body.scrollTop;
  var htmlStyle = Object.assign({}, $html.style);
  var bodyStyle = Object.assign({}, $body.style);
  $html.style.height = '100%';
  $html.style.overflow = 'hidden';
  $body.style.top = "-".concat(scrollTop, "px");
  $body.style.width = '100%';
  $body.style.height = 'auto';
  $body.style.position = 'fixed';
  $body.style.overflow = 'hidden';
  return function () {
    $html.style.height = htmlStyle.height || '';
    $html.style.overflow = htmlStyle.overflow || '';
    ['top', 'width', 'height', 'overflow', 'position'].forEach(function (x) {
      $body.style[x] = bodyStyle[x] || '';
    });
    supportsNativeSmoothScroll ? window.scrollTo({
      top: scrollTop,
      // @ts-ignore
      behavior: 'instant'
    }) : window.scrollTo(0, scrollTop);
  };
};

var preventDefault = function preventDefault(event) {
  if (!event.cancelable) return;
  event.preventDefault();
};

var handleScroll = function handleScroll(event, targetElement) {
  if (targetElement) {
    var scrollTop = targetElement.scrollTop,
        scrollLeft = targetElement.scrollLeft,
        scrollWidth = targetElement.scrollWidth,
        scrollHeight = targetElement.scrollHeight,
        clientWidth = targetElement.clientWidth,
        clientHeight = targetElement.clientHeight;
    var clientX = event.targetTouches[0].clientX - initialClientX;
    var clientY = event.targetTouches[0].clientY - initialClientY;
    var isVertical = Math.abs(clientY) > Math.abs(clientX);
    var isOnTop = clientY > 0 && scrollTop === 0;
    var isOnLeft = clientX > 0 && scrollLeft === 0;
    var isOnRight = clientX < 0 && scrollLeft + clientWidth + 1 >= scrollWidth;
    var isOnBottom = clientY < 0 && scrollTop + clientHeight + 1 >= scrollHeight;

    if (isVertical && (isOnTop || isOnBottom) || !isVertical && (isOnLeft || isOnRight)) {
      return preventDefault(event);
    }
  }

  event.stopPropagation();
  return true;
};

var lock = function lock(targetElement) {
  if (isServer()) return;

  if (detectOS().ios) {
    // iOS
    if (targetElement) {
      var elementArray = Array.isArray(targetElement) ? targetElement : [targetElement];
      elementArray.forEach(function (element) {
        if (element && lockedElements.indexOf(element) === -1) {
          element.ontouchstart = function (event) {
            initialClientY = event.targetTouches[0].clientY;
            initialClientX = event.targetTouches[0].clientX;
          };

          element.ontouchmove = function (event) {
            if (event.targetTouches.length !== 1) return;
            handleScroll(event, element);
          };

          lockedElements.push(element);
        }
      });
    }

    if (!documentListenerAdded) {
      document.addEventListener('touchmove', preventDefault, eventListenerOptions);
      documentListenerAdded = true;
    }
  } else if (lockedNum <= 0) {
    unLockCallback = detectOS().android ? setOverflowHiddenMobile() : setOverflowHiddenPc();
  }

  lockedNum += 1;
};

var unlock = function unlock(targetElement) {
  if (isServer()) return;
  lockedNum -= 1;
  if (lockedNum > 0) return;

  if (!detectOS().ios && typeof unLockCallback === 'function') {
    unLockCallback();
    return;
  } // iOS


  if (targetElement) {
    var elementArray = Array.isArray(targetElement) ? targetElement : [targetElement];
    elementArray.forEach(function (element) {
      var index = lockedElements.indexOf(element);

      if (index !== -1) {
        element.ontouchmove = null;
        element.ontouchstart = null;
        lockedElements.splice(index, 1);
      }
    });
  }

  if (documentListenerAdded) {
    document.removeEventListener('touchmove', preventDefault, eventListenerOptions);
    documentListenerAdded = false;
  }
};

const wrapperStyles = `
  position: fixed !important;
  top: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  left: 0 !important;
  z-index: 9999999;
  display: block !important;
  width: 100vw;
  height: 100%;
  margin: 0 !important;
  padding: 0 !important;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  background: rgba(0, 0, 0, 0.6);
`;
const iframeStyles = `
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  left: 0 !important;
  width: 100vw;
  height: 100%;
  margin: 0 !important;
  padding: 0 !important;
  background: none;
  border: none
`;
const iframeEmbeddedStyles = `
  position: static;
  width: 100%;
  height: 100%;
`;

const createEmbeddedIFrame = function (frame) {
  let embeddedOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  let isVeriffIframeMobile = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  const {
    rootElementID
  } = embeddedOptions;
  if (isVeriffIframeMobile) {
    frame.style.cssText = iframeStyles;
    const wrapper = document.createElement('div');
    wrapper.style.cssText = wrapperStyles;
    wrapper.appendChild(frame);
    document.body.appendChild(wrapper);
    focusLock.on(frame);
    lock(frame);
  } else {
    if (!rootElementID) {
      throw new Error('rootElementID must be specified in embedded mode');
    }
    if (!document.getElementById(rootElementID)) {
      throw new Error('rootElementID must point to an existing DOM element');
    }
    frame.style.cssText = iframeEmbeddedStyles;
    document.getElementById(rootElementID).appendChild(frame);
  }
};

let IFRAME_MESSAGES = function (IFRAME_MESSAGES) {
  IFRAME_MESSAGES["VERIFF_HANDSHAKE"] = "VERIFF_HANDSHAKE";
  IFRAME_MESSAGES["VERIFF_RENDER"] = "VERIFF_RENDER";
  IFRAME_MESSAGES["VERIFF_STARTED"] = "VERIFF_STARTED";
  IFRAME_MESSAGES["VERIFF_SUBMITTED"] = "VERIFF_SUBMITTED";
  IFRAME_MESSAGES["VERIFF_FINISHED"] = "VERIFF_FINISHED";
  IFRAME_MESSAGES["VERIFF_CANCELED"] = "VERIFF_CANCELED";
  IFRAME_MESSAGES["VERIFF_FORCE_RELOAD"] = "VERIFF_FORCE_RELOAD";
  IFRAME_MESSAGES["VERIFF_RELOAD_REQUEST"] = "VERIFF_RELOAD_REQUEST";
  return IFRAME_MESSAGES;
}({});

let MESSAGES = function (MESSAGES) {
  MESSAGES["STARTED"] = "STARTED";
  MESSAGES["SUBMITTED"] = "SUBMITTED";
  MESSAGES["FINISHED"] = "FINISHED";
  MESSAGES["CANCELED"] = "CANCELED";
  MESSAGES["RELOAD_REQUEST"] = "RELOAD";
  return MESSAGES;
}({});

const IFRAME_ID = 'veriffFrame';
function handleHandshakeEvent(frame, payload) {
  frame.contentWindow?.postMessage({
    name: IFRAME_MESSAGES.VERIFF_RENDER,
    payload
  }, '*');
}
function checkIfIsVeriffIframeMobile(embedded) {
  if (embedded) {
    try {
      const mediaQuery = matchMedia('(max-width: 767px), (hover: none)');
      return mediaQuery.matches;
    } catch (e) {
      console.error('Error while checking if iframe is mobile', e);
      return false;
    }
  }
  return false;
}
function appendParamToUrl(url, name, value) {
  if (value) {
    const newUrl = new URL(url);
    const params = newUrl.searchParams;
    params.set(name, value);
    newUrl.search = params.toString();
    return newUrl.toString();
  }
  return url;
}
function createWrapper() {
  const wrapper = document.createElement('div');
  wrapper.style.cssText = wrapperStyles;
  return wrapper;
}
function createIframe(url, embedded, embeddedOptions, isVeriffIframeMobile) {
  const frame = document.createElement('iframe');
  frame.src = url;
  frame.allow = 'autoplay; camera; microphone; fullscreen; accelerometer; magnetometer; gyroscope; picture-in-picture;';
  frame.id = IFRAME_ID;
  if (embedded) {
    createEmbeddedIFrame(frame, embeddedOptions, isVeriffIframeMobile);
  } else {
    frame.style.cssText = iframeStyles;
    const wrapper = createWrapper();
    wrapper.appendChild(frame);
    document.body.appendChild(wrapper);
    focusLock.on(frame);
    lock(frame);
  }
  return frame;
}
function createVeriffFrame(_ref) {
  let {
    url,
    lang,
    onEvent = () => {
      return;
    },
    embedded = false,
    embeddedOptions,
    onReload
  } = _ref;
  if (!url) {
    throw new Error('URL is not provided. Please provide a valid Veriff session url.');
  }
  const isVeriffIframeMobile = checkIfIsVeriffIframeMobile(embedded);
  function closeIframe() {
    const frame = document.getElementById(IFRAME_ID);
    if (frame && frame.parentNode) {
      focusLock.off(frame);
      unlock(frame);
      let wrapper = frame.parentNode.parentNode;
      let child = frame.parentNode;
      if (embedded && !isVeriffIframeMobile) {
        wrapper = frame.parentNode;
        child = frame;
      }
      if (wrapper) wrapper.removeChild(child);
    } else {
      unlock();
    }
    window.removeEventListener('message', handleMessage);
  }
  function handleMessage(event) {
    const frame = document.getElementById(IFRAME_ID);
    const version = "2.3.1";
    if (event.data === IFRAME_MESSAGES.VERIFF_HANDSHAKE) {
      handleHandshakeEvent(frame, {
        version,
        isReloadHandled: typeof onReload === 'function',
        isVeriffIframeMobile,
        embeddedConfigured: embedded,
        embedded: isVeriffIframeMobile ? false : embedded
      });
    }
    if (event.data === IFRAME_MESSAGES.VERIFF_STARTED) {
      onEvent(MESSAGES.STARTED);
    }
    if (event.data === IFRAME_MESSAGES.VERIFF_CANCELED) {
      closeIframe();
      onEvent(MESSAGES.CANCELED);
    }
    if (event.data === IFRAME_MESSAGES.VERIFF_SUBMITTED) {
      onEvent(MESSAGES.SUBMITTED);
    }
    if (event.data === IFRAME_MESSAGES.VERIFF_FINISHED) {
      closeIframe();
      onEvent(MESSAGES.FINISHED);
    }
    if (event.data === IFRAME_MESSAGES.VERIFF_FORCE_RELOAD) {
      window.location.reload();
    }
    if (event.data === IFRAME_MESSAGES.VERIFF_RELOAD_REQUEST) {
      if (typeof onReload === 'function') {
        onReload();
      }
      onEvent(MESSAGES.RELOAD_REQUEST);
    }
  }
  const newUrl = lang && lang.length > 0 ? appendParamToUrl(url, 'lang', lang) : url;
  createIframe(newUrl, embedded, embeddedOptions, isVeriffIframeMobile);
  window.addEventListener('message', handleMessage);
  return {
    close: closeIframe
  };
}

const CREATE_IMPACT_VERIFICATION_SESSION = index_module.dist.gql `
  mutation createImpactVerificationSession($user: UserIdInput!) {
    createImpactPublisherIdentityVerificationSession(user: $user) {
      sessionUrl
    }
  }
`;
const REFRESH_USER_STATUS = index_module.dist.gql `
  mutation refreshImpactPublisherFinanceStatus($user: UserIdInput!) {
    refreshImpactPublisherFinanceStatus(user: $user) {
      id
    }
  }
`;
const VERIFF_COMPLETE_EVENT_KEY = "sqm:veriff-updated";
function useVeriffApp() {
  const { id, accountId } = index_module.J();
  const [createImpactVerificationSessionMutation, { loading, errors }] = index_module.$e(CREATE_IMPACT_VERIFICATION_SESSION);
  const [refreshImpactPublisherFinanceStatus, { loading: refreshLoading, errors: refreshErrors },] = index_module.$e(REFRESH_USER_STATUS);
  const refresh = async () => {
    try {
      const res = await refreshImpactPublisherFinanceStatus({
        user: { id, accountId },
      });
      if (!res || res.message)
        throw new Error();
      window.dispatchEvent(new Event(VERIFF_COMPLETE_EVENT_KEY));
    }
    catch (e) {
      console.error("Failed to initialise Veriff:", e);
    }
  };
  const render = async () => {
    try {
      const res = await createImpactVerificationSessionMutation({
        user: { id, accountId },
      });
      if (!res || res.message)
        throw new Error();
      const sessionUrl = res.createImpactPublisherIdentityVerificationSession.sessionUrl;
      createVeriffFrame({
        url: sessionUrl,
        onEvent: (msg) => {
          switch (msg) {
            case MESSAGES.FINISHED:
            case MESSAGES.CANCELED:
              refresh();
          }
        },
      });
    }
    catch (e) {
      console.error("Failed to initialise Veriff:", e);
    }
  };
  return {
    render,
    loading: loading || refreshLoading,
    errors: errors || refreshErrors,
  };
}

const GET_USER_STATUS = index_module.dist.gql `
  query getUserStatus {
    user: viewer {
      ... on User {
        id
        impactConnection {
          connected
          publisher {
            id
            payoutsAccount {
              hold
              holdReasons
            }
          }
        }
        rewards(limit: 1000) {
          data {
            statuses
            partnerFundsTransfer {
              id
              status
              dateScheduled
              dateCreated
              dateTransferred
            }
          }
        }
      }
    }
  }
`;
const GET_TAX_SETTING = index_module.dist.gql `
  query getTenantSettings {
    tenantSettings {
      enforceUsTaxCompliance
    }
  }
`;
function getStatus(data) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
  const account = (_b = (_a = data.user.impactConnection) === null || _a === void 0 ? void 0 : _a.publisher) === null || _b === void 0 ? void 0 : _b.payoutsAccount;
  const hasTransferredReward = (_e = (_d = (_c = data === null || data === void 0 ? void 0 : data.user) === null || _c === void 0 ? void 0 : _c.rewards) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.find((reward) => {
    var _a;
    return reward.statuses.includes("REDEEMED") &&
      ((_a = reward.partnerFundsTransfer) === null || _a === void 0 ? void 0 : _a.status) === "TRANSFERRED";
  });
  if (!((_g = (_f = data.user) === null || _f === void 0 ? void 0 : _f.impactConnection) === null || _g === void 0 ? void 0 : _g.connected) || !account)
    return "INFORMATION_REQUIRED";
  const currentTaxDocument = (_j = (_h = data.user.impactConnection) === null || _h === void 0 ? void 0 : _h.publisher) === null || _j === void 0 ? void 0 : _j.currentTaxDocument;
  if (((_k = account.holdReasons) === null || _k === void 0 ? void 0 : _k.includes("NO_W9_DOCUMENT")) && !currentTaxDocument)
    return "OVER_W9_THRESHOLD";
  if ((_l = account.holdReasons) === null || _l === void 0 ? void 0 : _l.includes("IDV_CHECK_REQUIRED"))
    return "VERIFICATION:REQUIRED";
  if ((_m = account.holdReasons) === null || _m === void 0 ? void 0 : _m.includes("IDV_CHECK_REQUIRED_INTERNAL"))
    return "VERIFICATION:INTERNAL";
  if ((_o = account.holdReasons) === null || _o === void 0 ? void 0 : _o.includes("IDV_CHECK_REVIEW_INTERNAL"))
    return "VERIFICATION:REVIEW";
  if ((_p = account.holdReasons) === null || _p === void 0 ? void 0 : _p.includes("IDV_CHECK_FAILED_INTERNAL"))
    return "VERIFICATION:FAILED";
  // only show banner for NEW_PAYEE_REVIEW if a PFT was created
  if (((_q = account.holdReasons) === null || _q === void 0 ? void 0 : _q.includes("NEW_PAYEE_REVIEW")) && hasTransferredReward)
    return "NEW_PAYEE_REVIEW";
  if ((_r = account.holdReasons) === null || _r === void 0 ? void 0 : _r.includes("NEW_PAYEE_REVIEW"))
    return "DONE";
  if ((_s = account.holdReasons) === null || _s === void 0 ? void 0 : _s.includes("PAYMENT_HOLD_ON_CHANGE"))
    return "PAYMENT_HOLD_ON_CHANGE";
  if ((_t = account.holdReasons) === null || _t === void 0 ? void 0 : _t.includes("BENEFICIARY_NAME_INVALID"))
    return "BENEFICIARY_NAME_INVALID";
  if ((_u = account.holdReasons) === null || _u === void 0 ? void 0 : _u.includes("BENEFICIARY_NAME_MISMATCH"))
    return "BENEFICIARY_NAME_MISMATCH";
  if ((_v = account.holdReasons) === null || _v === void 0 ? void 0 : _v.includes("BANK_TAX_NAME_MISMATCH"))
    return "BANK_TAX_NAME_MISMATCH";
  if ((_w = account.holdReasons) === null || _w === void 0 ? void 0 : _w.includes("WITHDRAWAL_SETTINGS_INVALID"))
    return "WITHDRAWAL_SETTINGS_INVALID";
  if ((_x = account.holdReasons) === null || _x === void 0 ? void 0 : _x.includes("PAYMENT_RETURNED"))
    return "PAYMENT_RETURNED";
  if (account.hold)
    return "HOLD";
  return "DONE";
}
function usePayoutStatus(props) {
  var _a;
  const { type } = index_module.getEnvironmentSDK();
  const { loading, data, errors, refetch } = index_module.wn(GET_USER_STATUS, {});
  const { data: taxSettingRes } = index_module.wn(GET_TAX_SETTING, {});
  const { render, loading: veriffLoading, errors: veriffErrors, } = useVeriffApp();
  const [status, setStatus] = domContextHooks_module.useState(undefined);
  const enforceUsTaxComplianceOption = (_a = taxSettingRes === null || taxSettingRes === void 0 ? void 0 : taxSettingRes.tenantSettings) === null || _a === void 0 ? void 0 : _a.enforceUsTaxCompliance;
  domContextHooks_module.useEffect(() => {
    if (!data)
      return;
    const s = getStatus(data);
    setStatus(s);
  }, [data]);
  domContextHooks_module.useEffect(() => {
    const cb = () => refetch();
    window.addEventListener(TAX_FORM_UPDATED_EVENT_KEY, cb);
    window.addEventListener(VERIFF_COMPLETE_EVENT_KEY, cb);
    return () => {
      window.removeEventListener(TAX_FORM_UPDATED_EVENT_KEY, cb);
      window.removeEventListener(VERIFF_COMPLETE_EVENT_KEY, cb);
    };
  }, []);
  const onTermsClick = () => {
    let url = props.cashPayoutsPageUrl;
    if (url.includes("#"))
      url = url.split("#")[0];
    if (status === "INFORMATION_REQUIRED")
      url += "#1";
    else if (status === "OVER_W9_THRESHOLD" &&
      enforceUsTaxComplianceOption === "CASH_ONLY_DEFER_W9")
      url += "#3";
    window.history.pushState(null, "", url);
  };
  const onPaymentInfoClick = () => {
    let url = props.cashPayoutsPageUrl;
    url += "#4";
    window.history.pushState(null, "", url);
  };
  const onNewFormClick = () => {
    let url = props.cashPayoutsPageUrl;
    url += "#3";
    window.history.pushState(null, "", url);
  };
  return {
    states: {
      loading,
      veriffLoading,
      status,
      error: !!errors,
      enforceUsTaxComplianceOption,
    },
    data: { type },
    text: props.getTextProps(),
    callbacks: {
      onTermsClick,
      onClick: render,
      onPaymentInfoClick,
      onNewFormClick,
    },
  };
}

exports.TAX_FORM_UPDATED_EVENT_KEY = TAX_FORM_UPDATED_EVENT_KEY;
exports.VERIFF_COMPLETE_EVENT_KEY = VERIFF_COMPLETE_EVENT_KEY;
exports.getStatus = getStatus;
exports.usePayoutStatus = usePayoutStatus;
exports.useVeriffApp = useVeriffApp;
