<template>
  <RouterView />
  <Toaster position="top-right" :duration="5000" close-button />
  <CookieBanner />
  <CompleteProfileModal
    v-if="authStore.user"
    :is-open="authStore.showCompleteProfile"
    :user="authStore.user"
    @complete="authStore.onProfileComplete"
  />
</template>

<script setup lang="ts">
import { Toaster } from "vue-sonner";
import { useAuthStore } from "@/stores/auth";
import { defineAsyncComponent, computed } from "vue";
import { useHead } from "@unhead/vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";

const CompleteProfileModal = defineAsyncComponent(() => import("@/components/CompleteProfileModal.vue"));
const CookieBanner = defineAsyncComponent(() => import("@/components/CookieBanner.vue"));

const { t, locale, availableLocales } = useI18n();
const authStore = useAuthStore();
const route = useRoute();

const domain = 'https://radionica3d.me';

const canonicalUrl = computed(() => {
  const path = route.path === '/' ? '' : route.path.replace(/\/$/, '');
  return `${domain}${path}`;
});

const alternateLinks = computed(() => {
  const pathWithoutLang = route.path.replace(/^\/(en|me|ru|ua)/, '') || '/';
  const links = availableLocales.map(lang => ({
    rel: 'alternate' as const,
    hreflang: lang,
    href: `${domain}/${lang}${pathWithoutLang.replace(/\/$/, '')}`
  }));
  
  // Add x-default
  links.push({
    rel: 'alternate' as const,
    hreflang: 'x-default',
    href: `${domain}/me${pathWithoutLang.replace(/\/$/, '')}`
  });
  
  return links;
});

// Skip auth initialization and unnecessary pings during prerendering
const isPrerendering = (window as any).__PRERENDER_INJECTED !== undefined;
if (!isPrerendering) {
  authStore.init();
}

// Global SEO Defaults
useHead({
  titleTemplate: (title: string | undefined) => title ? `${title} | Radionica 3D` : 'Radionica 3D',
  htmlAttrs: {
    lang: computed(() => locale.value)
  },
  meta: [
    { name: 'description', content: computed(() => t('hero.description')) },
    { property: 'og:type', content: 'website' },
    { property: 'og:site_name', content: 'Radionica 3D' },
    { property: 'og:url', content: canonicalUrl },
    { property: 'og:image', content: 'https://radionica3d.me/og-image.jpg' },
    { name: 'twitter:card', content: 'summary_large_image' },
    { name: 'twitter:url', content: canonicalUrl },
  ],
  link: computed(() => [
    { rel: 'canonical' as const, href: canonicalUrl.value },
    ...alternateLinks.value
  ])
});
</script>
