(function () {
  const root = document.querySelector("[data-subscribe-fab]");
  if (!root) return;

  const toggle = root.querySelector(".subscribe-fab__toggle");
  const input = root.querySelector(".subscribe-fab__input");
  const triggers = document.querySelectorAll("[data-subscribe-trigger]");
  if (!toggle) return;

  const focusInput = () => {
    if (!input) return;
    requestAnimationFrame(function () {
      input.focus();
    });
  };

  const setOpen = (open, shouldFocusInput) => {
    root.classList.toggle("is-open", open);
    toggle.setAttribute("aria-expanded", open ? "true" : "false");
    if (open && shouldFocusInput) {
      focusInput();
    }
  };

  toggle.addEventListener("click", function () {
    const isOpen = root.classList.contains("is-open");
    setOpen(!isOpen, !isOpen);
  });

  triggers.forEach(function (trigger) {
    trigger.addEventListener("click", function (event) {
      event.preventDefault();
      setOpen(true, true);
    });
  });

  document.addEventListener("click", function (event) {
    if (event.target.closest("[data-subscribe-trigger]")) {
      return;
    }
    if (!root.contains(event.target)) {
      setOpen(false, false);
    }
  });

  document.addEventListener("keydown", function (event) {
    if (event.key === "Escape") {
      setOpen(false, false);
    }
  });
})();
