jQuery(function ($) {
  const popup = document.querySelector(".fjord-home-popup");
  if (!popup) {
    return;
  }
  const closeBtn = popup.querySelector(".fjord-home-popup__close");
  const overlay = popup.querySelector(".fjord-home-popup__overlay");

  const getDelay = () => parseInt(popup.dataset.delay, 10) || 2;
  const delayMs = getDelay() * 1000;
  const datasetPages = (popup.dataset.pages || "").split(",").map((value) => value.trim()).filter(Boolean);
  const pagesMap = {
    front: ["home", "front-page"],
    shop: ["post-type-archive-product", "woocommerce-shop", "archive", "woocommerce-page"],
    product: ["single-product"],
    post: ["single-post"],
  };

  const matchesPage = () => {
    if (!datasetPages.length) {
      return true;
    }
    const bodyClasses = document.body.className.split(/\s+/);
    return datasetPages.some((pageKey) => {
      const classes = pagesMap[pageKey] || [];
      return classes.some((cls) => bodyClasses.includes(cls));
    });
  };

  const repeatMinutes = Math.max(1, parseInt(popup.dataset.repeatMinutes, 10) || 1440);
  const storageKey = "fjordHomePopupShown";

  const behavior = popup.dataset.behavior || "once";
  const shouldShow = () => {
    const stored = localStorage.getItem(storageKey);
    if (!stored) {
      return true;
    }
    let parsed = null;
    try {
      parsed = JSON.parse(stored);
    } catch {
      parsed = null;
    }
    if (!parsed) {
      return true;
    }
    if (behavior === "repeat") {
      const goal = parsed.timestamp + repeatMinutes * 60 * 1000;
      return Date.now() > goal;
    }
    if (behavior === "repeat_always") {
      return true;
    }
    if (popup.dataset.adminBypass === "true") {
      return true;
    }
    return false;
  };

  const markShown = () => {
    localStorage.setItem(storageKey, JSON.stringify({ timestamp: Date.now() }));
  };

  const show = () => {
    popup.classList.add("is-visible");
    markShown();
  };

  const hide = () => {
    popup.classList.remove("is-visible");
  };

  const newsletterSection = popup.querySelector(".fjord-home-popup__newsletter");
  const newsletterBody = newsletterSection ? newsletterSection.querySelector(".fjord-home-popup__newsletter-body") : null;
  const newsletterSuccess = newsletterSection ? newsletterSection.querySelector(".fjord-home-popup__newsletter-success") : null;
  const newsletterCoupon = (popup.dataset.newsletterCoupon || "").trim();

  const showNewsletterCoupon = () => {
    if (!newsletterSection || !newsletterSuccess || !newsletterCoupon) {
      return;
    }
    if (newsletterBody) {
      newsletterBody.classList.add("is-hidden");
      newsletterBody.setAttribute("aria-hidden", "true");
    }
    newsletterSuccess.classList.add("is-visible");
  };

  const handleNewsletterSuccess = (event) => {
    if (!newsletterSection || !newsletterCoupon) {
      return;
    }
    const form = newsletterSection.querySelector("form");
    if (form && event.target === form) {
      showNewsletterCoupon();
    }
  };

  document.addEventListener("wpcf7mailsent", handleNewsletterSuccess);

  overlay.addEventListener("click", hide);
  closeBtn.addEventListener("click", hide);

  const init = () => {
    if (!matchesPage()) {
      return;
    }
    if (!shouldShow()) {
      return;
    }
    setTimeout(show, delayMs);
  };

  init();
});
