(function () {
  // Only initialize if not already initialized
  if (window.appInitialized) return;

  // Global state management
  const state = {
    dropdownOpen: false,
    activeDropdownLabel: "",
  };

  // Constants
  const VIEWPORT_BREAKPOINT = 790;
  const SCROLL_THRESHOLD = 100; // Show button after scrolling 100px
  const DEBOUNCE_DELAY = 100;

  // Utility functions
  const debounce = (func, wait) => {
    let timeout;
    return function (...args) {
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(this, args), wait);
    };
  };

  // URL Navigation - exposed globally
  window.goToUrl =
    window.goToUrl ||
    ((targetUrl) => {
      if (!targetUrl) return;
      window.location.href = targetUrl;
    });

  // Dropdown Management - private functions
  const handleDropdownClick = (clickedEl) => {
    const activeArea = clickedEl.classList.contains("nav-arrow")
      ? clickedEl.parentNode.nextElementSibling
      : clickedEl.nextElementSibling;

    if (!activeArea) return;

    if (!state.dropdownOpen) {
      openDropdown(activeArea);
    } else {
      toggleDropdown(activeArea, clickedEl);
    }
  };

  const openDropdown = (targetDropdownArea) => {
    if (!targetDropdownArea) return;

    targetDropdownArea.classList.add("active");
    updateNavArrow(targetDropdownArea, true);
    setActiveDropdownLabel(targetDropdownArea);
    state.dropdownOpen = true;
  };

  const toggleDropdown = (containingDDArea, clickedEl) => {
    if (!containingDDArea?.previousElementSibling) return;

    const currentLabel = stripTags(
      containingDDArea.previousElementSibling.innerHTML
    );

    if (currentLabel === state.activeDropdownLabel) {
      closeDropdowns();
    } else {
      closeDropdowns();
      openDropdown(containingDDArea);
    }
  };

  const closeDropdowns = () => {
    document.querySelectorAll(".dropdown-content").forEach((dropdownArea) => {
      dropdownArea.classList.remove("active");
      updateNavArrow(dropdownArea, false);
    });
    state.dropdownOpen = false;
  };

  const updateNavArrow = (dropdownArea, isActive) => {
    const navArrowEl = dropdownArea?.parentNode?.querySelector(".nav-arrow");
    if (navArrowEl) {
      navArrowEl.classList.toggle("point-up", isActive);
    }
  };

  const setActiveDropdownLabel = (targetDropdownArea) => {
    const previousSibling = targetDropdownArea?.previousElementSibling;
    if (previousSibling) {
      state.activeDropdownLabel = stripTags(previousSibling.innerHTML);
    }
  };

  // HTML Safety - private function
  const stripTags = (input, allowed = "") => {
    if (typeof input !== "string") return "";

    allowed = (allowed.toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join("");
    const tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
    const commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;

    return input
      .replace(commentsAndPhpTags, "")
      .replace(tags, ($0, $1) =>
        allowed.includes("<" + $1.toLowerCase() + ">") ? $0 : ""
      );
  };

  // UI Enhancement Functions - exposed globally
  window.beautifyCodeBlocks =
    window.beautifyCodeBlocks ||
    (() => {
      document.querySelectorAll("code").forEach((code) => {
        code.innerHTML = code.innerHTML.trim();
      });
    });

  window.makeAlertsFantasticola =
    window.makeAlertsFantasticola ||
    ((alertEls = document.querySelectorAll(".alert")) => {
      const alertTypes = {
        "alert-info": {
          headline: "Just To Let You Know...",
          icon: "fa-info-circle",
        },
        "alert-warning": {
          headline: "Warning!",
          icon: "fa-exclamation-circle",
        },
        "alert-success": { headline: "Best Practices", icon: "fa-star" },
        "alert-danger": { headline: "Danger!", icon: "fa-warning" },
      };

      alertEls.forEach((alertEl) => {
        const alertBodyInner = alertEl.innerHTML.trim();
        const alertType = Object.keys(alertTypes).find((type) =>
          alertEl.classList.contains(type)
        );
        const { headline = "Alert", icon = "fa-star" } =
          alertTypes[alertType] || {};

        alertEl.innerHTML = `
                <div class="alert-heading">
                    <i class="fa ${icon}"></i> ${headline}
                </div>
                <div class="alert-body">${alertBodyInner}</div>
            `;
      });
    });

  window.makeIframesFantasticola =
    window.makeIframesFantasticola ||
    ((iframeEls = document.querySelectorAll("iframe")) => {
      iframeEls.forEach((iframeEl) => {
        if (iframeEl.classList.contains("chartjs-hidden-iframe")) return;

        if (!iframeEl.classList.contains("video")) {
          iframeEl.classList.add("video");
          const containerDiv = document.createElement("div");
          containerDiv.className = "video-container";
          iframeEl.parentNode.insertBefore(containerDiv, iframeEl);
          containerDiv.appendChild(iframeEl);
        }
      });
    });

  window.stylePageNavBtns =
    window.stylePageNavBtns ||
    ((pageNavBtns = document.querySelectorAll(".page-nav-btns")) => {
      const secondButton = pageNavBtns[1];
      if (secondButton) {
        secondButton.style.marginTop = "76px";
      }
    });

  // Scroll Management
  window.scrollToTop =
    window.scrollToTop ||
    (() => {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    });

  const updateScrollToTopButton = () => {
    const scrollToTopBtn = document.getElementById("scrollToTopBtn");
    if (!scrollToTopBtn) return;

    const footerMobi = document.querySelector("#footer-mobi");
    const footerEl = document.querySelector("footer");

    // Update visibility after 100px of scrolling
    scrollToTopBtn.style.display =
      window.scrollY > SCROLL_THRESHOLD ? "block" : "none";

    // Update position while keeping button in viewport
    if (scrollToTopBtn.style.display === "block") {
      // Default position when not near footer
      let bottomPosition = 20; // 20px from bottom of viewport

      // Check if near footer
      if (window.innerWidth <= VIEWPORT_BREAKPOINT && footerMobi) {
        const footerRect = footerMobi.getBoundingClientRect();
        // Only adjust if footer is in view and adjustment wouldn't push button below viewport
        if (footerRect.top < window.innerHeight) {
          bottomPosition = Math.min(
            window.innerHeight - footerRect.top + 12,
            window.innerHeight - 50 // Keep button at least 50px from bottom of viewport
          );
        }
      } else if (footerEl) {
        // Check if footerEl exists before using it
        const footerElRect = footerEl.getBoundingClientRect();
        if (footerElRect.top < window.innerHeight) {
          bottomPosition = Math.min(
            window.innerHeight - footerElRect.top + 12,
            window.innerHeight - 50
          );
        }
      }

      scrollToTopBtn.style.bottom = `${bottomPosition}px`;
    }
  };

  // Showcase Modal - exposed globally
  window.openShowcaseModal =
    window.openShowcaseModal ||
    (async (buttonNum) => {
      try {
        openModal("showcase-modal");

        const allLearnBtns = document.querySelectorAll(
          ".features-overview button"
        );
        const targetLearnBtnIndex = buttonNum - 1;
        const targetCard = allLearnBtns[targetLearnBtnIndex]?.closest(".card");

        if (!targetCard) return;

        const targetCardHeading = targetCard.querySelector("h3");
        const featureHeadlineDiv = document.getElementById(
          "feature-popup-headline"
        );
        const targetModal = document.getElementById("showcase-modal");
        const targetModalBody = targetModal?.querySelector(
          ".modal-body-content"
        );

        if (featureHeadlineDiv && targetCardHeading) {
          featureHeadlineDiv.textContent = targetCardHeading.textContent;
        }

        if (targetModalBody) {
          const response = await fetch(`welcome/fetch_statement/${buttonNum}`);
          if (!response.ok)
            throw new Error(`HTTP error! status: ${response.status}`);
          const data = await response.text();
          targetModalBody.innerHTML = data;
        }
      } catch (error) {
        console.error("Error in openShowcaseModal:", error);
      }
    });

  // Event Listeners
  document.addEventListener("click", (event) => {
    const clickedEl = event.target;
    const closestDropdownLink = clickedEl.closest(".dropdown-link");

    if (closestDropdownLink) {
      handleDropdownClick(clickedEl);
    } else if (state.dropdownOpen) {
      closeDropdowns();
    }
  });

  // Prevent default on dropdown links
  document.querySelectorAll(".dropdown-link").forEach((link) => {
    link.addEventListener("click", (event) => event.preventDefault());
  });

  // Clean up inline styles
  document.querySelectorAll(".dropdown-content").forEach((content) => {
    content.removeAttribute("style");
  });

  // Scroll handler with debounce
  window.addEventListener(
    "scroll",
    debounce(updateScrollToTopButton, DEBOUNCE_DELAY)
  );
  window.addEventListener(
    "resize",
    debounce(updateScrollToTopButton, DEBOUNCE_DELAY)
  );

  // Initialize on DOM load
  document.addEventListener("DOMContentLoaded", () => {
    window.makeAlertsFantasticola();
    window.makeIframesFantasticola();
    window.stylePageNavBtns();
    updateScrollToTopButton();
  });

  // Mark as initialized
  window.appInitialized = true;
})();
