import type Page from "~~/types/collection/page";
import type { ComponentTypes } from "~~/types/component/baseComponent";

export const useSitemap = () => {
  const { navbar, footer } = useGlobal();
  const pages = useState<Page[]>("sitemap_pages");

  const sitemap = ref<sitemap>([]);

  for (const element of navbar.value?.navbar_items ?? []) {
    if (!element.default_active_child) {
      sitemap.value.push({
        path: element.URL.startsWith("/") ? element.URL : `/${element.URL}`,
        origin: "navbar",
        document: element?.page?.documentId,
        hasCollection: element.page.content.filter((c: ComponentTypes) => c.__component == "shared.list").length != 0,
      });
    }
    for (const subelement of element.navbar_sub_items) {
      let url = `${element.URL}/${subelement.URL}`;
      sitemap.value.push({
        path: url.startsWith("/") ? url : `/${url}`,
        origin: "navbar",
        document: subelement?.page?.documentId,
        hasCollection:
          subelement?.page?.content.filter((c: ComponentTypes) => c.__component == "shared.list").length != 0,
      });
    }
  }

  for (const element of pages.value) {
    let url = element.slug.replaceAll("~", "/");
    if (!sitemap.value.find((a) => a.path == url)) {
      sitemap.value.push({
        path: url.startsWith("/") ? url : `/${url}`,
        origin: "page",
        document: element.documentId,
        hasCollection: element.content.filter((c: ComponentTypes) => c.__component == "shared.list").length != 0,
      });
    }
  }

  for (const element of footer.value?.links ?? []) {
    let url = element.URL.startsWith("/") ? element.URL : `/${element.URL}`;
    if (!sitemap.value.find((a) => a.path == url) && !element.URL.startsWith("http")) {
      sitemap.value.push({
        path: url,
        origin: "footer",
        document: undefined,
        hasCollection: undefined,
      });
    }
  }

  return sitemap;
};

type sitemap = Array<{
  path: string;
  origin: string;
  document?: string;
  hasCollection?: boolean;
}>;
