<script setup lang="ts">
import type {
  PageDataResourceGroup,
  PageDataResourceGroupBtnInfo,
} from '#layers/types/api/pageData'
import type { ButtonType } from '#layers/types/components/button'

interface Props {
  resourcesData: PageDataResourceGroup[]
  pageVerTmplSeq: number
}
const props = defineProps<Props>()

const { locale } = useI18n()
const { sendLog, useAnalyticsLogDataDirect } = useAnalytics()

const getBtnType = (item?: PageDataResourceGroupBtnInfo): ButtonType => {
  const t = item?.detail?.btn_type
  const target = item?.detail?.action?.link_target
  if (t === 'URL' && target)
    return target === '_blank' ? 'external' : 'internal'
  if (t === 'DOWNLOAD') return 'download'
  return 'action'
}

const getBgColor = (item?: PageDataResourceGroupBtnInfo): string =>
  getColorCode({
    colorName: item?.color_name_btn,
    colorCode: item?.color_code_btn,
  })

const getTextColor = (item?: PageDataResourceGroupBtnInfo): string =>
  getColorCode({
    colorName: item?.color_name_txt,
    colorCode: item?.color_code_txt,
  })

const handleLogClick = (index: number) => {
  sendLog(
    locale.value,
    useAnalyticsLogDataDirect(props.resourcesData[index], props.pageVerTmplSeq)
  )
}

// 편의상
const buttonList = computed(() => props.resourcesData || [])
</script>

<template>
  <div
    v-if="buttonList.length"
    class="flex flex-wrap justify-center gap-3 md:gap-4"
  >
    <template v-for="(button, index) in buttonList" :key="index">
      <AtomsButtonLauncher
        v-if="button.btn_info?.detail?.btn_type === 'RUN'"
        type="duplication"
        :platform="button.btn_info?.detail?.market_type"
        :background-color="getBgColor(button.btn_info)"
        :text-color="getTextColor(button.btn_info)"
        :disabled="button?.btn_info?.disabled"
        @click="handleLogClick(index)"
      >
        {{ button.btn_info?.txt_btn_name }}
      </AtomsButtonLauncher>
      <AtomsButton
        v-else
        :type="getBtnType(button.btn_info)"
        :href="button.btn_info?.detail?.action?.url"
        :target="button.btn_info?.detail?.action?.link_target"
        :rel="button.btn_info?.detail?.action?.rel"
        :background-color="getBgColor(button.btn_info)"
        :text-color="getTextColor(button.btn_info)"
        :disabled="button?.btn_info?.disabled"
        @click="handleLogClick(index)"
      >
        {{ button.btn_info?.txt_btn_name }}
      </AtomsButton>
    </template>
  </div>
</template>
