function capitalizeFirstLetter(string) {
  return string.charAt(0).toLocaleUpperCase() + string.slice(1);
}

window.addEventListener("DOMContentLoaded", function () {
  const uri = decodeURI(location.hash.substring(1));
  let searchFragments = uri.split(" ");
  searchFragments = searchFragments.filter((el) => {
    if (
      el.startsWith("firstname") ||
      el.startsWith("lastname") ||
      (el !== "" &&
        !el.startsWith("birthdate") &&
        !el.startsWith("gender") &&
        !el.startsWith("city") &&
        !el.startsWith("phonenumber") &&
        !el.startsWith("@"))
    ) {
      return el;
    }
  });

  searchFragments = searchFragments.map((el) => {
    if (el.startsWith("firstname")) {
      return el.slice(10);
    } else if (el.startsWith("lastname")) {
      return el.slice(10);
    }
    return el.replace('"', "");
  });

  if (searchFragments) {
    const pre = '<ul class="list-suggest add-items inline">';
    const after = "</ul>";

    document
      .querySelectorAll("[data-suggest-container]")
      .forEach(function (container) {
        const suggestions = searchFragments.map(
          (el) =>
            `<li class="suggest-item-name"><span data-suggest-target="${container.dataset.suggestContainer}">${capitalizeFirstLetter(el)}</span></li>`,
        );
        container.innerHTML = pre + suggestions.join(" ") + after;
      });
  }

  const tags = document
    .querySelectorAll("[data-suggest-target]")
    .forEach((tag) => {
      tag.addEventListener("click", function (e) {
        const field = document.querySelector(
          `[name="${e.target.dataset.suggestTarget}"]`,
        );
        let suggestion = e.target.textContent.trim();
        switch (field.dataset.suggestTransform) {
          case "uppercase_all":
            suggestion = suggestion.toLocaleUpperCase();
            break;
          case "uppercase_first_letter":
          default:
            suggestion = capitalizeFirstLetter(suggestion);
        }

        if (field.value === "") {
          field.value = suggestion;
        } else {
          field.value = `${field.value} ${suggestion}`;
        }
        e.target.style.display = "none";

        [...document.querySelectorAll("[data-suggest-target]")]
          .filter((p) => p.textContent.includes(e.target.textContent))
          .forEach((p) => p.remove());
      });
    });
});
