import { useHead } from '@vueuse/head'
import { useRoute } from 'vue-router'
import { ref, watch, computed } from 'vue'
import { seoConfig } from '@/seo.config'
import { getImageUrl } from '@/utils/imageUrl'

export function useAutoSeo() {
  const route = useRoute()
  const dynamicData = ref<any>(null)

  const routeConfig = computed(() => {
    const routeName = route.name as string
    return seoConfig[routeName] || null
  })

  const seoMeta = computed(() => {
    if (!routeConfig.value) {
      return {
        title: 'Профессиональный спорт',
        description: 'Сайт о спорте и тренерах'
      }
    }

    const config = routeConfig.value
    const siteUrl = 'https://profbody.uz'
    const currentUrl = `${siteUrl}${route.path}`

    let ogImage = config.ogImage || ''
    if (ogImage && !ogImage.startsWith('http')) {
      ogImage = getImageUrl(ogImage)

      if (!ogImage.startsWith('http')) {
        ogImage = `${siteUrl}${ogImage}`
      }
    }

    return {
      title: config.title,
      description: config.description,
      keywords: config.keywords,
      ogImage,
      ogType: config.ogType || 'website',
      canonical: config.canonical || currentUrl
    }
  })

  const applySeo = () => {
    const meta = seoMeta.value

    useHead({
      title: meta.title,
      meta: [
        {
          name: 'description',
          content: meta.description || ''
        },
        {
          property: 'og:locale',
          content: 'ru_RU'
        },
        {
          property: 'og:type',
          content: meta.ogType || 'website'
        },
        {
          property: 'og:title',
          content: meta.title
        },
        {
          property: 'og:description',
          content: meta.description || ''
        },
        {
          property: 'og:url',
          content: meta.canonical || `https://profbody.uz${route.path}`
        },
        {
          property: 'og:site_name',
          content: 'Людмила Богатырь и Александр Сахаров'
        },
        {
          property: 'og:image',
          content: meta.ogImage || 'https://profbody.uz/default-og-image.jpg'
        },
        {
          name: 'twitter:card',
          content: 'summary_large_image'
        },
        {
          name: 'twitter:title',
          content: meta.title
        },
        {
          name: 'twitter:description',
          content: meta.description || ''
        },
        {
          name: 'twitter:image',
          content: meta.ogImage || 'https://profbody.uz/default-og-image.jpg'
        }
      ],
      link: [
        {
          rel: 'canonical',
          href: meta.canonical || `https://profbody.uz${route.path}`
        }
      ]
    })
  }

  watch(
    () => [route.name, route.params],
    () => {
      applySeo()
    },
    { immediate: true }
  )

  return { seoMeta }
}
