(function() {
  'use strict';
  try {
    const chatWebsiteAddress = new URL('https://www.cdcraee.it');
    if (chatWebsiteAddress.origin !== window.location.origin){
        throw new Error(`Domain "${window.location.origin}"" can't load snippet for 'https://www.cdcraee.it'. Please check your website domain in the current XCALLY Chat Website settings.`);
    }
  } catch (error) {
    console.warn(`Domain ${window.location.origin} can't load snippet for 'https://www.cdcraee.it'. Please check your website domain in the current XCALLY Chat Website settings.`);
    return;
  }
  // Init all URLs
  const remoteURL = new URL('https://chat.ingo.it');
  const chatOrigin = remoteURL.origin;
  const chatPath = '/chat-client/';
  const chatStylesPath = chatPath + 'styles/';
  const chatVersion = 'v3.36.1';

  // Style setttings
  const divColor = '#0071A5';
  const textColor = '#fafafa';
  const buttonColor = '#0071A5';
  const backgroungColor = '#fafafa';
  let alignment = "bottom_right";
  let verticalAlignment = "30";

  // iframe URL settings
  const iframeId = 'motion-chat-iframe';
  const iframeSrcURL = new URL(chatPath, chatOrigin);
  const iframeSearchParams = new URLSearchParams('address=https%3A%2F%2Fwww.cdcraee.it&onlineForm=&offlineForm=&id=6&name=CDC%20RAEE&description=&mapKey=email&mapKeyOffline=email&key=RAEE&agentAlias=Agent&customerAlias=Me&color=%230071A5&color_button=%230071A5&textColor=%23fafafa&textButtonColor=%23fafafa&fontSize=12&remote=https%3A%2F%2Fchat.ingo.it&animation=true&header_shape=rounded&header_online=Hai%20bisogno%20di%20aiuto%3F%20CHATTA%20CON%20NOI&start_chat_button=SCRIVI&offline_chat_button=Send&header_offline=&download_transcript=false&timeout=0&whiteLabel=Powered%20by%20Xenialab&defaultWhiteLabel=false&sitepic=1638185550220-MicrosoftTeams-image%20(15).png&closingQuestion=Vuoi%20terminare%20la%20conversazione%3F&formSubmitSuccessMessage=Form%20properly%20submitted&formSubmitFailureMessage=Form%20submission%20error&noteTitle=Note&placeholderMessage=Type%20a%20message&closingMessage=La%20chat%20%C3%A8%20terminata.%20Grazie%20per%20averci%20contattato&closingMessageButton=Invia&skipMessageButton=Salta&conditionAgreement=false&enableRating=false&enableFeedback=false&enableSendButton=true&enablePrintIcon=true&feedbackTitle=Feedback&ratingType=star&ratingStarsNumber=5&token=gl4hXLlaDs1gunMmyMLUOIyWks7xpYtw&autoclose=false&enableCustomerWriting=false&forwardTranscript=false&forwardTranscriptMessage=&forwardOffline=false&forwardOfflineAddress=&waitingTitle=All%20of%20our%20agents%20are%20busy%20at%20this%20time.%20Your%20chat%20is%20very%20important%20to%20us.&waitingMessage=Please%20hold%20and%20we%20will%20answer%20your%20request%20as%20soon%20as%20possible.&offlineMessageSubject=New%20offline%20message%20from%20websiteName&offlineMessageBody=You%20received%20a%20new%20offline%20message%20from%20websiteName.%20Here%20you%20can%20find%20the%20details%20of%20the%20request%3A&enableUnmanagedNote=true&unmanagedMessage=Your%20request%20has%20not%20been%20processed.&skipUnmanaged=Skip&sendUnmanaged=Send&enableCustomerAttachment=false&enableCustomerCheckmarks=false&agentAvatar=&showAgentAvatar=false&timezone=&notificationTemplate=%3Cp%3EAccount%3A%20%7B%7Baccount.name%7D%7D%3Cbr%20%2F%3E%0A%7B%7B%23queue%7D%7DQueue%3A%20%7B%7Bqueue.name%7D%7D%3Cbr%20%2F%3E%0A%7B%7B%2Fqueue%7D%7DFrom%20%3A%20%7B%7Bfrom%7D%7D%3C%2Fp%3E%0A&notificationSound=true&notificationShake=true&hideWhenOffline=true&agentIdentifier=website_alias&waitForTheAssignedAgent=10&alignment=bottom_right&verticalAlignment=30&labelText=SCRIVI&messagesAlignment=alternate&defaultTitle=&customerAvatar=&showCustomerAvatar=false&messageFontSize=12&backgroundColor=%23fafafa&queueTransfer=false&queueTransferTimeout=300&agentTransfer=true&agentTransferTimeout=300&systemAlias=System&systemAvatar=&mandatoryDispositionPauseId=2&mandatoryDisposition=true&vidaooEscalation=false&vidaooApiKey=0&vidaooTopic=Generated%20by%20XCALLY%20Motion&vidaooNote=Meeting%20generated%20for%20interaction%20%23%7B%7Binteraction.id%7D%7D%20by%20%7B%7Bagent.name%7D%7D&vidaooMetadata=&openNewInteraction=false&subjectOffline=&waitForTheAssignedQueue=10&enableCustomerAudioRecording=false&aiAssistantId=&aiProviderId=&createdAt=&updatedAt=&ListId=7&IntervalId=72881&MailAccountId=&Interval=&customerIp=94.16.106.112&referer=https%3A%2F%2Fwww.cdcraee.it%2F&openedInteractions=2&maxInteractions=660&virtual=&online=true&custom=true');
  iframeSearchParams.append('version', chatVersion);
  iframeSearchParams.append('location', btoa(window.location.host));
  iframeSrcURL.search = iframeSearchParams;

  // Style URL settings
  const linkURL =  new URL(chatStylesPath + 'mobile.css', chatOrigin);
  linkURL.search = new URLSearchParams({ version: chatVersion });
  const linkMobile = document.createElement('link');
  linkMobile.type = "text/css";
  linkMobile.rel='stylesheet';
  linkMobile.href = linkURL.toString();

  // Iframe localstorage whitelisting
  const allowedOrigins = [chatOrigin];

  function remoteLocalStorageEventHandler(event) {
    if (allowedOrigins.includes(event.origin)) {
      const { action, key, value } = event.data;
      const localStorage = window.localStorage;
      switch(action) {
        case 'setItem': {
          localStorage.setItem(key, JSON.stringify(value))
          event.source.postMessage(
            { action: 'setItemResult', key },
            event.origin
          );
          break;
        }
        case 'getItem': {
          let item = localStorage.getItem(key);
          if (item) {
            try {
              item = JSON.parse(item);
            } catch (error) {
              console.error('Cannot read data from localstorage', error);
            }
          }
          event.source.postMessage(
            { action: 'getItemResult', key, item },
            event.origin
          );
          break;
        }
        case 'removeItem': {   
          localStorage.removeItem(key);
          event.source.postMessage(
            { action: 'removeItemResult', key},
            event.origin
          );
          break;
        }
        default: {
          typeof action === 'string' && console.debug('Unsupported action', action)
          break;
        }
      }
    }
  }

  // DOM Manipulation
  let iframe = document.createElement('iframe');
  // Attributes
  iframe['id'] = iframeId;
  iframe['src'] = iframeSrcURL.toString()
  iframe['allow'] = 'camera;microphone'

  let  iframe_status = false;

  document.documentElement.style.setProperty('--xc-ws-div-color', divColor);
  document.documentElement.style.setProperty('--xc-ws-text-color', textColor);
  document.documentElement.style.setProperty('--xc-ws-button-color', buttonColor);
  document.documentElement.style.setProperty('--xc-ws-background-color', backgroungColor);

  document.head.appendChild(linkMobile);
  document.body.appendChild(iframe);

      // Bottom, right
    iframe.className = 'motion-chat-iframe-bottom_right';
    verticalAlignment = 0;
     

      

  // START Events management
  window.addEventListener(
    'message',
    (evt) => {
        remoteLocalStorageEventHandler(evt);
        switch (evt.data.cmd) {
            case 'show':
                              // Bottom, right
                iframe.style.top = 'auto';
                iframe.style.bottom = '0px';
                            break;
            case 'hide':
                              // Bottom, right
                iframe.style.top = 'calc(100% - 50px)';
                            break;
            case "init": 
                            break;
            case "offline": 
                            break;
            default:
              break;
        }
    },
    false
  );
  // END Events management

  // START Proactive action management
    // END Proactive action management
  if (window.DeviceOrientationEvent) {
    window.addEventListener('orientationchange', function() {
    if (alignment == 'right') {
      document.getElementById("chat_tab_arrow").innerHTML = "<strong> < </strong>";
      let iframeEl = document.getElementById('motion-chat-iframe');
      iframeEl.contentWindow?.postMessage({"evt":"hide"}, '*');
      tab_status = 0;
      iframe_h = topIframe_calc();
      topIframe_set(iframe_h);
      if(typeof div_tab != "undefined") topChat_set(iframe_h, verticalAlignment);
    }
    else if (alignment == 'left') {
      document.getElementById("chat_tab_arrow").innerHTML = "<strong> > </strong>";
      let iframeEl = document.getElementById('motion-chat-iframe');
      iframeEl.contentWindow?.postMessage({"evt":"hide"}, '*');
      tab_status = 0;
      iframe_h = topIframe_calc();
      topIframe_set(iframe_h);
      if(typeof div_tab != "undefined") {
        topChat_set(iframe_h, verticalAlignment);
      }
    } }, false);
  }

  window.addEventListener(
    "resize",
    function(event) {
      let iframe_h = topIframe_calc();
      topIframe_set(iframe_h);
      if (typeof div_tab != "undefined") {
          topChat_set(iframe_h, verticalAlignment);
      }
    }
  );

  function topIframe_calc(){
    let height_iframe
    let  heightD = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    let  iframeT = ((heightD/100)*verticalAlignment) + 450;
    if (heightD < iframeT) {
        height_iframe = 450 - (iframeT - heightD);
    }
    else {
        height_iframe = 450;
    }
    return height_iframe;
  }

  function topIframe_set(height_iframe){
    if (height_iframe > 340) {
      iframe.style['height'] = height_iframe +'px';
      if (alignment == "right" || alignment == "left" ) {
        iframe.style['top'] = verticalAlignment + "%"; 
      }
      else {
        iframe.style['bottom'] = "0%";
      }
    }
    else {
      iframe.style['height'] = '340px';
      if (alignment == "right" || alignment == "left" ) {
        iframe.style['top'] = "calc(100% - 340px)";
      }
      else {
        iframe.style['bottom'] = "0%";
      }
    }
  }

  function topChat_set(height_iframe, verticalAlignment) {
    if (height_iframe > 340) {
      div_tab.style['top'] = "calc("+ verticalAlignment +"% + " + (height_iframe - 100) + "px)";
    }
    else {
      div_tab.style['top'] = "auto";
      div_tab.style['bottom'] = "0px";
    }
  }

  // hide chat
        // hide template
      document.getElementById("motion-chat-iframe-tab").style.display = "none";
  }());