(function () {
  'use strict';

  function initSlider(root) {
    var slides = Array.prototype.slice.call(root.querySelectorAll('.custausu-rm-admin-top__slide'));
    var prev = root.querySelector('[data-custausu-rm-prev]');
    var next = root.querySelector('[data-custausu-rm-next]');
    var dots = Array.prototype.slice.call(root.querySelectorAll('[data-custausu-rm-dot]'));

    if (!slides.length) {
      return;
    }

    var index = 0;
    var timer = null;
    var paused = false;
    var delay = parseInt(root.getAttribute('data-custausu-rm-autoplay-delay') || '7000', 10);

    if (!delay || delay < 3000) {
      delay = 7000;
    }

    function show(nextIndex) {
      if (nextIndex < 0) {
        nextIndex = slides.length - 1;
      }

      if (nextIndex >= slides.length) {
        nextIndex = 0;
      }

      index = nextIndex;

      slides.forEach(function (slide, i) {
        var active = i === index;
        slide.classList.toggle('is-active', active);
        slide.setAttribute('aria-hidden', active ? 'false' : 'true');
      });

      dots.forEach(function (dot, i) {
        var active = i === index;
        dot.classList.toggle('is-active', active);
        dot.setAttribute('aria-current', active ? 'true' : 'false');
      });
    }

    function stopAutoplay() {
      if (timer) {
        window.clearInterval(timer);
        timer = null;
      }
    }

    function startAutoplay() {
      stopAutoplay();

      if (slides.length < 2 || paused) {
        return;
      }

      timer = window.setInterval(function () {
        if (!paused) {
          show(index + 1);
        }
      }, delay);
    }

    function pause() {
      paused = true;
      stopAutoplay();
      root.classList.add('is-paused');
    }

    function resume() {
      paused = false;
      root.classList.remove('is-paused');
      startAutoplay();
    }

    function manualShow(nextIndex) {
      show(nextIndex);
      startAutoplay();
    }

    if (prev) {
      prev.addEventListener('click', function () {
        manualShow(index - 1);
      });
    }

    if (next) {
      next.addEventListener('click', function () {
        manualShow(index + 1);
      });
    }

    dots.forEach(function (dot, i) {
      dot.addEventListener('click', function () {
        manualShow(i);
      });
    });

    slides.forEach(function (slide) {
      slide.addEventListener('click', function (event) {
        var interactive = event.target && event.target.closest
          ? event.target.closest('a, button, input, select, textarea, label')
          : null;

        if (interactive) {
          return;
        }

        if (paused) {
          resume();
        } else {
          pause();
        }
      });
    });

    var touchStartX = 0;
    var touchStartY = 0;
    var touchMoved = false;

    root.addEventListener('touchstart', function (event) {
      if (!event.touches || !event.touches.length) {
        return;
      }

      touchMoved = false;
      touchStartX = event.touches[0].clientX;
      touchStartY = event.touches[0].clientY;
    }, { passive: true });

    root.addEventListener('touchmove', function (event) {
      if (!event.touches || !event.touches.length) {
        return;
      }

      var dx = event.touches[0].clientX - touchStartX;
      var dy = event.touches[0].clientY - touchStartY;

      if (Math.abs(dx) > 12 || Math.abs(dy) > 12) {
        touchMoved = true;
      }
    }, { passive: true });

    root.addEventListener('touchend', function (event) {
      if (!touchMoved) {
        return;
      }

      var changed = event.changedTouches && event.changedTouches.length ? event.changedTouches[0] : null;
      if (!changed) {
        return;
      }

      var dx = changed.clientX - touchStartX;
      var dy = changed.clientY - touchStartY;

      if (Math.abs(dx) < 44 || Math.abs(dx) < Math.abs(dy) * 1.35) {
        return;
      }

      if (dx < 0) {
        manualShow(index + 1);
      } else {
        manualShow(index - 1);
      }
    }, { passive: true });

    root.addEventListener('keydown', function (event) {
      if (event.key === 'ArrowLeft') {
        manualShow(index - 1);
      }

      if (event.key === 'ArrowRight') {
        manualShow(index + 1);
      }
    });

    root.addEventListener('mouseenter', pause);
    root.addEventListener('mouseleave', resume);
    root.addEventListener('focusin', pause);
    root.addEventListener('focusout', function () {
      window.setTimeout(function () {
        if (!root.contains(document.activeElement)) {
          resume();
        }
      }, 50);
    });

    document.addEventListener('visibilitychange', function () {
      if (document.hidden) {
        stopAutoplay();
      } else {
        startAutoplay();
      }
    });

    show(0);
    startAutoplay();
  }

  function init() {
    Array.prototype.slice.call(document.querySelectorAll('[data-custausu-rm-slider]')).forEach(initSlider);
  }

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

/**
 * CAS RM — Doctor CTA bridge
 * Intercepts internal Doctor CTA hashes emitted by CAS Remote Messages.
 *
 * Important:
 * Do NOT open the <details> manually before triggering the Doctor UI.
 * The native Doctor animation is attached to the parked summary/logo flow.
 * We therefore click the real Doctor summary first and use manual open only
 * as a late fallback.
 */
(function () {
  'use strict';

  function casRmScrollToDoctor(panel) {
    try {
      panel.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    } catch (e) {
      panel.scrollIntoView();
    }
  }

  function casRmDoctorHashFromHref(href) {
    if (!href) {
      return '';
    }

    if (href.indexOf('#custausu-section-installation-doctor') !== -1) {
      return '#custausu-section-installation-doctor';
    }

    if (href.indexOf('#cas-section-installation-doctor') !== -1) {
      return '#cas-section-installation-doctor';
    }

    return '';
  }

  function casRmDoctorSamePageHref(href) {
    var hash = casRmDoctorHashFromHref(href);

    if (!hash) {
      return false;
    }

    if (href === hash) {
      return true;
    }

    var current = window.location.href.split('#')[0];

    return href.indexOf(current + hash) === 0 ||
      href.indexOf(window.location.origin + window.location.pathname + hash) === 0;
  }

  function casRmOpenDoctorPanelWithNativeAnimation() {
    var panel = document.getElementById('custausu-section-installation-doctor');

    if (!panel) {
      return false;
    }

    var summary = panel.querySelector('summary.custausu-doctor-summary, summary');

    if (!summary) {
      casRmScrollToDoctor(panel);
      panel.open = true;
      return true;
    }

    /*
     * If already open, do not click again or we may close it.
     * Just scroll/focus.
     */
    if (panel.open) {
      casRmScrollToDoctor(panel);

      try {
        summary.focus({ preventScroll: true });
      } catch (e) {
        try {
          summary.focus();
        } catch (err) {}
      }

      return true;
    }

    /*
     * Trigger the same path as clicking the parked Doctor logo/summary.
     * This gives existing Doctor JS/CSS the chance to run the intended
     * flying/ghost/smooth-scroll animation.
     */
    try {
      summary.click();
    } catch (e) {
      try {
        summary.dispatchEvent(new MouseEvent('click', {
          bubbles: true,
          cancelable: true,
          view: window
        }));
      } catch (err) {}
    }

    /*
     * Fallback only. If the native Doctor animation/listener did not open
     * the panel, open it later and scroll. The delay avoids overriding the
     * intended animation choreography.
     */
    window.setTimeout(function () {
      if (!panel.open) {
        panel.open = true;
        casRmScrollToDoctor(panel);
      }
    }, 1400);

    return true;
  }

  document.addEventListener('click', function (event) {
    var link = event.target && event.target.closest
      ? event.target.closest('a[href="#custausu-section-installation-doctor"], a[href*="#custausu-section-installation-doctor"], a[href="#cas-section-installation-doctor"], a[href*="#cas-section-installation-doctor"]')
      : null;

    if (!link) {
      return;
    }

    var href = link.getAttribute('href') || '';

    if (!casRmDoctorSamePageHref(href)) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    casRmOpenDoctorPanelWithNativeAnimation();
  }, true);
})();

/* CAS RM — Dismiss modal + AJAX */
(function () {
  'use strict';

  function ensureModal() {
    var modal = document.querySelector('.custausu-rm-dismiss-modal');
    if (modal) return modal;

    modal = document.createElement('div');
    modal.className = 'custausu-rm-dismiss-modal';
    modal.innerHTML =
      '<div class="custausu-rm-dismiss-modal__panel" role="dialog" aria-modal="true">' +
        '<h3>Custom Auth Suite™</h3>' +
        '<p></p>' +
        '<div class="custausu-rm-dismiss-modal__actions">' +
          '<button type="button" class="button custausu-rm-dismiss-modal__cancel">Cancel</button>' +
          '<button type="button" class="button button-primary custausu-rm-dismiss-modal__confirm">Hide for 3 days</button>' +
        '</div>' +
      '</div>';

    document.body.appendChild(modal);
    return modal;
  }

  function openModal(message, onConfirm) {
    var modal = ensureModal();
    var text = modal.querySelector('p');
    var cancel = modal.querySelector('.custausu-rm-dismiss-modal__cancel');
    var confirm = modal.querySelector('.custausu-rm-dismiss-modal__confirm');

    text.textContent = message || '';
    modal.classList.add('is-open');

    function close() {
      modal.classList.remove('is-open');
      cancel.onclick = null;
      confirm.onclick = null;
      modal.onclick = null;
      document.removeEventListener('keydown', onKeydown, true);
    }

    function onKeydown(event) {
      if (event.key === 'Escape') {
        event.preventDefault();
        close();
      }
    }

    cancel.onclick = close;
    confirm.onclick = function () {
      close();
      onConfirm();
    };

    modal.onclick = function (event) {
      if (event.target === modal) {
        close();
      }
    };

    document.addEventListener('keydown', onKeydown, true);

    try {
      confirm.focus({ preventScroll: true });
    } catch (e) {
      try { confirm.focus(); } catch (err) {}
    }
  }

  function ajaxDismiss(form) {
    var data = new FormData(form);
    data.set('custausu_rm_ajax', '1');

    var endpoint = form.getAttribute('action') || '';

    return fetch(endpoint, {
      method: 'POST',
      credentials: 'same-origin',
      body: data,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(function (response) {
      if (!response.ok) throw new Error('Dismiss failed');
      return response.json();
    });
  }

  document.addEventListener('submit', function (event) {
    var form = event.target && event.target.closest
      ? event.target.closest('.custausu-rm-admin-top__dismiss[data-custausu-rm-dismiss-warning]')
      : null;

    if (!form) return;

    event.preventDefault();
    event.stopPropagation();
    var message = form.getAttribute('data-custausu-rm-dismiss-warning') || '';

    function submitNormally() {
      if (window.HTMLFormElement && HTMLFormElement.prototype && HTMLFormElement.prototype.submit) {
        HTMLFormElement.prototype.submit.call(form);
        return;
      }

      form.submit();
    }

    function runDismiss() {
      var wrapper = form.closest('.custausu-rm-admin-top-wrap');

      ajaxDismiss(form).then(function (payload) {
        if (!payload || !payload.success) {
          submitNormally();
          return;
        }


        if (wrapper) {
          var activeSlide = wrapper.querySelector('[data-custausu-rm-event-card="1"].is-active') ||
            wrapper.querySelector('[data-custausu-rm-event-card="1"]');

          if (activeSlide) {
            document.dispatchEvent(new CustomEvent('custausu-rm:dismissed', {
              detail: {
                card: activeSlide,
                mode: 'hide_placement'
              }
            }));
          }

          wrapper.remove();
        }
      }).catch(function () {
        submitNormally();
      });
    }

    if (message) {
      openModal(message, runDismiss);
    } else {
      runDismiss();
    }
  });
})();

/**
 * CAS RM image fallback guard — mobile/desktop aware.
 *
 * The server should already resolve missing WebP assets before sending the
 * catalog payload. This client guard handles cached payloads or runtime image
 * failures and chooses the proper PNG fallback for the current viewport.
 */
(function () {
  'use strict';

  if (window.custausuRmImageFallbackGuardReady) {
    return;
  }

  window.custausuRmImageFallbackGuardReady = true;

  function pngTwinFromWebp(url) {
    if (!url || typeof url !== 'string') {
      return '';
    }

    var parts = url.split('?');
    var clean = parts.shift();
    var query = parts.length ? '?' + parts.join('?') : '';

    if (!/\.webp$/i.test(clean)) {
      return '';
    }

    return clean.replace(/\.webp$/i, '.png') + query;
  }

  function isMobileViewport() {
    return window.matchMedia && window.matchMedia('(max-width: 782px)').matches;
  }

  function disablePictureSources(img) {
    var picture = img.closest ? img.closest('picture') : null;

    if (!picture) {
      return;
    }

    Array.prototype.slice.call(picture.querySelectorAll('source')).forEach(function (source) {
      source.setAttribute('data-custausu-rm-disabled-srcset', source.getAttribute('srcset') || '');
      source.removeAttribute('srcset');
    });
  }

  document.addEventListener('error', function (event) {
    var img = event.target;

    if (!img || !img.tagName || img.tagName.toLowerCase() !== 'img') {
      return;
    }

    if (!img.closest || !img.closest('.custausu-rm-placement, .custausu-rm-admin-top-wrap')) {
      return;
    }

    if (img.getAttribute('data-custausu-rm-fallback-tried') === '1') {
      return;
    }

    var mobileFallback = img.getAttribute('data-custausu-rm-fallback-mobile-src') || '';
    var desktopFallback = img.getAttribute('data-custausu-rm-fallback-desktop-src') || '';
    var genericFallback = img.getAttribute('data-custausu-rm-fallback-src') || '';
    var derivedFallback = pngTwinFromWebp(img.currentSrc || img.getAttribute('src') || '');

    var fallback = isMobileViewport()
      ? (mobileFallback || genericFallback || derivedFallback)
      : (desktopFallback || genericFallback || derivedFallback);

    if (!fallback || fallback === img.getAttribute('src')) {
      return;
    }

    img.setAttribute('data-custausu-rm-fallback-tried', '1');
    disablePictureSources(img);
    img.src = fallback;
  }, true);
})();

/* CAS RM event sender */
(function () {
  'use strict';

  if (window.custausuRmEventSenderReady) {
    return;
  }

  window.custausuRmEventSenderReady = true;

  var config = window.CUSTAUSU_RM_EVENTS || {};

  if (!config || !config.enabled || !config.endpoint) {
    return;
  }

  function safeText(value, max) {
    value = typeof value === 'string' ? value : '';
    value = value.replace(/\s+/g, ' ').trim();
    return value.length > max ? value.slice(0, max) : value;
  }

  function placementLabel(placement) {
    var labels = {
      admin_dashboard: 'Admin dashboard',
      doctor_summary: 'Doctor summary',
      doctor_support: 'Doctor support',
      doctor_feedback: 'Doctor feedback',
      review_notice: 'Review notice',
    };

    return labels[placement] || placement || 'Unknown placement';
  }

  function eventLabel(type) {
    var labels = {
      impression: 'Impression',
      dismiss: 'Dismiss',
      cta_click: 'CTA click'
    };

    return labels[type] || type || 'Event';
  }

  function safeCtaUrlForMetadata(url) {
    url = safeText(url, 500);

    if (!url) {
      return '';
    }

    if (url.charAt(0) === '#') {
      return url;
    }

    try {
      var parsed = new URL(url, window.location.origin);
      return parsed.origin + parsed.pathname;
    } catch (e) {
      return '';
    }
  }

  function closestCard(node) {
    return node && node.closest
      ? node.closest('[data-custausu-rm-event-card="1"]')
      : null;
  }

  function cardIsVisible(card) {
    if (!card) return false;

    if (card.getAttribute('aria-hidden') === 'true') {
      return false;
    }

    if (card.classList && card.classList.contains('custausu-rm-admin-top__slide') && !card.classList.contains('is-active')) {
      return false;
    }

    return true;
  }

  function cardPayload(card, eventType, extra) {
    var ds = card && card.dataset ? card.dataset : {};
    var placement = ds.custausuRmPlacement || '';
    var title = safeText(ds.custausuRmTitle || ds.custausuRmMessageId || 'Remote message', 180);
    var ctaLabel = safeText(ds.custausuRmCtaLabel || '', 100);

    return {
      event_type: eventType,
      message_id: safeText(ds.custausuRmMessageId || '', 120),
      placement: safeText(placement, 80),
      category: safeText(ds.custausuRmCategory || '', 60),
      message_role: safeText(ds.custausuRmMessageRole || '', 90),
      delivery_group: safeText(ds.custausuRmDeliveryGroup || '', 90),
      dismiss_hash: safeText(ds.custausuRmDismissHash || '', 64),
      site_hash: safeText(config.siteHash || '', 96),
      cas_plan: safeText(config.casPlan || '', 60),
      license_status: safeText(config.licenseStatus || '', 60),
      client_version: safeText(config.clientVersion || '', 40),
      source: safeText(config.source || 'cas_plugin_admin', 60),
      metadata: Object.assign({
        title: title,
        subtitle: safeText(ds.custausuRmSubtitle || '', 220),
        cta_label: ctaLabel,
        placement_label: placementLabel(placement),
        event_label: eventLabel(eventType),
        page: safeText(window.location.pathname || '', 180)
      }, extra || {})
    };
  }

  function storageKey(eventType, card) {
    var ds = card && card.dataset ? card.dataset : {};
    return [
      'cas_rm_event',
      eventType,
      ds.custausuRmPlacement || '',
      ds.custausuRmMessageId || '',
      ds.custausuRmDismissHash || ''
    ].join(':');
  }

  function alreadySent(eventType, card) {
    try {
      return window.sessionStorage && sessionStorage.getItem(storageKey(eventType, card)) === '1';
    } catch (e) {
      return false;
    }
  }

  function markSent(eventType, card) {
    try {
      if (window.sessionStorage) {
        sessionStorage.setItem(storageKey(eventType, card), '1');
      }
    } catch (e) {}
  }

  function sendEvent(eventType, card, extra, oncePerSession) {
    if (!card) return;

    if (oncePerSession && alreadySent(eventType, card)) {
      return;
    }

    var payload = {
      event: cardPayload(card, eventType, extra || {})
    };

    if (!payload.event.message_id) {
      return;
    }

    if (oncePerSession) {
      markSent(eventType, card);
    }

    try {
      fetch(config.endpoint, {
        method: 'POST',
        credentials: 'omit',
        keepalive: true,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      }).catch(function () {});
    } catch (e) {}
  }

  function trackImpression(card) {
    if (
      !card
      || card.getAttribute('data-custausu-rm-track-impression') === '0'
      || !cardIsVisible(card)
    ) {
      return;
    }

    sendEvent('impression', card, {}, true);
  }

  function initImpressions() {
    var cards = Array.prototype.slice.call(document.querySelectorAll('[data-custausu-rm-event-card="1"]'));

    if (!cards.length) {
      return;
    }

    if (!('IntersectionObserver' in window)) {
      cards.forEach(trackImpression);
      return;
    }

    var observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (!entry.isIntersecting || entry.intersectionRatio < 0.35) {
          return;
        }

        trackImpression(entry.target);

        if (!entry.target.classList || !entry.target.classList.contains('custausu-rm-admin-top__slide')) {
          observer.unobserve(entry.target);
        }
      });
    }, {
      threshold: [0.35]
    });

    cards.forEach(function (card) {
      observer.observe(card);
    });

    Array.prototype.slice.call(document.querySelectorAll('.custausu-rm-admin-top__slide')).forEach(function (slide) {
      if (!('MutationObserver' in window)) {
        return;
      }

      var mutationObserver = new MutationObserver(function () {
        trackImpression(slide);
      });

      mutationObserver.observe(slide, {
        attributes: true,
        attributeFilter: ['class', 'aria-hidden']
      });
    });
  }

  document.addEventListener('click', function (event) {
    var cta = event.target && event.target.closest
      ? event.target.closest('[data-custausu-rm-event-cta="1"]')
      : null;

    if (!cta) {
      return;
    }

    var card = closestCard(cta);

    sendEvent('cta_click', card, {
      action_id: safeText(
        cta.getAttribute('data-custausu-rm-action-id') || '',
        80
      ),
      cta_label: safeText(cta.textContent || '', 100),
      cta_url: safeCtaUrlForMetadata(cta.getAttribute('href') || '')
    }, false);
  }, true);

  document.addEventListener('custausu-rm:dismissed', function (event) {
    var detail = event.detail || {};
    var card = detail.card || null;

    sendEvent('dismiss', card, {
      dismiss_mode: safeText(detail.mode || 'hide_message', 60)
    }, false);
  });

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