!function () {
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const EXPAND_MS = prefersReduced ? 0 : 350;

    let collapsedWidth = 368;
    let collapsedHeight = 192;

    const OPEN_WIDTH = 368;
    const OPEN_HEIGHT = '95vh';

    const frame = document.createElement('iframe');
    frame.id = '42chat-bot-frame';
    frame.title = '42chat Messenger';
    frame.src = "https://excon-shell-prod.web.app/messenger?eventId=6799a2b5b55681003977d23d&variant=button";
    frame.setAttribute('loading','lazy');
    frame.setAttribute('allowTransparency','true');
    frame.setAttribute('scrolling', 'no');
    frame.style.overflow = 'hidden';

    frame.style.cssText = [
      'position: fixed',
      'bottom: 0',
      'right: 0',
      'width: ' + collapsedWidth + 'px',
      'height: ' + collapsedHeight + 'px',
      'border: none',
      'background: transparent !important',
      'z-index: 1200'
    ].join(';');

    document.body.appendChild(frame);
    window.___MESSENGER_IFRAME_REF = frame;

    const TARGET_ORIGIN = '*';
    let iframeReady = false;
    const queue = [];
    let isOpen = false;
    const MIN_SIZE = 100;

    const postToIframe = (msg) => {
      if (iframeReady) {
        frame.contentWindow?.postMessage(msg, TARGET_ORIGIN);
      } else {
        queue.push(msg);
      }
    };

    window.addEventListener('message', (ev) => {
      if (ev.data?.type === '42chat-ready') {
        iframeReady = true;
        queue.splice(0).forEach(postToIframe);
        return;
      }

      if (ev.data?.type === 'messenger:resize' && typeof ev.data.width === 'number' && typeof ev.data.height === 'number') {
        collapsedWidth = Math.max(MIN_SIZE, ev.data.width);
        collapsedHeight = Math.max(MIN_SIZE, ev.data.height);
        if (!isOpen) {
          frame.style.width = collapsedWidth + 'px';
          frame.style.height = collapsedHeight + 'px';
        }
        return;
      }

      if (ev.data?.type === 'chat:resize') {
        isOpen = ev.data.offset === 0;
        if (isOpen) {
          frame.style.width = OPEN_WIDTH + 'px';
          frame.style.height = OPEN_HEIGHT;
          postToIframe({ type: 'HOST_OPEN', duration: EXPAND_MS });
        } else {
          frame.style.width = collapsedWidth + 'px';
          frame.style.height = collapsedHeight + 'px';
        }
      }
    });

    document.addEventListener('click', (ev) => {
      const inside = ev.target instanceof Node && frame.contains(ev.target);
      if (!inside) {
        postToIframe({ type: 'HOST_MINIMIZE' });
      }
    }, true);
  }();