(function () {
    if (window.widgetInstantHooks) return;
  
    const appendElement = (tag, attributes, parent = document.head) => {
      const element = document.createElement(tag);
      Object.keys(attributes).forEach(attr => element[attr] = attributes[attr]);
      parent.appendChild(element);
      return element;
    };
  
    const urlParams = new URLSearchParams(window.location.search);
    let protocol = 'https:';
    let host_path = '';
  
    const setHostPath = () => {

      const setHostAndMidValue = (scriptTag, hostValue, widgetPath = '') => {
        const url = new URL(scriptTag.src);
        localStorage.setItem('midValue', url.searchParams.get('mid') || '');
        host_path = `${protocol}//${hostValue}${widgetPath}`;
      };

      const scriptTagChat = document.querySelector('script[src*="https://chat.sndrmsg.com"]');
      const scriptTagVoice = document.querySelector('script[src*="https://voice.sndrmsg.com"]');



      if (scriptTagChat) {
        setHostAndMidValue(scriptTagChat, 'chat.sndrmsg.com', '/widget');
      } else if (scriptTagVoice) {
        setHostAndMidValue(scriptTagVoice, 'voice.sndrmsg.com');
      } else if (location.port === '3000' || location.port === '3001') {
        //host_path = `${location.protocol}//localhost:3000/widget`;
        host_path = `${window.location.origin}/widget`;
      } else {
        return false;
      }

      if (urlParams.get('mode') === 'dev') {
        host_path = `${protocol}//dev.dany.ai/widget`;
      }

      if (location.port === '3000' || location.port === '3001') {
        //host_path = `${location.protocol}//localhost:3000/widget`;
        host_path = `${window.location.origin}/widget`;
      }
 
      return true;
    };
  
    if (!setHostPath()) return;
  
    const resources = [
      { tag: 'script', attributes: { src: 'https://cdn.socket.io/4.7.5/socket.io.min.js', id: 'sndrmsg-script-socket' } },
      { tag: 'script', attributes: { src: 'https://cdn.jsdelivr.net/npm/compromise@14.13.0/builds/compromise.min.js', id: 'sndrmsg-script-compromise' } },
      { tag: 'link', attributes: { rel: 'stylesheet', type: 'text/css', href: `${host_path}/widget.css`, id: 'sndrmsg-style-widget' } }
    ];
  
    resources.forEach(resource => appendElement(resource.tag, resource.attributes));
  
    class Hooks {
      constructor() {
        this.hooks = {};
      }
  
      addHook(hookName, callback, options = {}) {
        if (!this.hooks[hookName]) {
          this.hooks[hookName] = [];
        }
        const hook = {
          callback: callback,
          once: options.once || false
        };
        this.hooks[hookName].push(hook);
      }
  
      removeHook(hookName, callback) {
        if (!this.hooks[hookName]) return;
        this.hooks[hookName] = this.hooks[hookName].filter(
          (hook) => hook.callback !== callback
        );
      }
  
      invokeHook(hookName, value, force = false) {
        if (!this.hooks[hookName]) return;
        this.hooks[hookName] = this.hooks[hookName].filter((hook) => {
          hook.callback(value, force);
          return !hook.once;
        });
      }
    }
  
    window.widgetInstantHooks = new Hooks();
  
    document.getElementById('sndrmsg-script-socket').onload = () => {
      appendElement('script', {
        src: 'https://cdn.jsdelivr.net/npm/socket.io-stream/socket.io-stream.js',
        id: 'sndrmsg-script-stream'
      }).onload = () => {
        const widgetContainer = document.createElement('div');
        widgetContainer.id = 'widget-container';
        document.body.appendChild(widgetContainer);
  
        const widgetScript = appendElement('script', {
          async: true,
          src: `${host_path}/js/dist/index.js?v=${Date.now()}`,
          id: 'sndrmsg-script-index'
        }, document.body);
  
        const additionalScripts = [
          { src: 'https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.3/min/tiny-slider.js', id: 'sndrmsg-script-tiny-slider' },
          { src: 'https://cdn.jsdelivr.net/gh/anseki/leader-line/leader-line.min.js', id: 'sndrmsg-script-leader-line' }
        ];
  
        additionalScripts.forEach(script => appendElement('script', { async: true, ...script }, document.body));
  
        appendElement('link', {
          rel: 'stylesheet',
          type: 'text/css',
          href: 'https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.3/tiny-slider.css',
          id: 'sndrmsg-style-tiny-slider'
        });
  
        widgetScript.onload = () => {
          let initedVoice = false;
  
          window.widgetInstantHooks.addHook('widgetSettings', async (widgetSettings) => {
            if (widgetSettings.isVoice && !initedVoice) {
              window.chatWidgetSettings = widgetSettings;
  
              appendElement('script', {
                src: `${host_path}/js/dist/voice.js?v=${Date.now()}`,
                id: 'sndrmsg-script-voice'
              }, document.body);
  
              initedVoice = true;
  
              if (widgetSettings?.selectVoice) {
                localStorage.setItem('selectedVoice', `{"id":"${widgetSettings.selectVoice}"}`);
              }
  
              localStorage.setItem('speechQuality', widgetSettings?.speechQuality || '');
            }
          });
  
          if (window.speechSynthesis?.onvoiceschanged !== undefined) {
            window.speechSynthesis.onvoiceschanged = () => {
              window.browserVoices = window.speechSynthesis.getVoices();
            };
          }
        };
      };
    };
  })();