<script setup lang="ts">
import { useGameDataStore } from '#layers/stores/useGameDataStore'

let cpHeader: any = null

const runtimeConfig = useRuntimeConfig()
const { locale, availableLocales } = useI18n()
const { gameData } = useGameDataStore()

const stoveInflowPath = runtimeConfig.public.stoveInflowPath
const stoveGameNo = runtimeConfig.public.stoveGameNo
const stoveGnbData = gameData?.stove_gnb_json

const languageCodes = computed(() => {
  if (Array.isArray(availableLocales)) {
    return availableLocales.map(
      (localeCode: any) => localeCode.code || localeCode
    )
  }
  return [locale]
})

const loadGnb = (locale: string) => {
  locale = locale.toLowerCase()

  const gnbOption = {
    wrapper: '#stove-wrap',
    isResponsive: true,
    skin: stoveGnbData?.skin_type || 'gnb-dark-mini',
    widget: {
      gameListAndService: false,
      languageSelect: false,
      notification: false,
      stoveDownload: false,
    },
    global: {
      userGds: true,
      defaultSelectedLanguage: locale || 'en',
      languageCoverages: languageCodes.value,
    },
    loginMethod: {
      params: {
        inflow_path: stoveInflowPath,
        game_no: stoveGameNo,
        show_play_button: stoveGnbData?.stove_install_button_visible || 'Y',
      },
      redirectCurrentPage: true,
      windowTitle: undefined,
    },
  }

  cpHeader = new (window as any).cp.Header(gnbOption)
  cpHeader.render()
}

onMounted(() => {
  loadGnb(locale.value)
})

onBeforeUnmount(() => {
  if (cpHeader && typeof cpHeader.destroy === 'function') {
    cpHeader.destroy()
  }
  cpHeader = null
})
</script>

<template>
  <div id="stove-wrap" class="relative z-[5]" />
</template>
