document.addEventListener("DOMContentLoaded", () => {
  const form = document.querySelector("[data-industry-search]");
  if (!form) return;

  const input = form.querySelector('input[type="search"]');
  const clearButton = form.querySelector("[data-industry-search-clear]");
  const emptyClearButton = document.querySelector(
    "[data-industry-search-empty-clear]",
  );
  const status = document.querySelector(".industry-search-status");
  const emptyState = document.querySelector("[data-industry-search-empty]");
  const grid = document.querySelector("#industries-directory-grid");
  const cards = [...document.querySelectorAll("[data-industry-card]")];

  const normalise = (value) =>
    value.toLocaleLowerCase().trim().replace(/\s+/g, " ");

  const filterIndustries = () => {
    const query = normalise(input.value);
    let visibleCount = 0;

    cards.forEach((card) => {
      const isMatch =
        query === "" ||
        normalise(card.dataset.industrySearchText || "").includes(query);
      card.hidden = !isMatch;
      if (isMatch) visibleCount += 1;
    });

    clearButton.hidden = query === "";
    grid.hidden = visibleCount === 0;
    emptyState.hidden = visibleCount !== 0;
    status.innerHTML =
      visibleCount === 1
        ? "<b>1</b> industry found"
        : `<b>${visibleCount}</b> industries found`;
  };

  const clearSearch = () => {
    input.value = "";
    filterIndustries();
    input.focus();
  };

  form.addEventListener("submit", (event) => event.preventDefault());
  input.addEventListener("input", filterIndustries);
  clearButton.addEventListener("click", clearSearch);
  emptyClearButton.addEventListener("click", clearSearch);
});
