<script setup lang="ts">
import { useTemplateRegistry } from '#layers/composables/useTemplateRegistry'
import type {
  PageDataValue,
  PageDataTemplate,
  PageDataMetaTag,
} from '#layers/types/api/pageData'

interface Props {
  pageData: PageDataValue
}

const props = defineProps<Props>()
const { locale } = useI18n()

const mainRef = ref<HTMLElement>()

// 템플릿 레지스트리 사용
const { getTemplateComponent } = useTemplateRegistry()

// 개별 메타 태그 표시 여부 확인
const shouldShowMetaTag = computed(() => props.pageData.meta_tag_type === 2)

// 템플릿 표시 여부 확인
const isTemplateVisible = (template: PageDataTemplate): boolean => {
  return Boolean(
    template?.page_ver_tmpl_json &&
      Object.keys(template?.page_ver_tmpl_json).length > 0
  )
}

// 템플릿 목록 계산
const visibleTemplates = computed(() =>
  Object.values(props.pageData.templates).filter(isTemplateVisible)
)

// SEO 메타 태그 설정
const setupSeoMeta = (metaTag: PageDataMetaTag) => {
  useSeoMeta({
    title: metaTag?.page_title ?? '',
    description: metaTag?.page_desc ?? '',
    ogTitle: metaTag?.og_title ?? '',
    ogDescription: metaTag?.og_desc ?? '',
    ogImage: metaTag?.og_image ?? '',
    twitterTitle: metaTag?.x_title ?? '',
    twitterImage: metaTag?.x_image ?? '',
    twitterDescription: metaTag?.x_desc ?? '',
  })
}

onMounted(() => {
  const { sendLog } = useAnalytics()
  sendLog(locale.value, useAnalyticsLogDataDirect('view', 1))
})

// 메타 태그 설정 감시
watchEffect(() => {
  if (shouldShowMetaTag.value && props.pageData?.meta_tag_json) {
    setupSeoMeta(props.pageData?.meta_tag_json)
  }
})

</script>

<template>
  <main ref="mainRef" class="main">
    <template
      v-for="(template, index) in visibleTemplates"
      :key="template.template_code ?? index"
    >
      <component
        :is="getTemplateComponent(template.template_code)"
        :components="template.page_ver_tmpl_json"
        :page-ver-tmpl-seq="template.page_ver_tmpl_seq"
      />
    </template>
    <BlocksUtileContainer
      :parent-ref="mainRef"
      :is-show-top-btn="pageData.use_top_btn ?? false"
      :is-show-sns-btn="pageData.use_sns_btn ?? false"
    />
  </main>
</template>

<style scoped>
.main {
  @apply relative pt-[48px] md:pt-[64px];
}
</style>
