(function initMyronInteractiveAtoms(global) {
  "use strict";

  var openLayerCount = 0;

  function onReady(callback) {
    if (global.document.readyState === "loading") {
      global.document.addEventListener("DOMContentLoaded", callback, { once: true });
      return;
    }

    callback();
  }

  function toArray(list) {
    return Array.prototype.slice.call(list || []);
  }

  function runSetup(name, setup) {
    try {
      setup();
    } catch (error) {
      if (global.console && typeof global.console.error === "function") {
        global.console.error("[MyronCMS] interactive atom setup failed: " + name, error);
      }
    }
  }

  function getFocusable(container) {
    return toArray(
      container.querySelectorAll(
        'a[href], area[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
      )
    ).filter(function filterHidden(node) {
      return !node.hasAttribute("hidden") && node.getAttribute("aria-hidden") !== "true";
    });
  }

  function syncBodyLock() {
    if (!global.document.body) {
      return;
    }

    global.document.body.style.overflow = openLayerCount > 0 ? "hidden" : "";
  }

  function rememberOpener(layer) {
    layer.__myronPreviousFocus = global.document.activeElement;
  }

  function restoreOpener(layer) {
    var opener = layer.__myronPreviousFocus;
    if (opener && typeof opener.focus === "function") {
      opener.focus();
    }
  }

  function openLayer(layer, backdrop) {
    if (!layer || layer.getAttribute("aria-hidden") === "false") {
      return;
    }

    rememberOpener(layer);
    layer.hidden = false;
    layer.setAttribute("aria-hidden", "false");
    if (backdrop) {
      backdrop.hidden = false;
      backdrop.setAttribute("aria-hidden", "false");
    }

    openLayerCount += 1;
    syncBodyLock();

    var focusable = getFocusable(layer);
    if (focusable.length > 0) {
      focusable[0].focus();
    } else if (typeof layer.focus === "function") {
      layer.focus();
    }
  }

  function closeLayer(layer, backdrop) {
    if (!layer || layer.getAttribute("aria-hidden") !== "false") {
      return;
    }

    layer.setAttribute("aria-hidden", "true");
    layer.hidden = true;
    if (backdrop) {
      backdrop.setAttribute("aria-hidden", "true");
      backdrop.hidden = true;
    }

    openLayerCount = Math.max(0, openLayerCount - 1);
    syncBodyLock();
    restoreOpener(layer);
  }

  function bindFocusTrap(layer, onEscape) {
    if (!layer) {
      return;
    }

    layer.addEventListener("keydown", function onLayerKeydown(event) {
      if (event.key === "Escape") {
        event.preventDefault();
        onEscape();
        return;
      }

      if (event.key !== "Tab") {
        return;
      }

      var focusable = getFocusable(layer);
      if (!focusable.length) {
        event.preventDefault();
        return;
      }

      var first = focusable[0];
      var last = focusable[focusable.length - 1];
      var active = global.document.activeElement;

      if (event.shiftKey && active === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && active === last) {
        event.preventDefault();
        first.focus();
      }
    });
  }

  function setupDialogs() {
    toArray(global.document.querySelectorAll("[data-myron-dialog]")).forEach(function bindDialog(dialog) {
      var dialogId = dialog.getAttribute("id");
      var backdrop = global.document.querySelector('[data-myron-dialog-backdrop="' + dialogId + '"]');

      function close() {
        closeLayer(dialog, backdrop);
      }

      bindFocusTrap(dialog, close);

      toArray(global.document.querySelectorAll('[data-myron-dialog-open="' + dialogId + '"]')).forEach(function bindOpen(button) {
        button.addEventListener("click", function onDialogOpen(event) {
          event.preventDefault();
          openLayer(dialog, backdrop);
        });
      });

      toArray(dialog.querySelectorAll("[data-myron-dialog-close]")).forEach(function bindClose(button) {
        button.addEventListener("click", function onDialogClose(event) {
          event.preventDefault();
          close();
        });
      });

      if (backdrop) {
        backdrop.addEventListener("click", close);
      }
    });
  }

  function setupDrawers() {
    toArray(global.document.querySelectorAll("[data-myron-drawer]")).forEach(function bindDrawer(drawer) {
      var drawerId = drawer.getAttribute("id");
      var backdrop = global.document.querySelector('[data-myron-drawer-backdrop="' + drawerId + '"]');

      function close() {
        closeLayer(drawer, backdrop);
      }

      bindFocusTrap(drawer, close);

      toArray(global.document.querySelectorAll('[data-myron-drawer-open="' + drawerId + '"]')).forEach(function bindOpen(button) {
        button.addEventListener("click", function onDrawerOpen(event) {
          event.preventDefault();
          openLayer(drawer, backdrop);
        });
      });

      toArray(drawer.querySelectorAll("[data-myron-drawer-close]")).forEach(function bindClose(button) {
        button.addEventListener("click", function onDrawerClose(event) {
          event.preventDefault();
          close();
        });
      });

      if (backdrop) {
        backdrop.addEventListener("click", close);
      }
    });
  }

  function setupDropdownMenus() {
    var roots = toArray(global.document.querySelectorAll("[data-myron-menu]"));
    if (!roots.length) {
      return;
    }

    function findContainingRoot(target) {
      var index;
      for (index = 0; index < roots.length; index += 1) {
        if (roots[index].contains(target)) {
          return roots[index];
        }
      }

      return null;
    }

    function closeAllMenus(exceptRoot) {
      roots.forEach(function closeMenu(root) {
        if (root === exceptRoot) {
          return;
        }

        var trigger = root.querySelector("[data-myron-menu-trigger]");
        var panel = root.querySelector("[data-myron-menu-panel]");
        if (!trigger || !panel) {
          return;
        }

        trigger.setAttribute("aria-expanded", "false");
        panel.hidden = true;
      });
    }

    roots.forEach(function bindMenu(root) {
      var trigger = root.querySelector("[data-myron-menu-trigger]");
      var panel = root.querySelector("[data-myron-menu-panel]");
      var items = toArray(root.querySelectorAll("[data-myron-menu-item]"));

      if (!trigger || !panel || !items.length) {
        return;
      }

      function setActive(index) {
        items.forEach(function updateItem(item, itemIndex) {
          item.classList.toggle("is-active", itemIndex === index);
        });
      }

      function open() {
        closeAllMenus(root);
        trigger.setAttribute("aria-expanded", "true");
        panel.hidden = false;
        setActive(0);
        items[0].focus();
      }

      function close(focusTrigger) {
        trigger.setAttribute("aria-expanded", "false");
        panel.hidden = true;
        items.forEach(function clear(item) {
          item.classList.remove("is-active");
        });
        if (focusTrigger) {
          trigger.focus();
        }
      }

      trigger.addEventListener("click", function onTriggerClick() {
        var expanded = trigger.getAttribute("aria-expanded") === "true";
        if (expanded) {
          close(false);
        } else {
          open();
        }
      });

      trigger.addEventListener("keydown", function onTriggerKeydown(event) {
        if (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          open();
        }
      });

      panel.addEventListener("keydown", function onPanelKeydown(event) {
        var activeIndex = -1;
        items.forEach(function findActive(item, itemIndex) {
          if (activeIndex === -1 && (item.classList.contains("is-active") || item === global.document.activeElement)) {
            activeIndex = itemIndex;
          }
        });

        if (event.key === "Escape") {
          event.preventDefault();
          close(true);
          return;
        }

        if (event.key === "ArrowDown") {
          event.preventDefault();
          activeIndex = activeIndex < 0 ? 0 : (activeIndex + 1) % items.length;
          setActive(activeIndex);
          items[activeIndex].focus();
          return;
        }

        if (event.key === "ArrowUp") {
          event.preventDefault();
          activeIndex = activeIndex < 0 ? items.length - 1 : (activeIndex - 1 + items.length) % items.length;
          setActive(activeIndex);
          items[activeIndex].focus();
          return;
        }

        if (event.key === "Home") {
          event.preventDefault();
          setActive(0);
          items[0].focus();
          return;
        }

        if (event.key === "End") {
          event.preventDefault();
          setActive(items.length - 1);
          items[items.length - 1].focus();
        }
      });

      items.forEach(function bindItem(item) {
        item.addEventListener("click", function onItemClick() {
          if (item.getAttribute("role") === "menuitemcheckbox") {
            var checked = item.getAttribute("aria-checked") === "true";
            item.setAttribute("aria-checked", checked ? "false" : "true");
          }

          close(true);
        });
      });
    });

    global.document.addEventListener("click", function onDocumentClick(event) {
      closeAllMenus(findContainingRoot(event.target));
    });
  }

  function setupCarousels() {
    toArray(global.document.querySelectorAll("[data-myron-carousel]")).forEach(function bindCarousel(root) {
      var track = root.querySelector("[data-myron-carousel-track]");
      var slides = toArray(root.querySelectorAll("[data-myron-carousel-slide]"));
      var dots = toArray(root.querySelectorAll("[data-myron-carousel-dot]"));
      var prev = root.querySelector("[data-myron-carousel-prev]");
      var next = root.querySelector("[data-myron-carousel-next]");
      var index = 0;
      var autoplayDelay = parseInt(root.getAttribute("data-myron-carousel-autoplay") || "", 10);
      var autoplayTimer = null;
      var isFade = root.classList.contains("myron-carousel--fade");
      var isPeek = root.classList.contains("myron-carousel--peek");

      if (!track || slides.length === 0) {
        return;
      }

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

        dots.forEach(function updateDot(dot, dotIndex) {
          dot.setAttribute("aria-current", dotIndex === index ? "true" : "false");
        });

        if (!isFade) {
          var basis = isPeek ? 88 : 100;
          track.style.transform = "translateX(" + (index * basis * -1) + "%)";
        }
      }

      function goTo(nextIndex) {
        index = (nextIndex + slides.length) % slides.length;
        update();
      }

      function restartAutoplay() {
        if (!autoplayDelay || autoplayDelay <= 0) {
          return;
        }

        global.clearInterval(autoplayTimer);
        autoplayTimer = global.setInterval(function autoAdvance() {
          goTo(index + 1);
        }, autoplayDelay);
      }

      if (prev) {
        prev.addEventListener("click", function onPrevClick() {
          goTo(index - 1);
          restartAutoplay();
        });
      }

      if (next) {
        next.addEventListener("click", function onNextClick() {
          goTo(index + 1);
          restartAutoplay();
        });
      }

      dots.forEach(function bindDot(dot, dotIndex) {
        dot.addEventListener("click", function onDotClick() {
          goTo(dotIndex);
          restartAutoplay();
        });
      });

      root.addEventListener("mouseenter", function onMouseEnter() {
        global.clearInterval(autoplayTimer);
      });

      root.addEventListener("mouseleave", restartAutoplay);

      update();
      restartAutoplay();
    });
  }

  function setupComboboxes() {
    toArray(global.document.querySelectorAll("[data-myron-combobox]")).forEach(function bindCombobox(root) {
      var input = root.querySelector("[data-myron-combobox-input]");
      var panel = root.querySelector("[data-myron-combobox-panel]");
      var trigger = root.querySelector("[data-myron-combobox-trigger]");
      var hiddenInput = root.querySelector("[data-myron-combobox-value]");
      var empty = root.querySelector("[data-myron-combobox-empty]");
      var options = toArray(root.querySelectorAll("[data-myron-combobox-option]"));
      var activeIndex = -1;

      if (!input || !panel || !trigger || !options.length) {
        return;
      }

      function visibleOptions() {
        return options.filter(function filterOption(option) {
          return !option.hidden;
        });
      }

      function open() {
        panel.hidden = false;
        trigger.setAttribute("aria-expanded", "true");
      }

      function close() {
        panel.hidden = true;
        trigger.setAttribute("aria-expanded", "false");
        activeIndex = -1;
        options.forEach(function clear(option) {
          option.classList.remove("is-active");
        });
      }

      function setActive(index) {
        var visible = visibleOptions();
        if (!visible.length) {
          activeIndex = -1;
          return;
        }

        activeIndex = Math.max(0, Math.min(index, visible.length - 1));
        options.forEach(function clear(option) {
          option.classList.remove("is-active");
        });
        visible[activeIndex].classList.add("is-active");
      }

      function syncFilter() {
        var term = (input.value || "").trim().toLowerCase();
        var visibleCount = 0;

        options.forEach(function updateOption(option) {
          var haystack = (option.getAttribute("data-search-text") || option.textContent || "").toLowerCase();
          var matches = term === "" || haystack.indexOf(term) !== -1;
          option.hidden = !matches;
          if (matches) {
            visibleCount += 1;
          }
        });

        if (empty) {
          empty.hidden = visibleCount !== 0;
        }

        setActive(0);
      }

      function commit(option) {
        var label = option.getAttribute("data-combobox-label") || option.textContent || "";
        var value = option.getAttribute("data-combobox-value") || label;
        input.value = label.replace(/\s+/g, " ").trim();
        if (hiddenInput) {
          hiddenInput.value = value;
        }
        options.forEach(function clear(optionNode) {
          optionNode.setAttribute("aria-selected", optionNode === option ? "true" : "false");
        });
        close();
      }

      trigger.addEventListener("click", function onTriggerClick() {
        if (panel.hidden) {
          open();
          syncFilter();
          input.focus();
        } else {
          close();
        }
      });

      input.addEventListener("focus", open);
      input.addEventListener("input", function onInput() {
        open();
        syncFilter();
      });

      input.addEventListener("keydown", function onKeydown(event) {
        var visible = visibleOptions();
        if (event.key === "ArrowDown") {
          event.preventDefault();
          open();
          setActive(activeIndex + 1);
        } else if (event.key === "ArrowUp") {
          event.preventDefault();
          open();
          setActive(activeIndex <= 0 ? visible.length - 1 : activeIndex - 1);
        } else if (event.key === "Enter" && activeIndex >= 0 && visible[activeIndex]) {
          event.preventDefault();
          commit(visible[activeIndex]);
        } else if (event.key === "Escape") {
          event.preventDefault();
          close();
        }
      });

      options.forEach(function bindOption(option) {
        option.addEventListener("mousedown", function onOptionMouseDown(event) {
          event.preventDefault();
        });
        option.addEventListener("click", function onOptionClick() {
          commit(option);
        });
      });

      global.document.addEventListener("click", function onDocumentClick(event) {
        if (!root.contains(event.target)) {
          close();
        }
      });

      syncFilter();
    });
  }

  function setupPickerToggles() {
    toArray(global.document.querySelectorAll("[data-myron-picker]")).forEach(function bindPicker(root) {
      var toggle = root.querySelector("[data-myron-picker-toggle]");
      var panel = root.querySelector("[data-myron-picker-panel]");

      if (!toggle || !panel) {
        return;
      }

      toggle.addEventListener("click", function onToggleClick(event) {
        event.preventDefault();
        var expanded = toggle.getAttribute("aria-expanded") === "true";
        toggle.setAttribute("aria-expanded", expanded ? "false" : "true");
        panel.hidden = expanded;
      });

      global.document.addEventListener("click", function onDocumentClick(event) {
        if (!root.contains(event.target)) {
          toggle.setAttribute("aria-expanded", "false");
          panel.hidden = true;
        }
      });
    });
  }

  function dismissToast(toast) {
    if (!toast || !toast.parentNode) {
      return;
    }

    toast.parentNode.removeChild(toast);
  }

  function setupToasts() {
    toArray(global.document.querySelectorAll("[data-myron-toast]")).forEach(function bindToast(toast) {
      var dismissButton = toast.querySelector("[data-myron-toast-dismiss]");
      var autoDismissMs = Number(toast.getAttribute("data-myron-auto-dismiss-ms") || "0");

      if (dismissButton) {
        dismissButton.addEventListener("click", function onDismiss() {
          dismissToast(toast);
        });
      }

      if (autoDismissMs > 0) {
        global.setTimeout(function onAutoDismiss() {
          dismissToast(toast);
        }, autoDismissMs);
      }
    });
  }

  function setupNewsletterSignups() {
    toArray(global.document.querySelectorAll("[data-myron-newsletter-signup]")).forEach(function bindNewsletter(root) {
      var form = root.matches("form") ? root : root.querySelector("form");
      var endpoint = root.getAttribute("data-myron-newsletter-endpoint");
      var email = form ? form.querySelector('input[type="email"]') : null;
      var message = root.querySelector("[data-myron-newsletter-message]");

      if (!form || !endpoint) {
        return;
      }

      form.addEventListener("submit", function onNewsletterSubmit(event) {
        if (email && !email.checkValidity()) {
          root.setAttribute("data-state", "error");
          return;
        }

        event.preventDefault();
        root.setAttribute("data-state", "submitting");
        if (message) {
          message.textContent = "";
        }

        global.fetch(endpoint, {
          method: form.getAttribute("method") || "POST",
          body: new global.FormData(form),
          credentials: "same-origin"
        }).then(function onResponse(response) {
          root.setAttribute("data-state", response.ok ? "success" : "error");
          if (message) {
            message.textContent = response.ok ? "Subscription saved." : "Subscription could not be saved.";
          }
        }).catch(function onError() {
          root.setAttribute("data-state", "error");
          if (message) {
            message.textContent = "Subscription could not be saved.";
          }
        });
      });
    });
  }

  function bindAsyncForm(root, endpointAttribute, messageSelector, successText, errorText) {
    var form = root.matches("form") ? root : root.querySelector("form");
    var endpoint = root.getAttribute(endpointAttribute);
    var message = root.querySelector(messageSelector);

    if (!form || !endpoint) {
      return;
    }

    form.addEventListener("submit", function onAsyncSubmit(event) {
      if (!form.checkValidity()) {
        root.setAttribute("data-state", "error");
        return;
      }

      event.preventDefault();
      root.setAttribute("data-state", "submitting");
      if (message) {
        message.textContent = "";
      }

      global.fetch(endpoint, {
        method: form.getAttribute("method") || "POST",
        body: new global.FormData(form),
        credentials: "same-origin"
      }).then(function onResponse(response) {
        root.setAttribute("data-state", response.ok ? "success" : "error");
        if (message) {
          message.textContent = response.ok ? successText : errorText;
        }
      }).catch(function onError() {
        root.setAttribute("data-state", "error");
        if (message) {
          message.textContent = errorText;
        }
      });
    });
  }

  function setupContactForms() {
    toArray(global.document.querySelectorAll("[data-myron-contact-form]")).forEach(function bindContact(root) {
      bindAsyncForm(
        root,
        "data-myron-contact-endpoint",
        "[data-myron-contact-message]",
        "Message sent.",
        "Message could not be sent."
      );
    });
  }

  function setupLeadMagnetCards() {
    toArray(global.document.querySelectorAll("[data-myron-lead-magnet-card]")).forEach(function bindLeadMagnet(root) {
      bindAsyncForm(
        root,
        "data-myron-lead-magnet-endpoint",
        "[data-myron-lead-magnet-message]",
        "Resource request saved.",
        "Resource request could not be saved."
      );
    });
  }

  function responseMessage(payload, fallback) {
    if (payload && typeof payload.message === "string" && payload.message.trim() !== "") {
      return payload.message;
    }
    if (payload && payload.errors && typeof payload.errors === "object") {
      var keys = Object.keys(payload.errors);
      if (keys.length) {
        return String(payload.errors[keys[0]] || fallback);
      }
    }
    return fallback;
  }

  function closeContainingDialog(form) {
    var dialog = form && form.closest ? form.closest("dialog") : null;
    if (dialog && typeof dialog.close === "function") {
      dialog.close();
    }
  }

  function preparePublicInteractionToken(form) {
    var input = form && form.querySelector ? form.querySelector("[data-public-interaction-token]") : null;
    if (!input) {
      return global.Promise.resolve();
    }

    var endpoint = input.getAttribute("data-public-interaction-endpoint") || "/api/v1/public-interactions/token";
    var purpose = input.getAttribute("data-public-interaction-purpose") || "";
    var resource = input.getAttribute("data-public-interaction-resource") || "";
    var separator = endpoint.indexOf("?") === -1 ? "?" : "&";
    var url = endpoint + separator + "purpose=" + encodeURIComponent(purpose) + "&resource=" + encodeURIComponent(resource);

    return global.fetch(url, {
      method: "GET",
      credentials: "same-origin",
      cache: "no-store",
      headers: { Accept: "application/json" }
    }).then(function onTokenResponse(response) {
      return response.json().catch(function fallbackJson() { return {}; }).then(function withTokenPayload(payload) {
        if (!response.ok || payload.success === false || typeof payload.token !== "string" || payload.token === "") {
          throw new Error("Public interaction token unavailable.");
        }
        input.value = payload.token;
      });
    });
  }

  function setupMicForms() {
    toArray(global.document.querySelectorAll("form[data-myron-mic-form]")).forEach(function bindMicForm(form) {
      var message = form.querySelector("[data-myron-form-message]");
      var fallbackSuccess = form.getAttribute("data-success-message") || "Thanks for submitting.";
      var fallbackError = "Submission could not be saved.";

      form.addEventListener("submit", function onMicFormSubmit(event) {
        if (!form.checkValidity()) {
          form.setAttribute("data-state", "error");
          return;
        }

        event.preventDefault();
        form.setAttribute("data-state", "submitting");
        if (message) {
          message.textContent = "";
        }

        preparePublicInteractionToken(form).then(function submitMicForm() {
          return global.fetch(form.action, {
          method: form.getAttribute("method") || "POST",
          body: new global.FormData(form),
          credentials: "same-origin",
          headers: { Accept: "application/json" }
          });
        }).then(function onResponse(response) {
          return response.json().catch(function fallbackJson() { return {}; }).then(function withPayload(payload) {
            if (!response.ok || payload.success === false) {
              form.setAttribute("data-state", "error");
              if (message) {
                message.textContent = responseMessage(payload, fallbackError);
              }
              return;
            }

            form.setAttribute("data-state", "success");
            if (message) {
              message.textContent = responseMessage(payload, fallbackSuccess);
            }

            var redirectUrl = payload.redirect_url || "";
            if (payload.success_strategy === "redirect" && redirectUrl) {
              global.location.href = redirectUrl;
              return;
            }
            if (payload.success_strategy === "modal-close") {
              closeContainingDialog(form);
            }
            form.reset();
          });
        }).catch(function onError() {
          form.setAttribute("data-state", "error");
          if (message) {
            message.textContent = fallbackError;
          }
        });
      });
    });
  }

  var steppedQuizInstanceCount = 0;

  function setupSteppedQuizPlayers() {
    if (!("IntersectionObserver" in global)) {
      return;
    }

    toArray(global.document.querySelectorAll('[data-quiz-presentation="stepped"]')).forEach(function bindSteppedQuiz(root) {
      if (root.__myronSteppedQuizBound) {
        return;
      }

      var form = root.querySelector("form[data-quiz-player]");
      var items = toArray(root.querySelectorAll("[data-quiz-item]"));
      var submitButton = form ? form.querySelector("[data-quiz-submit]") : null;
      if (!form || !submitButton || !items.length) {
        return;
      }

      var instanceId = steppedQuizInstanceCount += 1;
      var createdNodes = [];
      var index = 0;
      var started = false;
      var failedOpen = false;
      var progress;
      var intro;
      var startButton;
      var navigation;
      var previousButton;
      var nextButton;
      var errors = [];

      function removeNode(node) {
        if (!node) {
          return;
        }
        if (typeof node.remove === "function") {
          node.remove();
        } else if (node.parentNode) {
          node.parentNode.removeChild(node);
        }
      }

      function failOpen(error) {
        failedOpen = true;
        root.removeAttribute("data-quiz-enhanced");
        root.removeAttribute("data-quiz-started");
        root.removeAttribute("data-quiz-final");
        root.removeAttribute("data-quiz-current-step");
        items.forEach(function revealItem(item) {
          item.hidden = false;
          item.removeAttribute("data-quiz-active");
          item.removeAttribute("aria-describedby");
        });
        submitButton.hidden = false;
        if (intro) {
          intro.hidden = false;
        }
        createdNodes.forEach(removeNode);
        if (global.console && typeof global.console.error === "function") {
          global.console.error("[MyronCMS] stepped quiz enhancement failed open", error);
        }
      }

      function guarded(callback) {
        return function runGuarded(event) {
          if (failedOpen) {
            return;
          }
          try {
            callback(event);
          } catch (error) {
            failOpen(error);
          }
        };
      }

      function answered(item) {
        var controls = toArray(item.querySelectorAll('input:not([type="hidden"]), select, textarea'));
        if (!controls.length) {
          return false;
        }

        return controls.some(function controlHasValue(control) {
          var type = (control.getAttribute("type") || "").toLowerCase();
          if (type === "radio" || type === "checkbox") {
            return control.checked === true;
          }
          return String(control.value || "").trim() !== "";
        });
      }

      function clearError(itemIndex) {
        var error = errors[itemIndex];
        if (error) {
          error.hidden = true;
        }
        items[itemIndex].removeAttribute("data-quiz-invalid");
      }

      function validate(itemIndex) {
        var item = items[itemIndex];
        if (item.getAttribute("data-quiz-required") !== "true" || answered(item)) {
          clearError(itemIndex);
          return true;
        }

        item.setAttribute("data-quiz-invalid", "true");
        errors[itemIndex].hidden = false;
        var firstControl = item.querySelector('input:not([type="hidden"]), select, textarea');
        if (firstControl && typeof firstControl.focus === "function") {
          firstControl.focus();
        }
        return false;
      }

      function focusCurrent() {
        var item = items[index];
        item.setAttribute("tabindex", "-1");
        if (typeof item.focus === "function") {
          item.focus();
        }
      }

      function sync() {
        var isFinal = started && index === items.length - 1;
        root.setAttribute("data-quiz-started", started ? "true" : "false");
        root.setAttribute("data-quiz-final", isFinal ? "true" : "false");
        root.setAttribute("data-quiz-current-step", started ? String(index + 1) : "0");

        intro.hidden = started;
        progress.hidden = !started;
        navigation.hidden = !started;
        previousButton.disabled = !started || index === 0;
        nextButton.hidden = !started || isFinal;
        submitButton.hidden = !isFinal;
        progress.textContent = started ? "Question " + String(index + 1) + " of " + String(items.length) : "";

        items.forEach(function syncItem(item, itemIndex) {
          var active = started && itemIndex === index;
          item.hidden = !active;
          if (active) {
            item.setAttribute("data-quiz-active", "true");
          } else {
            item.removeAttribute("data-quiz-active");
          }
        });
      }

      try {
        intro = global.document.createElement("div");
        intro.className = "myron-quiz__intro";
        intro.hidden = true;
        intro.setAttribute("data-quiz-intro", "");
        intro.setAttribute("data-quiz-stepped-ui", "");

        var introText = root.getAttribute("data-quiz-intro-text") || "";
        if (introText !== "") {
          var introCopy = global.document.createElement("p");
          introCopy.className = "myron-quiz__intro-copy";
          introCopy.textContent = introText;
          intro.appendChild(introCopy);
        }

        startButton = global.document.createElement("button");
        startButton.className = "myron-quiz__button";
        startButton.type = "button";
        startButton.textContent = "Start";
        startButton.setAttribute("data-quiz-start", "");
        startButton.setAttribute("data-quiz-stepped-ui", "");
        intro.appendChild(startButton);
        root.insertBefore(intro, form);
        createdNodes.push(intro);

        progress = global.document.createElement("span");
        progress.className = "myron-quiz__progress";
        progress.hidden = true;
        progress.setAttribute("role", "status");
        progress.setAttribute("aria-live", "polite");
        progress.setAttribute("aria-atomic", "true");
        progress.setAttribute("data-quiz-progress", "");
        progress.setAttribute("data-quiz-stepped-ui", "");
        root.querySelector(".myron-quiz__header").appendChild(progress);
        createdNodes.push(progress);

        navigation = global.document.createElement("div");
        navigation.className = "myron-quiz__navigation";
        navigation.hidden = true;
        navigation.setAttribute("data-quiz-navigation", "");
        navigation.setAttribute("data-quiz-stepped-ui", "");

        previousButton = global.document.createElement("button");
        previousButton.className = "myron-quiz__button myron-quiz__button--secondary";
        previousButton.type = "button";
        previousButton.textContent = "Previous";
        previousButton.setAttribute("data-quiz-previous", "");

        nextButton = global.document.createElement("button");
        nextButton.className = "myron-quiz__button";
        nextButton.type = "button";
        nextButton.textContent = "Next";
        nextButton.setAttribute("data-quiz-next", "");

        navigation.appendChild(previousButton);
        navigation.appendChild(nextButton);
        form.insertBefore(navigation, submitButton);
        createdNodes.push(navigation);

        items.forEach(function prepareItem(item, itemIndex) {
          var error = global.document.createElement("p");
          var errorId = "myron-quiz-step-error-" + String(instanceId) + "-" + String(itemIndex + 1);
          error.className = "myron-quiz__step-error";
          error.id = errorId;
          error.hidden = true;
          error.setAttribute("role", "alert");
          error.setAttribute("data-quiz-step-error", "");
          error.textContent = "Please answer this question before continuing.";
          item.appendChild(error);
          item.setAttribute("aria-describedby", errorId);
          createdNodes.push(error);
          errors.push(error);

          toArray(item.querySelectorAll('input:not([type="hidden"]), select, textarea')).forEach(function bindClear(control) {
            control.addEventListener("input", guarded(function clearOnInput() { clearError(itemIndex); }));
            control.addEventListener("change", guarded(function clearOnChange() { clearError(itemIndex); }));
          });
        });

        startButton.addEventListener("click", guarded(function startQuiz() {
          started = true;
          index = 0;
          sync();
          focusCurrent();
        }));

        previousButton.addEventListener("click", guarded(function previousQuestion() {
          if (index === 0) {
            return;
          }
          clearError(index);
          index -= 1;
          sync();
          focusCurrent();
        }));

        nextButton.addEventListener("click", guarded(function nextQuestion() {
          if (!validate(index)) {
            return;
          }
          if (index < items.length - 1) {
            index += 1;
            sync();
            focusCurrent();
          }
        }));

        form.addEventListener("submit", guarded(function validateFinalStep(event) {
          if (!started || index !== items.length - 1 || validate(index)) {
            return;
          }
          event.preventDefault();
          if (typeof event.stopImmediatePropagation === "function") {
            event.stopImmediatePropagation();
          }
        }));

        root.setAttribute("data-quiz-enhanced", "true");
        sync();
        root.__myronSteppedQuizBound = true;
      } catch (error) {
        failOpen(error);
      }
    });
  }

  function setupQuizPlayers() {
    toArray(global.document.querySelectorAll("form[data-quiz-player]")).forEach(function bindQuizPlayer(form) {
      if (form.__myronQuizBound) {
        return;
      }
      form.__myronQuizBound = true;

      form.addEventListener("submit", function onQuizSubmit(event) {
        if (!form.checkValidity()) {
          form.setAttribute("data-state", "error");
          return;
        }

        event.preventDefault();
        var root = form.closest ? form.closest(".myron-quiz") : null;
        var endpoint = form.getAttribute("data-quiz-endpoint") || form.action || "";
        var submitButton = form.querySelector('[type="submit"]');
        var fallbackError = "Unable to submit this quiz. Please review your answers and try again.";

        form.setAttribute("data-state", "submitting");
        if (root) {
          root.setAttribute("data-state", "submitting");
        }
        if (submitButton) {
          submitButton.disabled = true;
        }

        preparePublicInteractionToken(form).then(function submitQuiz() {
          return global.fetch(endpoint, {
          method: form.getAttribute("method") || "POST",
          body: new global.FormData(form),
          credentials: "same-origin",
          headers: { Accept: "application/json" }
          });
        }).then(function onResponse(response) {
          return response.json().catch(function fallbackJson() { return {}; }).then(function withPayload(payload) {
            if (!response.ok || payload.success === false || typeof payload.resultHtml !== "string") {
              form.setAttribute("data-state", "error");
              if (root) {
                root.setAttribute("data-state", "error");
              }
              var message = responseMessage(payload, fallbackError);
              var error = form.querySelector("[data-quiz-error]");
              if (!error) {
                error = global.document.createElement("div");
                error.className = "myron-quiz__error";
                error.setAttribute("role", "alert");
                error.setAttribute("data-quiz-error", "");
                form.prepend(error);
              }
              error.textContent = message;
              if (submitButton) {
                submitButton.disabled = false;
              }
              return;
            }

            if (root) {
              root.setAttribute("data-state", "complete");
              root.innerHTML = payload.resultHtml;
            } else {
              form.insertAdjacentHTML("afterend", payload.resultHtml);
              form.remove();
            }
          });
        }).catch(function onError() {
          form.setAttribute("data-state", "error");
          if (root) {
            root.setAttribute("data-state", "error");
          }
          var error = form.querySelector("[data-quiz-error]");
          if (!error) {
            error = global.document.createElement("div");
            error.className = "myron-quiz__error";
            error.setAttribute("role", "alert");
            error.setAttribute("data-quiz-error", "");
            form.prepend(error);
          }
          error.textContent = fallbackError;
          if (submitButton) {
            submitButton.disabled = false;
          }
        });
      });
    });
  }

  function setupLegalDocTocs() {
    if (!("IntersectionObserver" in global)) {
      return;
    }

    toArray(global.document.querySelectorAll("[data-myron-legal-doc-toc]")).forEach(function bindLegalToc(root) {
      var links = toArray(root.querySelectorAll('a[href^="#"]'));
      var targets = links.map(function findTarget(link) {
        return global.document.getElementById((link.getAttribute("href") || "").slice(1));
      }).filter(Boolean);

      if (!targets.length) {
        return;
      }

      var observer = new global.IntersectionObserver(function onIntersect(entries) {
        entries.forEach(function syncEntry(entry) {
          if (!entry.isIntersecting) {
            return;
          }
          links.forEach(function syncLink(link) {
            var isCurrent = link.getAttribute("href") === "#" + entry.target.id;
            if (isCurrent) {
              link.setAttribute("aria-current", "location");
            } else {
              link.removeAttribute("aria-current");
            }
          });
        });
      }, { rootMargin: "-20% 0px -65% 0px" });

      targets.forEach(function observeTarget(target) {
        observer.observe(target);
      });
    });
  }

  function setupTierComparisonMatrices() {
    toArray(global.document.querySelectorAll("[data-myron-tier-comparison]")).forEach(function bindTierMatrix(root) {
      toArray(root.querySelectorAll("[data-myron-billing-period]")).forEach(function bindBilling(input) {
        input.addEventListener("change", function onBillingChange() {
          if (input.checked || input.tagName === "BUTTON") {
            root.setAttribute("data-billing-period", input.getAttribute("data-myron-billing-period") || "");
          }
        });
      });
    });
  }

  function setupPublicArchiveFilters() {
    toArray(global.document.querySelectorAll("[data-myron-public-archive-filter]")).forEach(function bindArchiveFilter(root) {
      var scope = root.getAttribute("data-myron-public-filter-scope") || "";
      var groups = toArray(root.querySelectorAll("[data-myron-public-filter-group]"));
      var count = root.querySelector("[data-myron-public-filter-count]");
      var rows = toArray(global.document.querySelectorAll("[data-myron-public-filter-row]")).filter(function inScope(row) {
        return !scope || (row.getAttribute("data-myron-public-filter-scope") || "") === scope;
      });
      var emptyStates = toArray(global.document.querySelectorAll("[data-myron-public-filter-empty]")).filter(function inScope(empty) {
        return !scope || (empty.getAttribute("data-myron-public-filter-scope") || "") === scope;
      });

      if (!groups.length || !rows.length) {
        return;
      }

      function valuesForRow(row, param) {
        return (row.getAttribute("data-filter-" + param) || "")
          .split("||")
          .map(function normalize(value) {
            return value.trim();
          })
          .filter(Boolean);
      }

      function selectedValues(group) {
        return toArray(group.querySelectorAll("[data-myron-public-filter-value]"))
          .filter(function selected(button) {
            return button.getAttribute("aria-pressed") === "true";
          })
          .map(function value(button) {
            return button.getAttribute("data-myron-public-filter-value") || "";
          })
          .filter(Boolean);
      }

      function readSelections() {
        return groups.map(function groupSelection(group) {
          return {
            group: group,
            param: group.getAttribute("data-myron-public-filter-param") || "",
            values: selectedValues(group)
          };
        }).filter(function hasParam(selection) {
          return selection.param !== "";
        });
      }

      function rowMatches(row, selections) {
        return selections.every(function matches(selection) {
          if (!selection.values.length) {
            return true;
          }

          var rowValues = valuesForRow(row, selection.param);
          return selection.values.some(function contains(value) {
            return rowValues.indexOf(value) !== -1;
          });
        });
      }

      function syncButtons(group) {
        var selected = selectedValues(group);
        var all = group.querySelector("[data-myron-public-filter-all]");
        if (all) {
          all.setAttribute("aria-pressed", selected.length ? "false" : "true");
          all.classList.toggle("myron-product-filters__option--active", selected.length === 0);
        }

        toArray(group.querySelectorAll("[data-myron-public-filter-value]")).forEach(function syncValue(button) {
          var isSelected = button.getAttribute("aria-pressed") === "true";
          button.classList.toggle("myron-product-filters__option--active", isSelected);
        });
      }

      function updateUrl(selections) {
        if (!global.history || typeof global.history.replaceState !== "function") {
          return;
        }

        var url = new URL(global.location.href);
        selections.forEach(function syncParam(selection) {
          url.searchParams.delete(selection.param);
          if (selection.values.length) {
            url.searchParams.set(selection.param, selection.values.join(","));
          }
        });
        global.history.replaceState({}, "", url.toString());
      }

      function updateCount(visibleCount) {
        if (!count) {
          return;
        }

        count.textContent = visibleCount + " " + (visibleCount === 1 ? "post" : "posts");
      }

      function apply(syncUrl) {
        var selections = readSelections();
        var hasSelection = selections.some(function hasValue(selection) {
          return selection.values.length > 0;
        });
        var visibleCount = 0;

        rows.forEach(function syncRow(row) {
          var visible = rowMatches(row, selections);
          row.hidden = !visible;
          if (visible) {
            visibleCount += 1;
          }
        });

        emptyStates.forEach(function syncEmpty(empty) {
          empty.hidden = !(hasSelection && visibleCount === 0);
        });

        groups.forEach(syncButtons);
        updateCount(visibleCount);
        root.setAttribute("data-state", hasSelection ? "filtered" : "all");
        if (syncUrl) {
          updateUrl(selections);
        }
      }

      groups.forEach(function bindGroup(group) {
        var param = group.getAttribute("data-myron-public-filter-param") || "";
        var url = new URL(global.location.href);
        var restored = [];
        url.searchParams.getAll(param).forEach(function collect(raw) {
          String(raw || "").split(",").forEach(function split(value) {
            var normalized = value.trim();
            if (normalized && restored.indexOf(normalized) === -1) {
              restored.push(normalized);
            }
          });
        });

        if (restored.length) {
          toArray(group.querySelectorAll("[data-myron-public-filter-value]")).forEach(function restore(button) {
            var value = button.getAttribute("data-myron-public-filter-value") || "";
            button.setAttribute("aria-pressed", restored.indexOf(value) !== -1 ? "true" : "false");
          });
        }

        toArray(group.querySelectorAll("[data-myron-public-filter-all]")).forEach(function bindAll(button) {
          button.addEventListener("click", function onAllClick() {
            toArray(group.querySelectorAll("[data-myron-public-filter-value]")).forEach(function clear(valueButton) {
              valueButton.setAttribute("aria-pressed", "false");
            });
            apply(true);
          });
        });

        toArray(group.querySelectorAll("[data-myron-public-filter-value]")).forEach(function bindValue(button) {
          button.addEventListener("click", function onValueClick() {
            var selected = button.getAttribute("aria-pressed") === "true";
            toArray(group.querySelectorAll("[data-myron-public-filter-value]")).forEach(function clear(valueButton) {
              valueButton.setAttribute("aria-pressed", "false");
            });
            button.setAttribute("aria-pressed", selected ? "false" : "true");
            apply(true);
          });
        });

        syncButtons(group);
      });

      apply(false);
    });
  }

  function setupCartTables() {
    toArray(global.document.querySelectorAll("[data-myron-cart-table]")).forEach(function bindCart(root) {
      var timer = null;

      toArray(root.querySelectorAll("[data-myron-cart-quantity]")).forEach(function bindQuantity(input) {
        input.addEventListener("input", function onQuantityInput() {
          root.setAttribute("data-state", "updating");
          if (timer) {
            global.clearTimeout(timer);
          }
          timer = global.setTimeout(function onQuantitySettled() {
            root.setAttribute("data-state", "default");
          }, 450);
        });
      });
    });
  }

  function setupCommerceCarts() {
    var storageKey = "myron.ecom.cart.v1";
    var memoryCart = [];

    function getStorage() {
      try {
        return global.localStorage || null;
      } catch (error) {
        return null;
      }
    }

    function readCart() {
      var storage = getStorage();
      if (!storage) {
        return memoryCart.slice();
      }

      try {
        var parsed = JSON.parse(storage.getItem(storageKey) || "[]");
        if (!Array.isArray(parsed)) {
          return [];
        }

        return parsed.map(normalizeLine).filter(Boolean);
      } catch (error) {
        return [];
      }
    }

    function writeCart(lines) {
      var normalized = lines.map(normalizeLine).filter(Boolean);
      var storage = getStorage();
      memoryCart = normalized.slice();

      if (!storage) {
        return;
      }

      try {
        storage.setItem(storageKey, JSON.stringify(normalized));
      } catch (error) {
        memoryCart = normalized.slice();
      }
    }

    function normalizeLine(line) {
      if (!line || !line.id) {
        return null;
      }

      var quantity = Math.max(0, parseInt(line.quantity, 10) || 0);
      if (quantity < 1) {
        return null;
      }

      return {
        id: String(line.id),
        title: String(line.title || "Product"),
        url: String(line.url || ""),
        unitPriceCents: Math.max(0, parseInt(line.unitPriceCents, 10) || 0),
        priceLabel: String(line.priceLabel || ""),
        quantity: quantity
      };
    }

    function formatMoney(cents) {
      var normalized = Math.max(0, parseInt(cents, 10) || 0);
      if (global.Intl && typeof global.Intl.NumberFormat === "function") {
        return new global.Intl.NumberFormat("en-US", {
          style: "currency",
          currency: "USD"
        }).format(normalized / 100);
      }

      return "$" + (normalized / 100).toFixed(2);
    }

    function productFromTrigger(trigger) {
      return normalizeLine({
        id: trigger.getAttribute("data-myron-product-id") || "",
        title: trigger.getAttribute("data-myron-product-title") || "",
        url: trigger.getAttribute("data-myron-product-url") || "",
        unitPriceCents: trigger.getAttribute("data-myron-product-price-cents") || "0",
        priceLabel: trigger.getAttribute("data-myron-product-price-label") || "",
        quantity: trigger.getAttribute("data-myron-product-quantity") || "1"
      });
    }

    function subtotalFor(lines) {
      return lines.reduce(function sum(total, line) {
        return total + (line.unitPriceCents * line.quantity);
      }, 0);
    }

    function addLine(product) {
      if (!product) {
        return;
      }

      var lines = readCart();
      var existing = lines.find(function findLine(line) {
        return line.id === product.id;
      });

      if (existing) {
        existing.quantity += product.quantity;
      } else {
        lines.push(product);
      }

      writeCart(lines);
      renderAllCarts();
    }

    function updateQuantity(productId, quantity) {
      var nextQuantity = Math.max(0, parseInt(quantity, 10) || 0);
      var lines = readCart().map(function updateLine(line) {
        if (line.id === productId) {
          line.quantity = nextQuantity;
        }
        return line;
      }).filter(function removeEmpty(line) {
        return line.quantity > 0;
      });

      writeCart(lines);
      renderAllCarts();
    }

    function renderLine(line, rootMode) {
      var article = global.document.createElement("article");
      var thumb = global.document.createElement("span");
      var body = global.document.createElement("span");
      var title = line.url ? global.document.createElement("a") : global.document.createElement("strong");
      var quantity = global.document.createElement("span");
      var lineTotal = global.document.createElement("span");

      article.className = "myron-cart-summary__item";
      article.setAttribute("data-myron-cart-line", line.id);
      thumb.className = "myron-cart-summary__thumb";
      thumb.setAttribute("aria-hidden", "true");

      if (line.url) {
        title.className = "myron-link";
        title.setAttribute("href", line.url);
      }
      title.textContent = line.title;

      quantity.className = "myron-text myron-text--muted";
      if (rootMode === "checkout") {
        quantity.textContent = "Quantity " + line.quantity;
      } else {
        var input = global.document.createElement("input");
        input.className = "myron-cart-summary__quantity";
        input.type = "number";
        input.min = "0";
        input.step = "1";
        input.value = String(line.quantity);
        input.setAttribute("aria-label", "Quantity for " + line.title);
        input.setAttribute("data-myron-cart-quantity", line.id);
        quantity.textContent = "Quantity ";
        quantity.appendChild(input);
      }

      lineTotal.textContent = formatMoney(line.unitPriceCents * line.quantity);
      body.appendChild(title);
      body.appendChild(quantity);
      article.appendChild(thumb);
      article.appendChild(body);
      article.appendChild(lineTotal);

      return article;
    }

    function renderCart(root, lines) {
      var mode = root.getAttribute("data-myron-commerce-cart") || "cart";
      var items = root.querySelector("[data-myron-cart-items]");
      var subtotal = subtotalFor(lines);

      root.setAttribute("data-state", lines.length > 0 ? "populated" : "empty");

      if (items) {
        items.textContent = "";
        if (lines.length === 0) {
          var empty = global.document.createElement("p");
          empty.className = "myron-cart-summary__empty";
          empty.setAttribute("data-myron-cart-empty", "");
          empty.textContent = "Your cart is empty.";
          items.appendChild(empty);
        } else {
          lines.forEach(function appendLine(line) {
            items.appendChild(renderLine(line, mode));
          });
        }
      }

      toArray(root.querySelectorAll("[data-myron-cart-subtotal]")).forEach(function updateSubtotal(target) {
        target.textContent = formatMoney(subtotal);
      });

      toArray(root.querySelectorAll("[data-myron-cart-total]")).forEach(function updateTotal(target) {
        target.textContent = formatMoney(subtotal);
      });
    }

    function renderAllCarts() {
      var lines = readCart();
      toArray(global.document.querySelectorAll("[data-myron-commerce-cart]")).forEach(function renderRoot(root) {
        renderCart(root, lines);
      });
    }

    global.document.addEventListener("click", function onCartAdd(event) {
      var trigger = event.target && event.target.closest ? event.target.closest("[data-myron-cart-add]") : null;
      if (!trigger) {
        return;
      }

      event.preventDefault();
      addLine(productFromTrigger(trigger));
      trigger.setAttribute("data-state", "added");
    });

    global.document.addEventListener("input", function onCartQuantity(event) {
      var input = event.target && event.target.matches && event.target.matches("[data-myron-cart-quantity]") ? event.target : null;
      if (!input) {
        return;
      }

      updateQuantity(input.getAttribute("data-myron-cart-quantity") || "", input.value);
    });

    renderAllCarts();
  }

  function setupInteractiveAtoms() {
    [
      ["setupDialogs", setupDialogs],
      ["setupDrawers", setupDrawers],
      ["setupDropdownMenus", setupDropdownMenus],
      ["setupCarousels", setupCarousels],
      ["setupComboboxes", setupComboboxes],
      ["setupPickerToggles", setupPickerToggles],
      ["setupToasts", setupToasts],
      ["setupNewsletterSignups", setupNewsletterSignups],
      ["setupContactForms", setupContactForms],
      ["setupLeadMagnetCards", setupLeadMagnetCards],
      ["setupMicForms", setupMicForms],
      ["setupSteppedQuizPlayers", setupSteppedQuizPlayers],
      ["setupQuizPlayers", setupQuizPlayers],
      ["setupLegalDocTocs", setupLegalDocTocs],
      ["setupTierComparisonMatrices", setupTierComparisonMatrices],
      ["setupPublicArchiveFilters", setupPublicArchiveFilters],
      ["setupCartTables", setupCartTables],
      ["setupCommerceCarts", setupCommerceCarts]
    ].forEach(function runInteractiveAtom(definition) {
      runSetup(definition[0], definition[1]);
    });
  }

  onReady(setupInteractiveAtoms);
})(window);
