document.addEventListener("DOMContentLoaded", function () {
  var body = document.body;
  var wrapper = document.querySelector(".wrapper");
  var menuToggle = document.getElementById("show-menu");
  var navLinks = null;
  var navActions = document.querySelector(".nav-actions");
  var mobileActions = document.querySelector(".nav-mobile-actions");
  var logoLink = document.querySelector(".nav-logo a");
  var scrollTopButton = document.querySelector(".scroll-top-btn");
  var lastScrollY = window.scrollY;
  var ticking = false;
  var hideAfter = 140;
  var scrollTopAfter = 420;
  var delta = 8;
  var searchUi = null;
  var searchEntries = buildSearchEntries();

  if (!body) {
    return;
  }

  if (!scrollTopButton) {
    scrollTopButton = document.createElement("button");
    scrollTopButton.type = "button";
    scrollTopButton.className = "scroll-top-btn";
    scrollTopButton.setAttribute("aria-label", "Scroll back to top");
    scrollTopButton.setAttribute("title", "Back to top");
    scrollTopButton.innerHTML = '<i class="fas fa-arrow-up" aria-hidden="true"></i>';
    body.appendChild(scrollTopButton);
  }

  renderSiteFooter();
  searchUi = createSearchUi();
  mountSearchTrigger(navActions, false);
  mountSearchTrigger(mobileActions, true);

  function getPathPrefix() {
    var href = logoLink ? logoLink.getAttribute("href") || "" : "";
    return href.indexOf("../") === 0 ? "../" : "";
  }

  function route(path) {
    return getPathPrefix() + path;
  }

  function getCurrentPageName() {
    var pathname = window.location.pathname || "";
    return (pathname.split("/").pop() || "index.html").toLowerCase();
  }

  function enhancePrimaryNav() {
    var navList = document.querySelector(".nav-links");
    var currentPage = getCurrentPageName();
    var isResourcesPage = currentPage === "resources.html" || currentPage === "gallery.html";
    var isGalleryPage = currentPage === "gallery.html";
    var isBlogPage = currentPage === "blog.html";
    var contactItem = null;
    var resourcesItem;
    var blogItem;

    if (!navList || navList.querySelector(".nav-resources-item")) {
      return;
    }

    Array.prototype.slice.call(navList.children).some(function (item) {
      var topLink;
      var href;

      if (!item || item.classList.contains("nav-mobile-actions")) {
        return false;
      }

      topLink = item.querySelector("a");
      href = topLink ? topLink.getAttribute("href") || "" : "";

      if (/contact\.html(?:#.*)?$/i.test(href)) {
        contactItem = item;
        return true;
      }

      return false;
    });

    resourcesItem = document.createElement("li");
    resourcesItem.className = "dropdown nav-resources-item";
    resourcesItem.innerHTML = [
      '<a href="' + route("resources.html") + '" class="desktop-link' + (isResourcesPage ? " is-current" : "") + '"' + (isResourcesPage ? ' aria-current="page"' : "") + ">Resources</a>",
      '<input type="checkbox" id="show-resources" aria-hidden="true">',
      '<label for="show-resources">Resources</label>',
      '<ul class="dropdown-menu resources-menu">',
      '  <li><a href="' + route("gallery.html") + '"' + (isGalleryPage ? ' class="is-current" aria-current="page"' : "") + ">Gallery</a></li>",
      "</ul>"
    ].join("");

    blogItem = document.createElement("li");
    blogItem.className = "nav-blog-item";
    blogItem.innerHTML = '<a href="' + route("blog.html") + '"' + (isBlogPage ? ' class="is-current" aria-current="page"' : "") + ">Blog</a>";

    if (contactItem) {
      navList.insertBefore(resourcesItem, contactItem);
      navList.insertBefore(blogItem, contactItem);
    } else {
      navList.appendChild(resourcesItem);
      navList.appendChild(blogItem);
    }
  }

  enhancePrimaryNav();
  navLinks = document.querySelectorAll(".nav-links a");

  function renderSiteFooter() {
    var existingFooters = Array.prototype.slice.call(document.querySelectorAll(".bottom-page, .site-footer"));
    var mount = existingFooters.length ? existingFooters[existingFooters.length - 1] : null;
    var parent = mount && mount.parentNode ? mount.parentNode : body;
    var nextSibling = mount ? mount.nextSibling : body.querySelector("script");
    var footer = document.createElement("footer");
    var currentYear = new Date().getFullYear();

    existingFooters.forEach(function (node) {
      if (node.parentNode) {
        node.parentNode.removeChild(node);
      }
    });

    footer.className = "site-footer";
    footer.id = "footer";
    footer.innerHTML = [
      '<div class="container">',
      '  <div class="site-footer-shell">',
      '    <section class="site-footer-brand">',
      '      <a class="site-footer-logo" href="' + route("index.html#home") + '" aria-label="NIQ homepage">',
      '        <img src="' + route("images/LOGO.png") + '" alt="NIQ Oil and Gas logo">',
      "      </a>",
      '      <span class="site-footer-kicker">Engineering. Offshore. Integrity.</span>',
      '      <p class="site-footer-copy">NIQ Oil and Gas Ltd provides offshore engineering, maintenance, marine assurance, integrity management, risk review, and technical consultancy support for projects that need disciplined execution.</p>',
      '      <div class="site-footer-social" aria-label="NIQ social media links">',
      '        <a href="https://twitter.com/official_niqong?s=11&t=5TDxRpwcNk7uCqtj_WQRpA" target="_blank" rel="noopener noreferrer" aria-label="Follow NIQ on Twitter"><i class="fab fa-twitter" aria-hidden="true"></i></a>',
      '        <a href="https://www.linkedin.com/company/niq-oil-gas-limited/" target="_blank" rel="noopener noreferrer" aria-label="Follow NIQ on LinkedIn"><i class="fab fa-linkedin-in" aria-hidden="true"></i></a>',
      '        <a href="https://www.instagram.com/niqong/" target="_blank" rel="noopener noreferrer" aria-label="Follow NIQ on Instagram"><i class="fab fa-instagram" aria-hidden="true"></i></a>',
      '        <a href="mailto:info@niqong.com" aria-label="Email NIQ"><i class="fas fa-envelope" aria-hidden="true"></i></a>',
      "      </div>",
      "    </section>",
      '    <nav aria-label="Footer quick links">',
      '      <h2 class="site-footer-heading">Quick Links</h2>',
      '      <ul class="site-footer-links">',
      '        <li><a href="' + route("index.html#home") + '">Home</a></li>',
      '        <li><a href="' + route("about.html") + '">About NIQ</a></li>',
      '        <li><a href="' + route("hse.html") + '">HSE</a></li>',
      '        <li><a href="' + route("index.html#services") + '">Services</a></li>',
      '        <li><a href="' + route("resources.html") + '">Resources</a></li>',
      '        <li><a href="' + route("blog.html") + '">Blog</a></li>',
      '        <li><a href="' + route("contact.html") + '">Contact</a></li>',
      "      </ul>",
      "    </nav>",
      '    <nav aria-label="Footer service links">',
      '      <h2 class="site-footer-heading">Core Services</h2>',
      '      <ul class="site-footer-links">',
      '        <li><a href="' + route("services/fpso.html") + '">FPSO Operations</a></li>',
      '        <li><a href="' + route("services/marine.html") + '">Marine Warranty</a></li>',
      '        <li><a href="' + route("services/offshore.html") + '">Offshore Subsea Intervention</a></li>',
      '        <li><a href="' + route("services/risks.html") + '">Risk Management</a></li>',
      '        <li><a href="' + route("services/throughlife.html") + '">Integrity Management</a></li>',
      '        <li><a href="' + route("services/flowassurance.html") + '">Flow Assurance</a></li>',
      "      </ul>",
      "    </nav>",
      '    <section class="site-footer-contact">',
      '      <h2 class="site-footer-heading">Contact</h2>',
      '      <ul class="site-footer-contact-list">',
      '        <li>',
      '          <i class="fas fa-phone" aria-hidden="true"></i>',
      "          <div>",
      '            <span class="site-footer-contact-label">Phone</span>',
      '            <a class="site-footer-contact-text" href="tel:+2349033058380">(+234) 903-305-8380</a>',
      "          </div>",
      "        </li>",
      '        <li>',
      '          <i class="fas fa-envelope" aria-hidden="true"></i>',
      "          <div>",
      '            <span class="site-footer-contact-label">Email</span>',
      '            <a class="site-footer-contact-text" href="mailto:info@niqong.com">info@niqong.com</a>',
      "          </div>",
      "        </li>",
      '        <li>',
      '          <i class="fas fa-map-marker-alt" aria-hidden="true"></i>',
      "          <div>",
      '            <span class="site-footer-contact-label">Location</span>',
      '            <a class="site-footer-contact-text site-footer-map-link" href="https://maps.google.com/?q=NIQ%20Oil%20and%20Gas%20Limited" target="_blank" rel="noopener noreferrer">Open NIQ on Google Maps</a>',
      "          </div>",
      "        </li>",
      "      </ul>",
      '      <a class="btn site-footer-cta" href="' + route("contact.html") + '">Request Consultation</a>',
      "    </section>",
      "  </div>",
      '  <div class="site-footer-bottom">',
      '    <p>Copyright &copy; ' + currentYear + ' NIQ Oil and Gas Limited. All rights reserved.</p>',
      '    <div class="site-footer-mini-links">',
      '      <a href="' + route("NIQ_OIL_AND_GAS_PROFILE_2022_(2)_(2)_NIQ_OIL_AND_GAS_PROFILE_202 (2)_compressed.pdf") + '" download>Download Profile</a>',
      '      <a href="' + route("contact.html") + '">Talk to NIQ</a>',
      '      <a class="site-footer-credit" href="#footer">Developed by Pelinks</a>',
      "    </div>",
      "  </div>",
      "</div>"
    ].join("");

    parent.insertBefore(footer, nextSibling);
  }

  function buildSearchEntries() {
    return [
      {
        title: "Home",
        url: route("index.html#home"),
        description: "Return to the homepage hero and company highlights.",
        keywords: "home hero company niq oil gas"
      },
      {
        title: "About NIQ",
        url: route("about.html"),
        description: "Company overview, experience, and operating approach.",
        keywords: "about company overview profile engineering consultancy"
      },
      {
        title: "Health, Safety and Environment",
        url: route("hse.html"),
        description: "Review NIQ's health, safety, and environmental standards.",
        keywords: "hse health safety environment standards compliance"
      },
      {
        title: "Services",
        url: route("index.html#services"),
        description: "Browse NIQ's engineering, maintenance, and offshore services.",
        keywords: "services engineering offshore maintenance subsea marine"
      },
      {
        title: "Resources",
        url: route("resources.html"),
        description: "Access NIQ downloads, references, and media pages.",
        keywords: "resources downloads profile documents gallery"
      },
      {
        title: "Gallery",
        url: route("gallery.html"),
        description: "View project, operations, and site imagery from NIQ.",
        keywords: "gallery images photos offshore marine operations"
      },
      {
        title: "Blog",
        url: route("blog.html"),
        description: "Read NIQ updates, notes, and technical insight summaries.",
        keywords: "blog articles insight updates engineering offshore"
      },
      {
        title: "FPSO Operations and Maintenance",
        url: route("services/fpso.html"),
        description: "Support for topsides, hull, and structure operations.",
        keywords: "fpso operations maintenance topsides hull structure"
      },
      {
        title: "Marine Warranty and Verification",
        url: route("services/marine.html"),
        description: "Marine warranty surveying and third-party technical verification.",
        keywords: "marine warranty surveyor verification assurance"
      },
      {
        title: "Upstream, Midstream and Downstream",
        url: route("services/streams.html"),
        description: "Technical support across the oil and gas value chain.",
        keywords: "upstream midstream downstream production processing"
      },
      {
        title: "Offshore Subsea Intervention",
        url: route("services/offshore.html"),
        description: "Offshore intervention, subsea scope planning, and execution support.",
        keywords: "offshore subsea intervention field execution"
      },
      {
        title: "Risk Management Services",
        url: route("services/risks.html"),
        description: "Risk identification, mitigation planning, and technical review.",
        keywords: "risk risk management assessment mitigation"
      },
      {
        title: "Through-Life Integrity Management",
        url: route("services/throughlife.html"),
        description: "Asset integrity support across the operating lifecycle.",
        keywords: "integrity asset lifecycle reliability"
      },
      {
        title: "Flow Assurance Engineering",
        url: route("services/flowassurance.html"),
        description: "Flow assurance support for production stability, restart planning, and transport reliability.",
        keywords: "flow assurance hydrate wax scale slugging restart production chemistry"
      },
      {
        title: "Expert Witness and Consultancy",
        url: route("services/consult.html"),
        description: "Engineering consultancy and technical advisory support.",
        keywords: "consultancy expert witness advisory engineering"
      },
      {
        title: "Installation Engineering",
        url: route("services/install.html"),
        description: "Installation planning and offshore engineering support.",
        keywords: "installation engineering lifting transportation"
      },
      {
        title: "Support Services",
        url: route("services/supportservices.html"),
        description: "Operational support services for offshore and onshore delivery.",
        keywords: "support services manpower logistics project delivery"
      },
      {
        title: "Other Services",
        url: route("services/otherservices.html"),
        description: "Additional engineering and maintenance capabilities.",
        keywords: "other services additional capability engineering"
      },
      {
        title: "Contact",
        url: route("contact.html"),
        description: "Call, email, view the map, or send an enquiry to NIQ.",
        keywords: "contact phone email quote enquiry"
      }
    ];
  }

  function showHeader() {
    body.classList.remove("nav-is-hidden");
  }

  function hideHeader() {
    body.classList.add("nav-is-hidden");
  }

  function updateScrollTopButton(currentScrollY) {
    if (!scrollTopButton) {
      return;
    }

    scrollTopButton.classList.toggle("is-visible", currentScrollY > scrollTopAfter);
  }

  function updateHeaderState() {
    var currentScrollY = window.scrollY;
    var menuOpen = menuToggle ? menuToggle.checked : false;

    updateScrollTopButton(currentScrollY);

    if (!wrapper) {
      lastScrollY = currentScrollY;
      ticking = false;
      return;
    }

    if (body.classList.contains("search-is-open") || menuOpen || currentScrollY <= hideAfter) {
      showHeader();
    } else if (currentScrollY > lastScrollY + delta) {
      hideHeader();
    } else if (currentScrollY < lastScrollY - delta) {
      showHeader();
    }

    lastScrollY = currentScrollY;
    ticking = false;
  }

  function createSearchUi() {
    var overlay = document.createElement("div");
    overlay.className = "site-search";
    overlay.innerHTML = [
      '<button type="button" class="site-search-backdrop" aria-label="Close search"></button>',
      '<div class="site-search-panel" role="dialog" aria-modal="true" aria-labelledby="site-search-title">',
      '  <div class="site-search-header">',
      '    <div>',
      '      <span class="site-search-kicker">Site Search</span>',
      '      <h2 class="site-search-title" id="site-search-title">Find pages and services quickly</h2>',
      "    </div>",
      '    <button type="button" class="site-search-close" aria-label="Close search">',
      '      <i class="fas fa-times" aria-hidden="true"></i>',
      "    </button>",
      "  </div>",
      '  <form class="site-search-form" role="search">',
      '    <label class="site-search-input-wrap" for="site-search-input">',
      '      <i class="fas fa-search" aria-hidden="true"></i>',
      '      <input id="site-search-input" class="site-search-input" type="search" placeholder="Search services, HSE, contact, FPSO..." autocomplete="off">',
      "    </label>",
      "  </form>",
      '  <ul class="site-search-results" aria-live="polite"></ul>',
      "</div>"
    ].join("");

    body.appendChild(overlay);

    var input = overlay.querySelector(".site-search-input");
    var results = overlay.querySelector(".site-search-results");
    var closeButton = overlay.querySelector(".site-search-close");
    var backdrop = overlay.querySelector(".site-search-backdrop");
    var form = overlay.querySelector(".site-search-form");

    function getMatches(query) {
      var normalized = query.trim().toLowerCase();
      var terms;

      if (!normalized) {
        return searchEntries.slice(0, 6);
      }

      terms = normalized.split(/\s+/);

      return searchEntries
        .map(function (entry) {
          var haystack = (entry.title + " " + entry.description + " " + entry.keywords).toLowerCase();
          var score = 0;
          var matches = true;

          terms.forEach(function (term) {
            if (haystack.indexOf(term) === -1) {
              matches = false;
              return;
            }

            if (entry.title.toLowerCase().indexOf(term) !== -1) {
              score += 4;
            }

            if (entry.keywords.toLowerCase().indexOf(term) !== -1) {
              score += 2;
            }

            if (entry.description.toLowerCase().indexOf(term) !== -1) {
              score += 1;
            }
          });

          if (!matches) {
            return null;
          }

          return {
            entry: entry,
            score: score
          };
        })
        .filter(Boolean)
        .sort(function (left, right) {
          return right.score - left.score || left.entry.title.localeCompare(right.entry.title);
        })
        .map(function (item) {
          return item.entry;
        });
    }

    function renderResults(query) {
      var normalized = query.trim();
      var matches = normalized ? getMatches(normalized) : searchEntries.slice(0, 6);

      if (!matches.length) {
        results.innerHTML = '<li class="site-search-empty">No results found. Try terms like "FPSO", "HSE", "contact", or "offshore".</li>';
        return;
      }

      results.innerHTML = matches
        .slice(0, 8)
        .map(function (entry) {
          return [
            '<li class="site-search-result">',
            '  <a class="site-search-result-link" href="' + entry.url + '">',
            '    <span class="site-search-result-title">' + entry.title + "</span>",
            '    <span class="site-search-result-desc">' + entry.description + "</span>",
            "  </a>",
            "</li>"
          ].join("");
        })
        .join("");
    }

    function closeSearch() {
      body.classList.remove("search-is-open");
      input.blur();
    }

    function openSearch() {
      showHeader();
      if (menuToggle) {
        menuToggle.checked = false;
      }
      body.classList.add("search-is-open");
      renderResults(input.value);
      window.setTimeout(function () {
        input.focus();
        input.select();
      }, 30);
    }

    input.addEventListener("input", function () {
      renderResults(input.value);
    });

    form.addEventListener("submit", function (event) {
      var matches = getMatches(input.value);

      event.preventDefault();

      if (input.value.trim() && matches[0]) {
        window.location.href = matches[0].url;
      }
    });

    closeButton.addEventListener("click", closeSearch);
    backdrop.addEventListener("click", closeSearch);

    overlay.addEventListener("click", function (event) {
      if (event.target.closest(".site-search-result-link")) {
        closeSearch();
      }
    });

    document.addEventListener("keydown", function (event) {
      if (event.key === "Escape" && body.classList.contains("search-is-open")) {
        closeSearch();
      }
    });

    renderResults("");

    return {
      open: openSearch,
      close: closeSearch
    };
  }

  function mountSearchTrigger(container, showText) {
    var contactButton = container ? container.querySelector(".btn-primary-nav") : null;
    var button;

    if (!container || !contactButton || container.querySelector(".nav-search-btn")) {
      return;
    }

    button = document.createElement("button");
    button.type = "button";
    button.className = "nav-search-btn";
    button.setAttribute("aria-label", "Search the site");
    button.innerHTML = showText
      ? '<i class="fas fa-search" aria-hidden="true"></i><span>Search</span>'
      : '<i class="fas fa-search" aria-hidden="true"></i><span>Search</span>';

    contactButton.insertAdjacentElement("afterend", button);
    button.addEventListener("click", function () {
      if (searchUi) {
        searchUi.open();
      }
    });
  }

  window.addEventListener(
    "scroll",
    function () {
      if (!ticking) {
        window.requestAnimationFrame(updateHeaderState);
        ticking = true;
      }
    },
    { passive: true }
  );

  if (menuToggle) {
    menuToggle.addEventListener("change", function () {
      if (menuToggle.checked) {
        showHeader();
      }
    });
  }

  navLinks.forEach(function (link) {
    link.addEventListener("click", function () {
      if (menuToggle) {
        menuToggle.checked = false;
      }
      showHeader();
    });
  });

  if (scrollTopButton) {
    scrollTopButton.addEventListener("click", function () {
      window.scrollTo({
        top: 0,
        behavior: "smooth"
      });
      showHeader();
    });
  }

  window.addEventListener("resize", function () {
    if (window.innerWidth > 980 && menuToggle) {
      menuToggle.checked = false;
    }
    showHeader();
  });

  updateHeaderState();
});
