if (window.NodeList && !window.NodeList.prototype.forEach) {
  window.NodeList.prototype.forEach = Array.prototype.forEach;
}

function resizeEhqIframe(event) {
  const iframeContainers = document.querySelectorAll(".ehq-embed-iframe");
  iframeContainers.forEach(function (iframe) {
    const { height, location } = event.data;

    if (height && location === iframe.src) {
      iframe.style.height = height + "px";
    }
  });
}

function renderEhq() {
  const hostOrigin = window.location.href;
  const scriptTag = document.querySelector(
    'script[src*="static/client/ideas.js"]'
  );
  const ehqIdeasDom = document.querySelectorAll(
    "#ehq-embed-ideas, .ehq-embed-ideas"
  );

  ehqIdeasDom.forEach(function (ehqElement) {
    const href = ehqElement.getAttribute("data-href");
    const height = ehqElement.getAttribute("height") || "800px";
    const width = ehqElement.getAttribute("width") || "100%";
    const projectPermalink = ehqElement.getAttribute("data-project-permalink");
    const brainstormerPermalink = ehqElement.getAttribute(
      "data-project-brainstormer-link"
    );
    const ideasEngagementBannerTitle = ehqElement.getAttribute(
      "data-ideas-engagement-banner-title"
    );
    const allIdeasEngagementBanner = ehqElement.getAttribute(
      "data-ideas-engagement-banner"
    );

    const hostSiteUrl = scriptTag.src.match(
      /^https?:\/\/([^/?#]+)(?:[/?#]|$)/i
    )[0];

    const hostOriginAttr = hostOrigin ? "hostOrigin=" + hostOrigin : "";

    let fnUrl =
      hostSiteUrl +
      "embeds/projects/" +
      projectPermalink +
      "/brainstormers/banner/" +
      brainstormerPermalink;

    if (allIdeasEngagementBanner)
      fnUrl =
        hostSiteUrl +
        "embeds/projects/" +
        projectPermalink +
        "/brainstormers/banner";

    const hrefData = fnUrl + "?baseUrl=" + href + "&" + hostOriginAttr;

    const iframe = document.createElement("iframe");
    iframe.width = width;
    iframe.height = height;
    iframe.frameBorder = 0;
    iframe.marginWidth = 0;
    iframe.marginHeight = 0;
    iframe.scrolling = "no";
    iframe.name = brainstormerPermalink;
    iframe.title = ideasEngagementBannerTitle || "Ideas";
    iframe.className = "ehq-embed-iframe";
    iframe.src = hrefData.replace(/&\s*$/, "");

    const isIframeLoaded = document.querySelector(
      'iframe[src*="' + iframe.src + '"]'
    );
    if (!isIframeLoaded) ehqElement.appendChild(iframe);
  });
}

window.addEventListener("load", renderEhq);
window.addEventListener("message", resizeEhqIframe);
