document.addEventListener("DOMContentLoaded", () => {
  /* --- References ---*/
  const containerComponent = document.getElementById("container-component");
  const pageWrapper = document.querySelector("body > .wrapper");
  const body = document.body;
  const isDialog = body.classList.contains("dialog");

  /* --- Header ---*/
  const mainHeader = document.createElement("main-header");
  mainHeader.innerText = document.title;
  mainHeader.classList.add("main-header");

  /* 1. title */
  const title = document.createElement("h1");
  title.classList.add("main-header__title");
  /* buttons wrapper */
  const buttonsWrapper = document.createElement("div");
  buttonsWrapper.classList.add("main-header__buttons-wrapper");

  /* 2. toggle dark */
  const toggleDarkBtn = document.createElement("button");
  toggleDarkBtn.innerText = "toggle dark";
  toggleDarkBtn.addEventListener("click", function () {
    // html.classList.toggle("dark");
    // eslint-disable-next-line no-alert
    alert(
      "Like a masterpiece sculpted with care, a good piece of work is a testament to patience. Light theme needs a little more dedication. "
    );
  });
  buttonsWrapper.appendChild(toggleDarkBtn);

  /* 3. toggle dir */
  const toggleDirBtn = document.createElement("button");
  toggleDirBtn.innerText = "toggle dir";
  toggleDirBtn.addEventListener("click", function () {
    const dir = html.getAttribute("dir");
    if (dir === "ltr") {
      html.setAttribute("dir", "rtl");
    } else {
      html.setAttribute("dir", "ltr");
    }
  });
  buttonsWrapper.appendChild(toggleDirBtn);

  let shorterBtn;
  let initialBtn;
  let tallerBtn;

  if (isDialog) {
    /* 4. toggle width */
    const toggleWidthLabel = document.createElement("label");
    toggleWidthLabel.innerText = "width:";
    const toggleWidthBtnGroup = document.createElement("div");
    toggleWidthBtnGroup.classList.add("buttons-group");
    /* small*/
    const smallBtn = document.createElement("button");
    smallBtn.innerText = "small";
    smallBtn.addEventListener("click", () => {
      containerComponent.classList.remove("large");
      containerComponent.classList.add("small");
    });
    toggleWidthBtnGroup.appendChild(smallBtn);
    /* medium*/
    const mediumBtn = document.createElement("button");
    mediumBtn.innerText = "medium";
    mediumBtn.addEventListener("click", () => {
      containerComponent.classList.remove("large");
      containerComponent.classList.remove("small");
    });
    toggleWidthBtnGroup.appendChild(mediumBtn);
    /* large*/
    const largeBtn = document.createElement("button");
    largeBtn.innerText = "large";
    largeBtn.addEventListener("click", () => {
      containerComponent.classList.remove("small");
      containerComponent.classList.add("large");
    });
    toggleWidthBtnGroup.appendChild(largeBtn);
    buttonsWrapper.appendChild(toggleWidthBtnGroup);
    buttonsWrapper.appendChild(toggleWidthLabel);

    /* 5. toggle height */
    const toggleHeightLabel = document.createElement("label");
    toggleHeightLabel.innerText = "height:";
    const toggleHeightBtnGroup = document.createElement("div");
    toggleHeightBtnGroup.classList.add("buttons-group");
    /* shorter*/
    shorterBtn = document.createElement("button");
    shorterBtn.innerText = "shorter";
    shorterBtn.addEventListener("click", () => {});
    toggleHeightBtnGroup.appendChild(shorterBtn);
    /* initial */
    initialBtn = document.createElement("button");
    initialBtn.innerText = "initial";
    initialBtn.addEventListener("click", () => {});
    toggleHeightBtnGroup.appendChild(initialBtn);
    /* taller*/
    tallerBtn = document.createElement("button");
    tallerBtn.innerText = "taller";
    toggleHeightBtnGroup.addEventListener("click", () => {});
    toggleHeightBtnGroup.appendChild(tallerBtn);
    buttonsWrapper.appendChild(toggleHeightBtnGroup);
    buttonsWrapper.appendChild(toggleHeightLabel);
  }

  /* 6. append */
  mainHeader.appendChild(buttonsWrapper);

  if (pageWrapper) {
    /* ai assistant has a .wrapper inside the body*/
    pageWrapper.insertBefore(mainHeader, pageWrapper.firstChild);
  } else {
    body.insertBefore(mainHeader, body.firstChild);
  }
  /* toggle height functionality */
  let initialHeight;
  if (gxIdeComponent && containerComponent && isDialog) {
    gxIdeComponent.addEventListener("componentDidRenderFirstTime", () => {
      setTimeout(() => {
        // Just to be completely sure.
        initialHeight = containerComponent.offsetHeight;
        containerComponent.style.height = initialHeight + "px";
        // Display body
        body.classList.remove("opacity-0");
      }, 250);
    });
    const heightVariation = 100;
    shorterBtn.addEventListener("click", () => {
      containerComponent.style.height = initialHeight - heightVariation + "px";
    });
    initialBtn.addEventListener("click", () => {
      containerComponent.style.height = initialHeight + "px";
    });
    tallerBtn.addEventListener("click", () => {
      containerComponent.style.height = initialHeight + heightVariation + "px";
    });
  } else {
    body.classList.remove("opacity-0");
  }

  /* --- Show Parts --- */
  const showPartsBtn = null;
  if (showPartsBtn) {
    showPartsBtn.addEventListener("click", function () {
      /* Parts that are discoverable (for example gxg-combo-item, is not visible until you open the gxg-combo)*/
      const hiddenGxgComponents = [
        "GXG-COMBO-BOX-ITEM",
        "GXG-CONTEXTUAL-MENU",
        "GXG-CONTEXTUAL-MENU-ITEM",
        "GXG-FILTER-ITEM",
        "GXG-LIST-BOX-ITEM",
        "GXG-MODAL"
      ];
      if (gxConsole) {
        const parts = window.getElementSelectorParts(gxIdeComponent);
        if (parts.length) {
          /* Clear*/
          gxConsole.innerHTML = "";
          let currentSelectedPart = undefined;
          parts.forEach(part => {
            /* part div*/
            const partSelector = document.createElement("div");
            partSelector.classList.add("part-selector");
            partSelector.innerText = part;
            partSelector.setAttribute("tabindex", "1");
            /* part span (circle for indicating additional information)*/
            const partCircle = document.createElement("span");
            partCircle.classList.add("circle");
            partSelector.prepend(partCircle);
            /* get part*/
            currentSelectedPart = window.querySelectorPart(`${part}`);
            if (!currentSelectedPart) {
              /* This part is not currently rendered by the component, probably because some property is not present*/
              partSelector.classList.add("part-selector--hidden");
            } else {
              currentSelectedPartNodeName = currentSelectedPart.nodeName;
              /* add class to indicate if this part belongs to a component that is not visible at a glance*/
              if (hiddenGxgComponents.includes(currentSelectedPartNodeName)) {
                partSelector.classList.add("part-selector--discoverable");
              }
            }
            partSelector.addEventListener("click", () => {
              if (currentSelectedPart) {
                /* Remove current selected part style*/
                currentSelectedPart.style.outline = "none";
              }
              currentSelectedPart = window.querySelectorPart(`${part}`);
              currentSelectedPart.style.outline = `3px solid var(--color-border-warning-default)`;
              currentSelectedPart.style.outlineOffset = "-2px";
            });
            /* append*/
            gxConsole.appendChild(partSelector);
          });
        }
      }
    });
  }

  /* --- Helpers ---*/
  window.getElementSelectorParts = element => {
    const queries = [];
    const elementParts = element.shadowRoot?.querySelectorAll(`[part]`);
    const elementExportParts =
      element.shadowRoot?.querySelectorAll(`[exportparts]`);

    elementParts?.forEach(el => {
      queries.push(
        `${element.tagName.toLowerCase()}::part(${el.getAttribute("part")})`
      );
    });
    elementExportParts?.forEach(el => {
      queries.push(
        ...[
          ...el.getAttribute("exportparts").matchAll(/(?:[\w-]+:)?([\w-]+)/g)
        ].map(item => `${element.tagName.toLowerCase()}::part(${item[1]})`)
      );
    });

    return queries.sort();
  };

  window.querySelectorPart = selector => {
    const querySelectorDeep = (element, parts) => {
      const shadow = element.shadowRoot;
      const partList = parts.split(" ");

      const partElement = shadow.querySelector(
        partList.map(partName => `[part~="${partName}"]`).join("")
      );
      if (partElement) {
        return partElement;
      }

      const exportPartElement = shadow.querySelector(
        partList.map(partName => `[exportparts*="${partName}"]`).join("")
      );
      if (exportPartElement) {
        const exportPartList = [];
        const exportparts = exportPartElement.getAttribute("exportparts");

        partList.forEach(partItem => {
          const exportPartName = exportparts.match(
            `(?:([\\w-]+):)?(${partItem})`
          )[1];
          if (exportPartName) {
            exportPartList.push(exportPartName);
          }
        });

        if (partList.length === exportPartList.length) {
          return querySelectorDeep(exportPartElement, exportPartList.join(" "));
        }
      }

      return null;
    };

    const selectorItems = selector.match("(.*)::part\\(([^)]+)\\)");
    const entity = selectorItems[1];
    const partName = selectorItems[2];

    return querySelectorDeep(document.querySelector(entity), partName);
  };
});

/* --- Console ---*/
let logNumber = 1;
// (not used in this file, but in /pages/components)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const appendConsoleLog = log => {
  const codeWrapper = document.getElementById("code-wrapper");
  if (codeWrapper) {
    const logNumberEl = document.createElement("span");
    logNumberEl.classList.add("log-number");
    logNumberEl.innerText = logNumber;
    logNumber++;
    const pre = document.createElement("pre");
    const code = document.createElement("code");
    code.classList.add("gx-console", "language-javascript");
    code.textContent = log;
    pre.appendChild(logNumberEl);
    pre.appendChild(code);
    codeWrapper.insertBefore(pre, codeWrapper.children[0]);
    Prism.highlightElement(code);
  }
};

// (not used in this file, but in /pages/components)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const stringify = data => {
  return JSON.stringify(data, null, 2);
};

/* --- Ch Styles --- */
const head = document.head || document.getElementsByTagName("head")[0];
const chStyle = document.createElement("ch-style");
chStyle.innerText =
  "::-webkit-scrollbar{width:var(--gxg-scrollbar-width);height:var(--gxg-scrollbar-width);cursor:initial}::-webkit-scrollbar-track{background-color:var(--gxg-scrollbar-track-background);border-radius:var(--gxg-scrollbar-track-border-radius)}::-webkit-scrollbar-thumb{background-color:var(--gxg-scrollbar-track-thumb-background);border-radius:var(--gxg-scrollbar-track-thumb-radius);}::-webkit-scrollbar-thumb:hover{background-color:var(--gxg-scrollbar-track-thumb-hover-background)}::-webkit-scrollbar-corner{background:rgba(0,0,0,0)}";
head.appendChild(chStyle);
