(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define([], factory);
  } else if (typeof exports !== "undefined") {
    factory();
  } else {
    var mod = {
      exports: {}
    };
    factory();
    global.chat_interfaceJs = mod.exports;
  }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function () {
  "use strict";

  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

  function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

  function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

  (function (window) {
    var featureFlags = {
      die: function die() {
        var userAgent = JSON.parse('{"chrome":true,"firefox":false,"ie":false,"mobile_safari":false,"mozilla":false,"opera":false,"safari":false,"webkit":true,"android":false,"version":"537.36"}');

        if (userAgent.ie) {
          var searchParams = new URLSearchParams(location.search);
          return !searchParams.has('ie');
        } else {
          return false;
        }
      }
    };

    if (featureFlags.die()) {
      return;
    }

    if (isScopeInitialized()) {
      run();
    } else {
      var onLoadAttachedPoll = setInterval(function () {
        if (isScopeInitialized()) {
          clearInterval(onLoadAttachedPoll);
          run();
        }
      }, 1000);
    }

    function isScopeInitialized() {
      return window.$HD && typeof window.$HD.onLoad === 'function';
    }

    function run() {
      var config = JSON.parse('{"bundle_path":"/static/js/app.v1.ef1bc6bd4db830c68de1.js","env":"production","sentry_dsn":"","maxUploadSize":5242880,"maxAttachmentsCount":5,"clientVersion":"84","personalizationFormInputMaxLength":128,"updateMessagesViewedTimeDelay":5000,"transcript":{"download_limit":300000},"socket_requestTimeout":5000,"socket_initialDataEventName":"INITIAL_DATA","allowedExtensions":["csv","jpeg","jpg","pdf","png","txt","xls","xlsx","zip","pem","crt","key","cer","p7b","p7s","p7c","p12","pfx","ca-bundle","wav","eml","mp4","mov","doc","docx"]}');

      _extends(window.$HD, {
        loaded: false,
        loading: false,
        $config: config,
        base_host: 'https://chat.engagement.ai',
        cdnPath: 'https://cdn.engagement.ai/production',
        clientTokenCookieName: "clientToken".concat(config.env),
        siteTokenCookieName: "siteToken".concat(config.env),
        getCookie: getCookie,
        setCookie: setCookie,
        deleteCookie: deleteCookie,
        load: load,
        resetSession: resetSession,
        updateCustomer: updateCustomer
      });

      window.$HD.onLoad(window.$HD);
    }

    function load() {
      var loadOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      if (window.$HD.loading) {
        return;
      }

      if (!window.$HD.loaded) {
        window.$HD.loading = true;
      }

      var noop = function noop() {};

      window.$HD.loginCallBack = loadOptions.loginCallBack || noop;
      var clientToken = getCookie(window.$HD.clientTokenCookieName);
      request({
        path: '/load',
        query: {
          load: !window.$HD.loaded,
          login: loadOptions.login || !!loadOptions.token,
          reset: loadOptions.reset,
          token: loadOptions.token || clientToken
        }
      }).then(function (response) {
        window.$HD.domain = response.domain || location.hostname.replace(/^www\./, '');
        updateCookies(response);

        if (!window.$HD.loaded) {
          addChatTag();
          addSchemeCss(response.uiScheme);
          return addScript(response.chatScriptFile);
        }

        if (window.$HD.__interface) {
          window.$HD.__interface.reconnect(response.clean, response.reconnect);
        }
      }).then(function () {
        window.$HD.loaded = true;
        window.$HD.loading = false;
        window.$HD.loginCallBack();
      }).catch(function () {
        window.$HD.loading = false;
      });
    }

    function resetSession() {
      var token = getCookie(window.$HD.siteTokenCookieName);
      window.$HD.load({
        token: token,
        reset: true
      });
    }

    function updateCustomer(token) {
      return request({
        method: 'POST',
        path: '/update_customer',
        body: {
          token: token
        }
      }).then(updateCookies);
    }

    function request(_ref) {
      var _ref$method = _ref.method,
          method = _ref$method === void 0 ? 'GET' : _ref$method,
          path = _ref.path,
          query = _ref.query,
          body = _ref.body;
      var headers = {
        'Content-Type': 'application/json'
      };
      var clientToken = getCookie(window.$HD.clientTokenCookieName);

      if (clientToken) {
        headers.authorization = clientToken;
      }

      return fetch(window.$HD.base_host + '/api/v1/chat' + path + formatQueryString(query), {
        method: method,
        body: body ? JSON.stringify(body) : undefined,
        headers: headers
      }).then(function (response) {
        if (!response.ok) {
          throw new Error(response.statusText);
        }

        return response.json();
      });
    }

    function formatQueryString() {
      var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var truthyQueryParams = Object.entries(query).filter(function (_ref2) {
        var _ref3 = _slicedToArray(_ref2, 2),
            key = _ref3[0],
            value = _ref3[1];

        return key && value;
      }).map(function (_ref4) {
        var _ref5 = _slicedToArray(_ref4, 2),
            key = _ref5[0],
            value = _ref5[1];

        return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
      });

      if (!truthyQueryParams.length) {
        return '';
      }

      return "?".concat(truthyQueryParams.join('&'));
    }

    function addScript(src) {
      var scriptTag = document.createElement('script'),
          firstScriptTag = document.getElementsByTagName('script')[0];
      scriptTag.type = 'text/javascript';
      scriptTag.charset = 'utf-8';
      scriptTag.async = true;
      scriptTag.src = src;
      firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag);
      return new Promise(function (resolve) {
        return scriptTag.onload = resolve;
      });
    }

    function addSchemeCss(uiScheme) {
      var styleTag = document.createElement('style');
      var headTag = document.head || document.getElementsByTagName('head')[0];
      styleTag.type = 'text/css';
      styleTag.appendChild(document.createTextNode(uiScheme));
      headTag.appendChild(styleTag);
    }

    function addChatTag() {
      var chatTag = document.createElement('div');
      chatTag.className = 'chat';
      document.body.appendChild(chatTag);
    }

    function updateCookies(_ref6) {
      var siteToken = _ref6.siteToken,
          clientToken = _ref6.clientToken;

      if (siteToken === false) {
        deleteCookie(window.$HD.siteTokenCookieName);
      } else if (siteToken) {
        setCookie(window.$HD.siteTokenCookieName, siteToken);
      }

      if (clientToken === false) {
        deleteCookie(window.$HD.clientTokenCookieName);
      } else if (clientToken) {
        setCookie(window.$HD.clientTokenCookieName, clientToken);
      }
    }

    function getCookie(name) {
      var nameEQ = name + '=';
      var cookieKeyValue = document.cookie.split(';').find(function (cookie) {
        return cookie.includes(nameEQ);
      });
      return cookieKeyValue && (cookieKeyValue.split(nameEQ)[1] || true);
    }

    function setCookie(cookieName) {
      var _options;

      var cookieValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
      var expires = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 24 * 3600 * 30;
      var options = (_options = {}, _defineProperty(_options, cookieName, cookieValue), _defineProperty(_options, "samesite", 'strict'), _defineProperty(_options, "path", '/'), _defineProperty(_options, "domain", window.$HD.domain), _options);
      var expirationDate = new Date();
      expirationDate.setTime(expirationDate.getTime() + expires * 1000);
      options.expires = expirationDate.toUTCString();
      document.cookie = Object.entries(options).map(function (_ref7) {
        var _ref8 = _slicedToArray(_ref7, 2),
            name = _ref8[0],
            value = _ref8[1];

        return "".concat(name).concat(value === true ? '' : '=' + value);
      }).join(';');
    }

    function deleteCookie(name) {
      return setCookie(name, '', -1);
    }
  })(window);
});
