(function () {
  'use strict';

  function initializePreview(root) {
    if (!root || root.dataset.casPreviewReady === '1') {
      return;
    }

    const video = root.querySelector('.custausu-rm-doctor-support-card__img');
    const card = root.querySelector('.custausu-doctor-support-fallback-card');

    if (!video || !card) {
      return;
    }

    root.dataset.casPreviewReady = '1';

    const desktopSrc = video.getAttribute('data-desktop-src') || '';
    const mobileSrc = video.getAttribute('data-mobile-src') || '';
    let maxPlays = parseInt(video.getAttribute('data-max-plays') || '2', 10);

    if (!maxPlays || maxPlays < 1) {
      maxPlays = 2;
    }

    const mq = window.matchMedia
      ? window.matchMedia('(max-width: 782px)')
      : null;

    let activeSrc = '';
    let playCount = 0;
    let hasStarted = false;
    let isFinished = false;
    let isVisible = false;

    function wantedSrc() {
      if (mq && mq.matches && mobileSrc) {
        return mobileSrc;
      }

      return desktopSrc || mobileSrc;
    }

    function applyLayout() {
      if (mq && mq.matches) {
        card.style.minHeight = '550px';
        card.style.aspectRatio = 'auto';
      } else {
        card.style.minHeight = '448px';
        card.style.aspectRatio = '735 / 448';
      }
    }

    function applySource() {
      const src = wantedSrc();

      if (!src || src === activeSrc) {
        return;
      }

      activeSrc = src;

      while (video.firstChild) {
        video.removeChild(video.firstChild);
      }

      const source = document.createElement('source');
      source.src = src;
      source.type = 'video/webm';
      video.appendChild(source);
      video.load();
    }

    function safePlay() {
      if (!isVisible || isFinished) {
        return;
      }

      applySource();

      const promise = video.play();

      if (promise && typeof promise.catch === 'function') {
        promise.catch(function () {});
      }
    }

    function startWhenVisible() {
      if (hasStarted || isFinished) {
        safePlay();
        return;
      }

      hasStarted = true;
      playCount = 1;
      safePlay();
    }

    video.addEventListener('ended', function () {
      if (playCount < maxPlays) {
        playCount += 1;

        try {
          video.currentTime = 0;
        } catch (error) {}

        safePlay();
        return;
      }

      isFinished = true;
    });

    applyLayout();

    const onViewportChange = function () {
      applyLayout();

      if (!hasStarted) {
        activeSrc = '';
        applySource();
      }
    };

    if (mq && typeof mq.addEventListener === 'function') {
      mq.addEventListener('change', onViewportChange);
    } else if (mq && typeof mq.addListener === 'function') {
      mq.addListener(onViewportChange);
    }

    if ('IntersectionObserver' in window) {
      const observer = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          isVisible = entry.isIntersecting && entry.intersectionRatio >= 0.35;

          if (isVisible) {
            startWhenVisible();
          } else if (!isFinished && !video.paused) {
            video.pause();
          }
        });
      }, {
        threshold: [0, 0.35, 0.65]
      });

      observer.observe(card);
    } else {
      isVisible = true;
      startWhenVisible();
    }
  }

  function initializeAll() {
    document.querySelectorAll(
      '.custausu-doctor-support-preview--fallback'
    ).forEach(initializePreview);
  }

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