(() => {
  "use strict";

  const path = location.pathname;

  function bodyClass(name) {
    document.body.classList.add(name);
  }

  function setupMalaysia() {
    bodyClass("project-malaysia-cost");

    const find = () => {
      const nav = [...document.querySelectorAll("nav")].find(element => {
        const text = element.textContent || "";
        return (
          text.includes("Overview") &&
          text.includes("Cost Breakdown") &&
          text.includes("Housing Explorer") &&
          text.includes("Budget Simulator")
        );
      });

      if (!nav) return false;

      nav.classList.add("mc-nav");

      const row = nav.parentElement;
      row?.classList.add("mc-topbar-row");

      const brand = row?.firstElementChild;
      brand?.classList.add("mc-brand");

      const inner = row?.parentElement;
      inner?.classList.add("mc-topbar-inner");

      const topbar = inner?.parentElement;
      topbar?.classList.add("mc-topbar");

      const mainHeading = [...document.querySelectorAll("h1")][0];
      const headingGroup = mainHeading?.parentElement;
      headingGroup?.classList.add("mc-page-heading");

      const headingRow = headingGroup?.parentElement;
      if (headingRow) {
        const possibleActions = [...headingRow.children].find(
          child => child !== headingGroup
        );
        possibleActions?.classList.add("mc-page-actions");
      }

      return true;
    };

    watchUntil(find);
  }

  function setupAcademic() {
    bodyClass("project-academic-evidence");

    const find = () => {
      const mobileHeader = [...document.querySelectorAll("header, div")].find(element => {
        const text = element.textContent?.trim() || "";
        return (
          text.includes("R. Ocaviantyo T.L.") &&
          element.querySelector("button")
        );
      });

      if (mobileHeader) {
        mobileHeader.classList.add("ae-mobile-header");
      }

      const mobileMenu = [...document.querySelectorAll("div")].find(element => {
        const text = element.textContent || "";
        return (
          text.includes("Curriculum Vitae") &&
          text.includes("Admission Docs") &&
          getComputedStyle(element).position === "fixed"
        );
      });
      mobileMenu?.classList.add("ae-mobile-menu");

      const badge = [...document.querySelectorAll("[data-testid='status-badge'], div")].find(
        element => (element.textContent || "").includes("Graduate Applicant 2025")
      );

      if (!badge) return false;

      badge.classList.add("ae-status-badge");

      const hero = badge.closest("section");
      hero?.classList.add("ae-hero");

      const content = badge.parentElement?.parentElement;
      content?.classList.add("ae-hero-content");

      const heading = hero?.querySelector("h1");
      const actionGroup = [...(hero?.querySelectorAll("div") || [])].find(element => {
        const text = element.textContent || "";
        return (
          text.includes("View Projects") &&
          text.includes("Research Statement") &&
          text.includes("GitHub")
        );
      });

      actionGroup?.classList.add("ae-hero-actions");
      return Boolean(hero && heading);
    };

    watchUntil(find);
  }

  function setupIncident() {
    bodyClass("project-incident-monitoring");

    const find = () => {
      const sidebar = [...document.querySelectorAll("aside")].find(element => {
        const text = element.textContent || "";
        return (
          text.includes("Incident Monitoring Dashboard") &&
          text.includes("Dashboard") &&
          text.includes("Incidents") &&
          text.includes("Timeline") &&
          text.includes("Reports")
        );
      });

      if (!sidebar) return false;
      if (sidebar.dataset.mobileReady === "true") return true;

      sidebar.dataset.mobileReady = "true";
      sidebar.classList.add("incident-sidebar");

      const close = document.createElement("button");
      close.type = "button";
      close.className = "incident-sidebar-close";
      close.setAttribute("aria-label", "Close navigation");
      close.textContent = "×";
      sidebar.appendChild(close);

      const backdrop = document.createElement("button");
      backdrop.type = "button";
      backdrop.className = "incident-mobile-backdrop";
      backdrop.setAttribute("aria-label", "Close navigation");

      const trigger = document.createElement("button");
      trigger.type = "button";
      trigger.className = "incident-mobile-button";
      trigger.setAttribute("aria-label", "Open incident navigation");
      trigger.setAttribute("aria-expanded", "false");
      trigger.innerHTML = `
        <svg viewBox="0 0 24 24" aria-hidden="true">
          <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
            d="M4 7h16M4 12h16M4 17h16"/>
        </svg>
        <span>Incident Menu</span>
      `;

      document.body.append(backdrop, trigger);

      const setOpen = open => {
        sidebar.classList.toggle("is-open", open);
        backdrop.classList.toggle("is-visible", open);
        trigger.setAttribute("aria-expanded", String(open));
        document.documentElement.classList.toggle("mobile-project-menu-open", open);
        document.body.classList.toggle("mobile-project-menu-open", open);
      };

      trigger.addEventListener("click", () => setOpen(true));
      close.addEventListener("click", () => setOpen(false));
      backdrop.addEventListener("click", () => setOpen(false));

      sidebar.querySelectorAll("a").forEach(link => {
        link.addEventListener("click", () => setOpen(false));
      });

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

      addEventListener("resize", () => {
        if (innerWidth >= 768) setOpen(false);
      }, { passive: true });

      return true;
    };

    watchUntil(find);
  }

  function watchUntil(setup) {
    if (setup()) return;

    let attempts = 0;
    const observer = new MutationObserver(() => {
      attempts += 1;
      if (setup() || attempts > 180) {
        observer.disconnect();
      }
    });

    observer.observe(document.documentElement, {
      childList: true,
      subtree: true
    });

    setTimeout(() => {
      setup();
      observer.disconnect();
    }, 12000);
  }

  if (path.includes("/projects/malaysia-cost/")) {
    setupMalaysia();
  } else if (path.includes("/projects/academic-evidence/")) {
    setupAcademic();
  } else if (path.includes("/projects/incident-monitoring/")) {
    setupIncident();
  }
})();
