var seoService = (function () {
  function createLink(rel, href) {
    const link = document.createElement("link");
    link.rel = rel;
    link.href = href;
    return link;
  };

  function getVehicleDate(year, month, locale) {
    const isValidYear = year > 0;
    const isValidMonth = month > 0 && month < 13;

    if (!isValidYear && !isValidMonth) return "";

    const releaseDate = new Date();
    if (isValidYear) {
      releaseDate.setFullYear(year);
    }
    if (isValidMonth) {
      releaseDate.setMonth(month - 1);
    }

    return releaseDate.toLocaleDateString(locale, {
      year: isValidYear ? "numeric" : undefined,
      month: isValidMonth ? "long" : undefined,
    });
  };

  return {
    init: function () {
      const url = `https://eu.api.oneweb.mercedes-benz.com/css/bootstrap?referrer=${window.location.href}&version=${self.crypto.randomUUID()}`;

      fetch(url).then((res) => res.json())
        .then((seo) => {
          const vehicleDate = getVehicleDate(seo.year, seo.month, seo.locale);
          const title = seo.title.replace("{date}", vehicleDate);
          const description = seo.description.replace("{date}", vehicleDate);
          this.addOrUpdateMeta("robots", seo.robots);
          this.updateTitle(title);
          this.addOrUpdateMeta("description", description);
          this.addOrUpdateLinkRelCanonical(seo.canonicalUrl);
          this.addOrUpdateOpenGraph("og:title", title);
          this.addOrUpdateOpenGraph("og:type", "website");
          this.addOrUpdateOpenGraph("og:image", seo.imageUrl);
          this.addOrUpdateOpenGraph("og:url", seo.canonicalUrl);
          this.addOrUpdateOpenGraph("og:description", description);
          this.addOrUpdateOpenGraph("og:locale", seo.locale);
          this.addOrUpdateOpenGraph("og:video", seo.videoUrl);
          this.removeLinkAlternates();
          this.addLinkAlternates(seo.alternates);
          this.addOrUpdateStructuredData(seo);
        });
    },
    addPreloadImages: function () {
      if (!window.aemNamespace) {
        return;
      }
      const assetUri = window.aemNamespace.environmentVariables.assetUri;
      const location = window.location.href;
      if (location.match(/(faq\.html|faq-sirius\.html)$/)) {
        document.head.insertAdjacentHTML(
          "afterbegin",
          `
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/faq-header.webp" media="(min-width: 768px)" />
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/faq-header-mobile.webp" media="(max-width: 767px)" />
          `
        );
      }

      if (location.match(/(manuals\.html)$/)) {
        document.head.insertAdjacentHTML(
          "afterbegin",
          `
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/oom-header.webp" media="(min-width: 768px)" />
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/oom-header-mobile.webp" media="(max-width: 767px)" />
          `
        );
      }

      if (location.includes("faq.html")) {
        document.head.insertAdjacentHTML(
          "afterbegin",
          `
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/faq-footer.webp" media="(min-width: 768px)" />
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/faq-footer-mobile.webp" media="(max-width: 767px)" />
          `
        );
      }

      if (location.includes("manuals.html")) {
        document.head.insertAdjacentHTML(
          "afterbegin",
          `
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/oom-footer.webp" media="(min-width: 768px)" />
            <link rel="preload" as="image" href="${assetUri}/css-css-oom/latest/oom-footer-mobile.webp" media="(max-width: 767px)" />
          `
        );
      }
    },
    updateTitle: function (title) {
      if (title) {
        document.title = title;
      }
    },
    addOrUpdateMeta: function (name, content) {
      if (content) {
        const tag = document.querySelector(`meta[name="${name}"]`);
        if (tag) {
          tag.content = content;
        } else {
          const meta = document.createElement("meta");
          meta.name = name;
          meta.content = content;
          document.head.appendChild(meta);
        }
      }
    },
    addOrUpdateLinkRelCanonical: function (href) {
      if (href) {
        const tag = document.querySelector("link[rel='canonical']");
        if (tag) {
          tag.href = href;
        } else {
          document.head.appendChild(createLink("canonical", href));
        }
      }
    },
    addOrUpdateStructuredData: function (seo) {
      if (seo.structuredData) {
        const tag = document.querySelector("script[type='application/ld+json']");
        const innerText = seo.structuredData.replace("{date}", getVehicleDate(seo.year, seo.month, seo.locale));
        if (tag) {
          tag.innerText = innerText;
        } else {
          const script = document.createElement("script");
          script.type = "application/ld+json";
          script.innerText = innerText;
          document.head.appendChild(script);
        }
      }
    },
    addOrUpdateOpenGraph: function (property, content) {
      if (content) {
        const tag = document.querySelector(`meta[property='${property}']`);
        if (tag) {
          tag.content = content;
        } else {
          const meta = document.createElement("meta");
          meta.setAttribute("property", property);
          meta.content = content;
          document.head.appendChild(meta);
        }
      }
    },
    addLinkAlternates: function (alternates) {
      for (const [locale, url] of Object.entries(alternates)) {
        const link = createLink("alternate", url);
        link.setAttribute("hreflang", locale);
        document.head.appendChild(link);
      }
    },
    removeLinkAlternates: function () {
      for (const link of document.querySelectorAll("link[rel='alternate']")) {
        link.remove();
      }
    },
  };
})();

seoService.addPreloadImages();
seoService.addOrUpdateLinkRelCanonical(window.location.href);
seoService.init();
