(function() {

  let chatbotIframe = null;
  let chatbotContainer = null;
  let chatbotWelcomePrompt = null;
  let chatbotWelcomePromptText = null;
  let chatbotWelcomePromptClose = null;
  let isMobileOpen = false;
  const WELCOME_PROMPT_DISMISSED_STORAGE_PREFIX = 'chatbotWelcomePromptDismissed';

  const DIMENSIONS = {
    minimized: { width: 160, height: 85 },
    minimizedMobile: { width: 115, height: 90 },
    open: { width: 500, height: 700 }
  };

  const MOBILE_BREAKPOINT = 768;

  function getViewportWidth() {
    if (window.visualViewport && typeof window.visualViewport.width === 'number') {
      return Math.round(window.visualViewport.width);
    }

    if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientWidth;
    }

    return window.innerWidth;
  }

  function isMobile() {
    return getViewportWidth() <= MOBILE_BREAKPOINT;
  }

  function loadCss() {
    const style = document.createElement('style');
    style.type = 'text/css';
    const initDims = isMobile() ? DIMENSIONS.minimizedMobile : DIMENSIONS.minimized;
    style.innerHTML =
      '#proassistChatbotWidgetContainer { position: fixed; bottom: 20px; right: 20px; width: ' + initDims.width + 'px; height: ' + initDims.height + 'px; z-index: 10000000; transition: width 0.3s ease, height 0.3s ease; }' +
      '#proassistChatbotWidgetContainer.mobile-open { top: 0; bottom: 0; left: 0; right: 0; width: auto !important; height: auto !important; transition: none; }' +
      '#proassistChatbotWidgetContainer iframe { width: 100%; height: 100%; overflow: hidden; border: none; }' +
      '#proassistChatbotWelcomePrompt { position: fixed; bottom: 115px; right: 20px; display: flex; align-items: flex-start; gap: 8px; background: #ffffff; border: 1px solid #233A89; border-radius: 4px; padding: 8px 22px 8px 16px; font-family: Roboto, sans-serif; font-size: 12px; font-weight: 400; line-height: 20px; letter-spacing: 0.1px; color: #444444; white-space: nowrap; z-index: 10000001; opacity: 0; transform: translateY(14px); transition: opacity 0.3s ease, transform 0.3s ease; pointer-events: none; }' +
      '#proassistChatbotWelcomePrompt.visible { opacity: 1; transform: translateY(0); }' +
      '#proassistChatbotWelcomePrompt.visible { pointer-events: auto; }' +
      '#proassistChatbotWelcomePromptText { display: block; }' +
      '#proassistChatbotWelcomePromptClose { position: absolute; top: -11px; right: -11px; display: flex; align-items: center; justify-content: center; width: 23px; height: 23px; flex-shrink: 0; padding: 0; border: 1px solid #8593C3; border-radius: 50%; background: #ffffff; cursor: pointer; opacity: 0; visibility: hidden; z-index: 1; transition: opacity 0.2s ease, visibility 0.2s ease; }' +
      '#proassistChatbotWelcomePromptClose img { display: block; width: 8px; height: 8px; }' +
      '#proassistChatbotWelcomePrompt:hover #proassistChatbotWelcomePromptClose, #proassistChatbotWelcomePrompt:focus-within #proassistChatbotWelcomePromptClose { opacity: 1; visibility: visible; }' +
      '@media (hover: none) { #proassistChatbotWelcomePromptClose { opacity: 1; visibility: visible; } }' +
      '#proassistChatbotWelcomePrompt::after { content: ""; position: absolute; bottom: -7px; right: 40px; width: 0; height: 0; border-left: 4px solid transparent; border-right: 4px solid transparent; border-top: 8px solid #ffffff; }' +
      '#proassistChatbotWelcomePrompt::before { content: ""; position: absolute; bottom: -9px; right: 39px; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 9px solid #233A89; }';
    document.head.appendChild(style);
  }

  function isWelcomePromptDismissed(storageKey) {
    if (!storageKey) {
      return false;
    }

    try {
      return window.localStorage.getItem(storageKey) === 'true';
    } catch (error) {
      return false;
    }
  }

  function persistWelcomePromptDismissed(storageKey) {
    if (!storageKey) {
      return;
    }

    try {
      window.localStorage.setItem(storageKey, 'true');
    } catch (error) {
      // Ignore storage write issues.
    }
  }

  function getFallbackWelcomePromptStorageKey() {
    return WELCOME_PROMPT_DISMISSED_STORAGE_PREFIX + ':fallback';
  }

  function loadHtml() {
    const content = '<iframe src="https://system.proassist.pl/api/chatbot/widget/view/venue/ps-v1557-14f4tu' +
      (('https://system.proassist.pl/api/chatbot/widget/view/venue/ps-v1557-14f4tu'.indexOf('?') >= 0) ? '&' : '?') +
      'vw=' + getViewportWidth() + '" frameborder="0"></iframe>';
    const widget = document.createElement('div');
    widget.id = 'proassistChatbotWidgetContainer';
    widget.innerHTML = content;
    document.body.appendChild(widget);
    chatbotContainer = widget;
    chatbotIframe = widget.querySelector('iframe');
  }

  function updateContainerSize(isOpen) {
    if (!chatbotContainer) return;

    if (isMobile()) {
      if (isOpen) {
        chatbotContainer.classList.add('mobile-open');
        chatbotContainer.style.width = '';
        chatbotContainer.style.height = '';
      } else {
        chatbotContainer.classList.remove('mobile-open');
        const mobileDims = DIMENSIONS.minimizedMobile;
        chatbotContainer.style.width = mobileDims.width + 'px';
        chatbotContainer.style.height = mobileDims.height + 'px';
      }
    } else {
      chatbotContainer.classList.remove('mobile-open');
      const dims = isOpen ? DIMENSIONS.open : DIMENSIONS.minimized;
      chatbotContainer.style.width = dims.width + 'px';
      chatbotContainer.style.height = dims.height + 'px';
    }
  }

  function showWelcomePrompt(text, storageKey) {
    const resolvedStorageKey = storageKey || getFallbackWelcomePromptStorageKey();

    if (isWelcomePromptDismissed(resolvedStorageKey)) {
      return;
    }

    if (!chatbotWelcomePrompt) {
      chatbotWelcomePrompt = document.createElement('div');
      chatbotWelcomePrompt.id = 'proassistChatbotWelcomePrompt';
      chatbotWelcomePrompt.setAttribute('role', 'status');

      chatbotWelcomePromptText = document.createElement('span');
      chatbotWelcomePromptText.id = 'proassistChatbotWelcomePromptText';

      chatbotWelcomePromptClose = document.createElement('button');
      chatbotWelcomePromptClose.id = 'proassistChatbotWelcomePromptClose';
      chatbotWelcomePromptClose.type = 'button';
      chatbotWelcomePromptClose.setAttribute('aria-label', 'Zamknij dymek zachęty');
      chatbotWelcomePromptClose.innerHTML = '<img src="https\u003A\/\/system.proassist.pl/libs/chatbot/img/close_message_chatbot.svg" alt="" role="presentation" />';

      chatbotWelcomePromptClose.addEventListener('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        persistWelcomePromptDismissed(chatbotWelcomePrompt.dataset.storageKey);
        hideWelcomePrompt();

        if (chatbotIframe && chatbotIframe.contentWindow) {
          chatbotIframe.contentWindow.postMessage({
            type: 'chatbot-welcome-prompt',
            action: 'dismiss',
            storageKey: chatbotWelcomePrompt.dataset.storageKey
          }, '*');
        }
      });

      chatbotWelcomePrompt.appendChild(chatbotWelcomePromptText);
      chatbotWelcomePrompt.appendChild(chatbotWelcomePromptClose);
      document.body.appendChild(chatbotWelcomePrompt);
    }
    chatbotWelcomePrompt.dataset.storageKey = resolvedStorageKey;
    chatbotWelcomePromptText.textContent = text;
    setTimeout(function() {
      chatbotWelcomePrompt.classList.add('visible');
    }, 100);
  }

  function hideWelcomePrompt() {
    if (!chatbotWelcomePrompt) return;
    chatbotWelcomePrompt.classList.remove('visible');
  }

  function setupChatbotStateListener() {
    window.addEventListener('message', function(event) {
      if (!event.data) return;
      if (event.data.type === 'chatbot-state') {
        isMobileOpen = !!event.data.isOpen;
        updateContainerSize(event.data.isOpen);
        if (event.data.isOpen) hideWelcomePrompt();
      } else if (event.data.type === 'chatbot-welcome-prompt') {
        if (event.data.action === 'show') {
          showWelcomePrompt(event.data.text, event.data.storageKey);
        } else if (event.data.action === 'hide') {
          hideWelcomePrompt();
        } else if (event.data.action === 'dismiss') {
          persistWelcomePromptDismissed(event.data.storageKey || getFallbackWelcomePromptStorageKey());
          hideWelcomePrompt();
        }
      }
    });
  }

  function sendViewportWidth() {
    if (chatbotIframe && chatbotIframe.contentWindow) {
      chatbotIframe.contentWindow.postMessage({
        type: 'viewport-width',
        width: getViewportWidth()
      }, '*');
    }
  }

  function setupViewportCommunication() {
    function handleViewportChange() {
      updateContainerSize(isMobileOpen);
      sendViewportWidth();
    }

    window.addEventListener('resize', handleViewportChange);
    window.addEventListener('orientationchange', handleViewportChange);

    if (window.visualViewport) {
      window.visualViewport.addEventListener('resize', handleViewportChange);
    }

    if (chatbotIframe) {
      chatbotIframe.addEventListener('load', function() {
        sendViewportWidth();
      });
    }

    setTimeout(sendViewportWidth, 500);
  }

  function domReady() {
    loadCss();
    loadHtml();
    setupViewportCommunication();
    setupChatbotStateListener();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', domReady);
  } else {
    domReady();
  }
})();
