<script setup>
import PublicLocalizedVersionBanner from '~/components/shared/PublicLocalizedVersionBanner.vue'
import { buildPublicJsonLdForRoute } from '~/utils/public-json-ld'

const route = useRoute()
const runtimeConfig = useRuntimeConfig()
const { locale } = usePublicLocale()
const publicJsonLd = ref(await buildPublicJsonLdForRoute(route.path, locale.value))
const gtmId = computed(() => String(runtimeConfig.public.gtmId || '').trim())
const shouldLoadGtm = computed(() => Boolean(gtmId.value) && !import.meta.dev)

watch(
  [() => route.path, () => locale.value],
  async ([path, currentLocale]) => {
    publicJsonLd.value = await buildPublicJsonLdForRoute(path, currentLocale)
  },
  { immediate: false },
)

useHead(() => ({
  script: publicJsonLd.value
    ? [{
        key: 'public-json-ld',
        type: 'application/ld+json',
        innerHTML: JSON.stringify(publicJsonLd.value),
      }]
    : [],
}))

useHead(() => {
  if (!shouldLoadGtm.value) {
    return {}
  }

  return {
    script: [
      {
        key: 'gtm-bootstrap',
        innerHTML: `
          window.dataLayer = window.dataLayer || [];
          window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
        `,
        tagPosition: 'head',
      },
      {
        key: 'gtm-src',
        src: `https://www.googletagmanager.com/gtm.js?id=${gtmId.value}`,
        async: true,
        tagPosition: 'head',
      },
    ],
    noscript: [
      {
        key: 'gtm-noscript',
        innerHTML: `<iframe src="https://www.googletagmanager.com/ns.html?id=${gtmId.value}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
        tagPosition: 'bodyOpen',
      },
    ],
  }
})
</script>

<template>
  <NuxtLayout>
    <NuxtRouteAnnouncer />
    <NuxtPage />
    <PublicLocalizedVersionBanner />
  </NuxtLayout>
</template>
