/**
 * Main JS file for template
 * @package fga.marketing-materials
 */
/// <reference path="../../types/app.d.ts" />
/// <reference path="../../types/data.d.ts" />

const TITLE_SELECTOR = "title";
const HEADER_SELECTOR = "header";
const NAVIGATION_LIST_SELECTOR = `[data-section="navigation-list"]`;
const NAVIGATION_BUTTON_SELECTOR = `[data-item="navigation-button"]`;
const CAP_BUTTON_SELECTOR = `[data-item="capability-statement-button"]`;
const HOME_BUTTON_SELECTOR = `[data-item="home-button"]`;

const setupBasicInformation = () => {
  const htmlElement = select("html");
  const header = select(HEADER_SELECTOR);
  const navList = select(NAVIGATION_LIST_SELECTOR);
  const navigationButton = select(NAVIGATION_BUTTON_SELECTOR);
  const capButton = select(CAP_BUTTON_SELECTOR);
  const titleElement = select(TITLE_SELECTOR);

  if (titleElement) {
    titleElement.innerHTML = companyData.legalName;
  }

  if (header) {
    header.style.backgroundColor = pageStructure.header.style.backgroundColor;
  }

  if (capButton) {
    const { backgroundColor, color } =
      pageStructure.header.capabilityStatementButton.style;

    capButton.style.backgroundColor = backgroundColor;
    capButton.style.color = color;

    const currentUrl = window.location.href;
    const regex = /(https|http):\/\/(.*?)\.fedgovadv\.info\//;
    const match = currentUrl.match(regex);
    console.log(match);
    if (match) {
      const textFromUrl = match[2];
      capButton.setAttribute("href", `files/${textFromUrl}.pdf`);
    }
  }

  if (navigationButton) {
    navigationButton.style.color = pageStructure.header.navigation.style.color;
  }
  navigationButton.addEventListener("click", () => {
    const icon = select(navigationButton, "i");

    toggleCls(htmlElement, "overflow-hidden");
    toggleCls(icon, "fa-bars", "fa-times");
    toggleCls(navigationButton, "rotate-90");
    toggleCls(navList, "open", "close");
  });
};

const setupHeroSection = () => {
  const hero = select(`[data-section="hero"]`);
  const subsection = select(`[data-section="hero-subsection"]`);

  const { subtitle, message, external } = companyData.hero;

  if (!hero) return;

  if (subtitle) {
    subsection.appendChild(
      create(
        "h3",
        {
          classList: "text-xl capitalize",
          style: {
            color: pageStructure.hero.subtitle.style.color,
            borderBottom: `2px solid ${COLORS.principal_color}`,
            width: "fit-content",
            padding: "0 1rem 0 5px",
          },
        },
        subtitle,
      ),
    );
  }

  subsection.appendChild(
    create("div", {}, [
      create(
        "h1",
        {
          classList: "text-4xl font-bold",
          style: {
            color: "white",
          },
        },
        companyData.legalName,
      ),
      create(
        "div",
        {
          classList: "flex gap-2",
          style: { color: pageStructure.hero.codes.style.color },
        },
        companyData.codes.map((code) => {
          const [key, value] = Object.entries(code)[0];
          if (!value) return;

          return create(
            "p",
            {
              classList: "uppercase text-sm",
            },
            `${key}: ${value}`,
          );
        }),
      ),
    ]),
  );

  if (message) {
    subsection.appendChild(
      create(
        "p",
        {
          classList: "md:w-1/2",
          style: {
            color: "white",
          },
        },
        message,
      ),
    );
  }

  if (external && external.link) {
    subsection.appendChild(
      create("div", {}, [
        create(
          "a",
          {
            classList: "px-4 py-2 rounded-full inline-block hover:shadow-lg",
            style: {
              color: pageStructure.hero.external.style.color,
              backgroundColor:
                pageStructure.hero.external.style.backgroundColor,
            },
            target: "_blank",
            href: external.link,
          },
          [create("button", external.text)],
        ),
      ]),
    );
  }
};

const setupCertificates = () => {
  const certificates = select(`[data-section="certificates"]`);
  const subsection = select(`[data-section="certificates-subsection"]`);

  if (!certificates) return;

  certificates.style.backgroundColor =
    companyData.certificates.attributes.backgroundColor;

  const element = create(
    "div",
    {},
    recursiveChildren(getCertificatesStructure(companyData.certificates)),
  );

  subsection.appendChild(element);
};

const setupAboutSection = () => {
  const about = select(`[data-section="about"]`);
  const subsection = select(`[data-section="about-subsection"]`);
  const { subtitle, title, message, navigation = false } = companyData.about;

  if (!about) return;

  about.style.backgroundColor = pageStructure.about.style.backgroundColor;

  if (navigation) {
    about.setAttribute("data-navigation", navigation);
  }

  if (subtitle) {
    subsection.appendChild(
      create(
        "h3",
        {
          classList: "text-xl capitalize",
          style: {
            color: "white",
            borderBottom: `2px solid ${COLORS.principal_color}`,
            width: "fit-content",
            padding: "0 1rem 0 5px",
          },
        },
        subtitle,
      ),
    );
  }

  subsection.appendChild(
    create("h1", { classList: "text-4xl font-bold text-white" }, title),
  );

  subsection.appendChild(
    create(
      "p",
      {
        classList: "text-white",
      },
      message,
    ),
  );
};

const setupCodeList = () => {
  const codeList = select(`[data-section="code-list"]`);
  const subsection = select(`[data-section="code-list-subsection"]`);

  if (!codeList) return;

  if (companyData.code_list.length == 0) {
    return codeList.remove();
  }

  Object.keys(pageStructure.code_list.style).forEach((key) => {
    codeList.style[key] = pageStructure.code_list.style[key];
  });

  codeList.style.backgroundColor =
    pageStructure.code_list.section.style.backgroundColor;

  companyData.code_list.forEach((section) => {
    const { title, list } = section;
    const { length: ListLength } = list;

    subsection.appendChild(
      create("div", 
        { 
          classList: "mb-4"
        },
        [
        create(
          "h3",
          {
            classList: "text-2xl capitalize font-bold w-fit border-b-2",
            style: pageStructure.code_list.style,
          },
          title,
        ),
        create(
          "div",
          { classList: "mt-2 mt-1 flex flex-col flex-wrap md:flex-row mb-4" },
          list.map((row) =>
            create(
              "p",
              {
                classList: "whitespace-nowrap overflow-x-hidden text-ellipsis w-full",
                style: {
                  width: ListLength >= 30 ? "50%" : undefined
                },
                title: row.join(": ")
              },  
              row.map((text, index) =>
                create(
                  "span",
                  index === 0
                    ? {
                        classList: "w-fit font-bold",
                      }
                    : {},
                  index === 0 ? text + ":" : ` ${text}`,
                ),
              ),
            ),
          ),
        ),
      ]),
    );
  });
};

const setupSectionList = () => {
  const sectionList = select(`[data-section="section-list"]`);
  const subsection = select(`[data-section="section-list-subsection"]`);

  if (!sectionList) return;

  companyData.section_list.forEach((item) => {
    const sectionStyle = getSectionStyle(item);

    if (!sectionStyle) return;

    const section = create(
      sectionStyle.parent.type,
      sectionStyle.parent.attributes ?? {},
      recursiveChildren(sectionStyle.parent.children) ?? [],
    );

    subsection.appendChild(section);
  });
};

const setupSwiper = () => {
  const swiperList = selectAll(`[data-swiper="container"]`);

  swiperList.forEach((swiper) => {
    const swiperPagination = select(swiper, `.swiper-pagination`);
    const swiperButtonNext = select(swiper, `.swiper-button-next`);
    const swiperButtonPrev = select(swiper, `.swiper-button-prev`);

    const mySwiper = new Swiper(swiper, {
      loop: true,
      pagination: {
        el: swiperPagination,
        clickable: true,
      },
      navigation: {
        nextEl: swiperButtonNext,
        prevEl: swiperButtonPrev,
      },
    });
  });
};

const setupNavigation = () => {
  const htmlElement = select("html");
  const header = select(HEADER_SELECTOR);
  const navList = select(NAVIGATION_LIST_SELECTOR);
  const navButton = select(NAVIGATION_BUTTON_SELECTOR);
  const capButton = select(CAP_BUTTON_SELECTOR);
  const homeButton = select(HOME_BUTTON_SELECTOR);
  const homeSection = select(`[data-section="hero"]`);

  const picture = select(header, "picture");
  const img = select(header, "img");
  const pList = selectAll(header, "p");

  const navIcon = select(navButton, "i");

  const sections = selectAll("[data-navigation]");

  if (!navList) return;

  const scrollIntoView = (tag) => {
    const { innerWidth } = window;
    const section = select(`[data-section="${tag}"]`);

    if (!section) return;

    section.scrollIntoView({ behavior: "smooth" });
    removeCls(htmlElement, "overflow-hidden");

    if (innerWidth <= 768) {
      addCls(navButton, "close");
      addCls(navList, "close");
      addCls(navIcon, "fa-bars");

      removeCls(navButton, "open");
      removeCls(navList, "open");
      removeCls(navIcon, "fa-times");
      removeCls(navButton, "rotate-90");
    }
  };

  const watchScroll = () => {
    const { scrollY } = window;

    if (scrollY > 0) {
      addCls(navList, "h-screen", "!top-16");
      addCls(header, "shadow-lg");
      addCls(capButton, "px-3", "py-2", "text-sm");
      addCls(img, "my-1");
      addCls(picture, "!h-10");
      addCls(homeSection, "!pt-16");

      pList.forEach((p) => addCls(p, "text-sm"));
    } else {
      removeCls(navList, "h-screen", "!top-16");
      removeCls(header, "shadow-lg");
      removeCls(capButton, "px-3", "py-2", "text-sm");
      removeCls(img, "my-1");
      removeCls(picture, "!h-10");
      removeCls(homeSection, "!pt-16");

      pList.forEach((p) => removeCls(p, "text-sm"));
    }
  };

  homeButton.addEventListener("click", () => scrollIntoView("hero"));

  sections.forEach((section) => {
    const { navigation } = section.dataset;

    const button = create(
      "p",
      {
        classList: "cursor-pointer duration-300",
        style: pageStructure.header.navigation.list.style,
      },
      navigation.split(":")[1],
    );

    button.addEventListener("click", () => {
      const [tag] = navigation.split(":");
      scrollIntoView(tag);
    });

    navList.appendChild(button);
  });

  const watchResize = () => {
    const { innerWidth } = window;

    if (innerWidth > 768) {
      addCls(navIcon, "fa-bars");

      removeCls(htmlElement, "overflow-hidden");
      removeCls(navButton, "active", "close", "open");
      removeCls(
        navList,
        "active",
        "close",
        "open",
        "[&>p]:!text-white",
        "!h-[calc(100vh-4rem)]",
      );
      removeCls(navIcon, "fa-times");
      removeCls(navButton, "rotate-90");
    } else {
      addCls(navButton, "active", "close");
      addCls(navList, "active", "close", "[&>p]:!text-white");
    }
  };

  const watchHash = () => {
    const hash = window.location.hash.slice(1);

    const element = select(`[data-section="${hash}"]`);

    if (!element) return;

    setTimeout(
      () => history.replaceState("", document.title, window.location.pathname),
      1000,
    );
    element.scrollIntoView({ behavior: "smooth" });
  };

  window.addEventListener("scroll", watchScroll);
  window.addEventListener("resize", watchResize);
  window.addEventListener("hashchange", watchHash);
  watchScroll();
  watchResize();
  watchHash();
};

const setupFooter = () => {
  const footer = create(
    "footer",
    recursiveChildren(getFooterStructure(pageStructure.footer)),
  );

  select("body").appendChild(footer);
};

const init = () => {
  setupBasicInformation();
  setupHeroSection();
  setupCertificates();
  setupAboutSection();
  setupCodeList();

  setupSectionList();

  setupSwiper();
  setupNavigation();

  setupFooter();
};

window.addEventListener("load", init);
