(() => {
const $faq = $("#faq");

const sanitizeFaqUrl = (url = "") => {
  url = url.trim();
  // Allow:
  // - absolute URLs (https)
  // - relative (/path or path)
  // - plain domains (domain.com)
  const isValid = /^(https:\/\/|\/(?!\/)|\.\/|\.\.\/|[a-z0-9-_]+\.[a-z]{2,}(\/|$))/i.test(url);
  return isValid ? url.replace(/"/g, "") : "#";
};

const faqText = $faq.data("faqtext");
const faqURL = $faq.data("faqurl");
const faqHeadings = $faq.data("faqheadings");
const faqTitle = $faq.data("faqtitle");

if (!faqText) {
  $faq.hide();
  return;
}

const faqTextArray = faqText.split("|");
const faqURLArray = faqURL.split("|");
const faqHeadingsArray = faqHeadings.split("|");

// Ensure all arrays align
if (
  faqTextArray.length !== faqURLArray.length ||
  faqTextArray.length !== faqHeadingsArray.length
) {
  return;
}

// Build DOM and append
const $list = $("<ul>");

faqURLArray.forEach((url, i) => {
  const $link = $("<a>", {
    href: sanitizeFaqUrl(url),
    title: faqTextArray[i].replace(/"/g, ""),
    text: faqHeadingsArray[i]
  });

  $("<li>").append($link).appendTo($list);
});

$faq
  .append($("<p>").text(faqTitle))
  .append($list);
})();
