<script setup lang="ts">
import { SplideSlide } from '@splidejs/vue-splide'
import { getComponentGroup, getComponentGroupAry } from '#layers/utils/dataUtil'
import type { PageDataTemplateComponents } from '#layers/types/api/pageData'

// Types
type Platform = 'google_play' | 'app_store' | 'pc' | 'stove'

// Props
interface Props {
  components: PageDataTemplateComponents
  pageVerTmplSeq: number
}
const props = defineProps<Props>()

// Configuration
const runtimeConfig = useRuntimeConfig()
const runType = runtimeConfig.public.runType
const staticUrl = runtimeConfig.public.staticUrl
const multilingualBaseApiUrl = `${staticUrl}/${runType}/test`
const multilingualFileName = 'test_homepage_brand_download.json'

// Multilingual
const resultGetMultilingual = await useGetMultilingual({
  baseApiUrl: multilingualBaseApiUrl,
  fileName: multilingualFileName,
})
const { tm, locale }: any = useI18n({
  useScope: 'local',
  messages: Object(resultGetMultilingual?.value?.multilingual),
})

// Composables
const device = useDevice()
const breakpoints = useResponsiveBreakpoints()
const { checkPCSpec } = useCheckPCSpec(tm)

// Store
const gameDataStore = useGameDataStore()
const { gameData } = storeToRefs(gameDataStore)

// Data
const backgroundData = computed(() =>
  getComponentGroup(props.components, 'background')
)
const specCheckData = computed(() =>
  getComponentGroupAry(props.components, 'tablePcSpecTool')
)
const schemeFormatData = computed(
  () => specCheckData.value[0]?.display?.text || ''
)
const setupUrlData = computed(() => specCheckData.value[1]?.display?.text || '')

// Refs
const specPCRef = ref<HTMLElement | null>(null)
const specMobileRef = ref<HTMLElement | null>(null)
const driverArray = ref<Array<string>>([
  'DirectX',
  'NVIDIA',
  'AMD',
  'intel',
  'Visual',
])
const pcSpecArray = ref<Array<string>>([
  'Os',
  'Cpu',
  'Vga',
  'Ram',
  'Directx',
  'Hdd',
])
const mobileSpecArray = ref<Array<string>>(['Android', 'Ios'])
const mobileOSArray = ref<Array<string>>(['AOS', 'iOS'])

// Computed
const platformList = computed(() => {
  if (breakpoints.value.isMobile) {
    return ['MOBILE', 'PC', 'STOVE']
  } else {
    return ['PC', 'STOVE', 'MOBILE']
  }
})
const driverList = computed(() =>
  driverArray.value.map(driver => ({
    id: `DRIVER_${driver}`,
    driverCode: driver,
    driverText: tm(`Download_Driver_${driver}`),
  }))
)
const pcSpecList = computed(() =>
  pcSpecArray.value.map(data => ({
    id: `PC_TABLE_ITEM_${data}`,
    itemCode: data,
    itemText: tm(`Download_Table_${data}`),
    itemData: getComponentGroupAry(props.components, `tablePcSpec${data}`),
  }))
)
const mobileSpecList = computed(() =>
  mobileSpecArray.value.map(data => ({
    id: `MO_TABLE_ITEM_${data}`,
    itemCode: data,
    itemText: tm(`Download_Table_${data}`),
    itemData: getComponentGroupAry(props.components, `tableMoSpec${data}`),
  }))
)
const mobileOSList = computed(() =>
  mobileOSArray.value.map(os => ({
    id: `MO_OS_${os}`,
    osCode: os,
    osText: tm(`Download_${os}_OS`),
    platformCode: tm(`Download_${os}_Platform`),
    platformText: tm(`Download_${os}_Name`),
    isValue: device[tm(`Download_${os}_IsValue`) as keyof typeof device],
  }))
)

// Functions
/**
 * 입력한 pc, mobile 인자값에 따라 해당 최소사양&권장사양 테이블로 포커스 스크롤 이동합니다.
 * @param target<string> 'pc' | 'mobile'
 */
const handleMoveFocus = (target: 'pc' | 'mobile') => {
  const refs: Record<string, HTMLElement | null> = {
    pc: specPCRef.value,
    mobile: specMobileRef.value,
  }

  const adjustedOffset: number = breakpoints.value.isMobile ? 80 : 100
  const adjustedOffsetTop: number =
    refs[target]?.getBoundingClientRect().top + window.scrollY - adjustedOffset

  window.scrollTo({ top: adjustedOffsetTop, behavior: 'smooth' })
}
</script>

<template>
  <WidgetsFixMainTitle
    :title="tm('Download_Page_Title')"
    :resources-data="backgroundData"
  />

  <div class="section-container static">
    <section class="section-static">
      <WidgetsFixSubTitle :title="tm('Download_Section_Platform_Title')" />

      <BlocksSlideDefault
        :per-page="platformList.length"
        :gap="20"
        :arrows="false"
        :pagination="false"
        :drag="false"
        :breakpoints="{
          1023: {
            perPage: 'auto',
            gap: 12,
            focus: 0,
            drag: true,
            padding: { left: 0, right: 0 },
          },
        }"
        class="overflow-hidden w-[100vw] px-[20px] ml-[-20px] mt-[16px] sm:px-[40px] sm:ml-[-40px] md:w-full md:px-0 md:mt-[24px] md:ml-0"
      >
        <SplideSlide
          v-for="platform in platformList"
          :key="platform"
          class="flex flex-col items-center justify-between shrink-0 whitespace-normal w-[295px] h-[280px] bg-[#FFFFFF] p-[20px] rounded-[12px] text-left md:w-[calc((100%-40px)/3)] md:h-[314px] md:p-[24px] md:rounded-[16px] lg:w-[420px] lg:h-[340px] lg:p-[32px]"
        >
          <div
            class="flex flex-col items-start justify-start gap-[8px] w-full md:gap-[12px]"
          >
            <WidgetsFixSubTitle :title="tm(`Download_Box_${platform}_Title`)" />

            <p
              v-if="
                tm(`Download_Box_${platform}_Description_List`).length === 1
              "
              v-dompurify-html="tm(`Download_Box_${platform}_Description01`)"
              class="text-[#999999] text-[14px] font-[400] leading-[24px] tracking-[-0.42px] md:text-[15px] md:tracking-[-0.45px]"
            ></p>
            <ul
              v-else-if="
                tm(`Download_Box_${platform}_Description_List`).length > 1
              "
            >
              <li
                v-for="description in tm(
                  `Download_Box_${platform}_Description_List`
                )"
                :key="description"
                v-dompurify-html="tm(description)"
                class="relative pl-[22px] before:content-[''] before:absolute before:top-[10px] before:left-[9px] before:w-[3px] before:h-[3px] before:rounded-full before:bg-[#999999] text-[#999999] text-[14px] font-[400] leading-[24px] tracking-[-0.42px] md:text-[15px] md:tracking-[-0.45px]"
              ></li>
            </ul>

            <AtomsButton
              v-if="platform !== 'STOVE'"
              type="action"
              button-size="size-small"
              background-color="transparent"
              text-color="#1F1F1F"
              class="relative w-auto h-auto px-0 text-[16px] font-[500] leading-[24px] tracking-[-0.48px] before:content-[''] before:absolute before:z-[2] before:top-p before:left-0 before:w-full before:h-full before:bg-[#FFFFFF] before:transition-opacity before:duration-300 before:ease-in-out before:opacity-0 hover:before:opacity-20"
              @click="
                handleMoveFocus(platform.toLowerCase() as 'pc' | 'mobile')
              "
            >
              <span>{{ tm(`Download_Box_${platform}_SpecCheck`) }}</span>
              <AtomsIconsLongArrowRightLine
                :size="20"
                color="#1F1F1F"
                class="relative rotate-90"
              />
            </AtomsButton>
          </div>

          <div
            class="flex flex-col items-center justify-center gap-[8px] w-full md:gap-[12px]"
          >
            <template v-if="platform === 'MOBILE'">
              <template v-for="os in mobileOSList" :key="os.id">
                <AtomsButtonLauncher
                  v-if="device.isMobile ? os.isValue : true"
                  :platform="`${os.platformCode as Platform}`"
                  class="!w-full"
                >
                  <span>{{ os.platformText }}</span>
                </AtomsButtonLauncher>
              </template>
            </template>
            <template v-else>
              <AtomsButton
                v-if="breakpoints.isMobile"
                type="action"
                button-size="size-small"
                background-color="#EBEBEB"
                text-color="#999999"
                :disabled="true"
                class="w-full px-0 border border-solid border-[rgba(0,0,0,0.1)] cursor-default"
              >
                <span>{{ tm(`Download_Button_${platform}_Mobile`) }}</span>
              </AtomsButton>
              <AtomsButtonLauncher
                v-else-if="breakpoints.isMd || breakpoints.isDesktop"
                :platform="`${platform.toLowerCase() as Platform}`"
                class="!w-full"
              >
                <span>{{ tm(`Download_Button_${platform}`) }}</span>
              </AtomsButtonLauncher>
            </template>
          </div>
        </SplideSlide>
      </BlocksSlideDefault>
    </section>

    <section ref="specPCRef" class="section-static">
      <WidgetsFixSubTitle :title="tm('Download_Section_PC_Title')" />

      <table>
        <thead>
          <tr>
            <th class="w-[80px] md:w-[172px]">
              {{ tm('Download_Table_Item') }}
            </th>
            <th>{{ tm('Download_Table_Min_Spec') }}</th>
            <th>{{ tm('Download_Table_Rec_Spec') }}</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="tr in pcSpecList" :key="tr.id">
            <tr>
              <th class="w-[80px] md:w-[172px]">{{ tr.itemText }}</th>
              <template v-for="td in tr.itemData" :key="td.display.text">
                <td>{{ td.display.text }}</td>
              </template>
            </tr>
          </template>
        </tbody>
      </table>

      <div
        v-if="!breakpoints.isMobile"
        class="relative flex items-end justify-between w-full mt-[24px] gap-[24px]"
      >
        <ul
          v-if="tm('Download_Section_PC_Notice_List').length > 0"
          class="relative flex flex-col items-center justify-start w-full"
        >
          <template
            v-for="notice in tm('Download_Section_PC_Notice_List')"
            :key="notice"
          >
            <li
              v-dompurify-html="tm(notice)"
              class="relative w-full pl-[26px] text-left text-[#666666] text-[16px] font-[400] leading-[26px] tracking-[-0.48px] before:content-[''] before:absolute before:top-[11px] before:left-[10px] before:w-[4px] before:h-[4px] before:bg-[#666666] before:rounded-full"
            ></li>
          </template>
        </ul>
        <AtomsButton
          type="action"
          button-size="size-small"
          background-color="#383838"
          text-color="#FFFFFF"
          class="shrink-0 w-[206px] px-0 text-[16px]"
          @click="
            checkPCSpec({
              schemeFormat: schemeFormatData,
              setupUrl: setupUrlData,
              gameNo: gameData?.game_code?.toString(),
              locale: locale as string,
            })
          "
        >
          <em
            class="inline-flex items-center justify-center gap-[8px] not-italic"
          >
            <span
              class="relative inline-flex items-center justify-center w-[20px] h-[20px]"
            >
              <img
                :src="
                  getImageHost(
                    '/images/common/ic-v2-hardware-desktop-line.svg',
                    { imageType: 'common' }
                  )
                "
                alt="Desktop-Icon"
                loading="lazy"
                draggable="false"
                class="w-full object-contain"
              />
            </span>
            <span>{{ tm('Download_Button_SpecCheck') }}</span>
          </em>
        </AtomsButton>
      </div>
    </section>

    <section v-if="!breakpoints.isMobile" class="section-static">
      <WidgetsFixSubTitle :title="tm('Download_Section_Driver_Title')" />
      <ul class="flex items-center justify-between gap-[20px] w-full">
        <template v-for="driver in driverList" :key="driver.id">
          <li class="w-full h-[250px]">
            <div
              class="flex flex-col items-center justify-between gap-[16px] h-[250px] rounded-[16px] p-[20px] bg-[#FFFFFF]"
            >
              <div class="flex items-center justify-center w-full">
                <img
                  :src="
                    getImageHost(
                      `/images/common/grades_driver/Type-${driver.driverCode}.svg`,
                      { imageType: 'common' }
                    )
                  "
                  :alt="driver.driverText"
                  loading="lazy"
                  draggable="false"
                />
              </div>

              <div
                class="flex flex-col items-start justify-end gap-[16px] w-full"
              >
                <p
                  class="text-left text-[#666666] text-[16px] font-[400] leading-[26px] tracking-[-0.48px]"
                >
                  {{ driver.driverText }}
                </p>

                <AtomsButton
                  type="download"
                  button-size="size-small"
                  background-color="#383838"
                  text-color="#FFFFFF"
                  class="w-full px-0"
                  target="_blank"
                  rel="noopener noreferrer"
                  :href="tm(`Download_Driver_${driver.driverCode}_Url`)"
                >
                  <span>{{ tm('Download_Button_Download') }}</span>
                </AtomsButton>
              </div>
            </div>
          </li>
        </template>
      </ul>
    </section>

    <section ref="specMobileRef" class="section-static">
      <WidgetsFixSubTitle :title="tm('Download_Section_MOBILE_Title')" />
      <table>
        <thead>
          <tr>
            <th rowspan="2" class="w-[80px] md:w-[172px]">
              {{ tm('Download_Table_Item') }}
            </th>
            <th colspan="2">{{ tm('Download_Table_Min_Spec') }}</th>
            <th colspan="2">{{ tm('Download_Table_Rec_Spec') }}</th>
          </tr>
          <tr>
            <th>{{ tm('Download_Table_Device') }}</th>
            <th>{{ tm('Download_Table_Os') }}</th>
            <th>{{ tm('Download_Table_Device') }}</th>
            <th>{{ tm('Download_Table_Os') }}</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="tr in mobileSpecList" :key="tr.id">
            <tr>
              <th class="w-[80px] md:w-[172px]">{{ tr.itemText }}</th>
              <template v-for="td in tr.itemData" :key="td.display.text">
                <td>{{ td.display.text }}</td>
              </template>
            </tr>
          </template>
        </tbody>
      </table>
    </section>
  </div>
</template>

<style scoped>
/* 고정형 페이지 Table Style */
table {
  @apply w-full h-auto border-collapse border-spacing-0 table-fixed;
}
table th {
  @apply py-[8px] px-[12px] border border-[#D9D9D9] bg-[#FAFAFA] text-[#1F1F1F] text-[14px] font-bold leading-[24px] tracking-[-0.42px]
  md:py-[11px] md:px-[20px] md:text-[16px] md:leading-[26px] md:tracking-[-0.48px];
}
table td {
  @apply h-[64px] py-[8px] px-[12px] border border-[#D9D9D9] bg-[#FFFFFF] text-[#666666] text-[14px] font-[400] leading-[24px] tracking-[-0.42px]
  md:h-[80px] md:py-[14px] md:px-[20px] md:text-[16px] md:leading-[26px] md:tracking-[-0.48px];
}

/* 플랫폼별 다운로드 Mobile Overflow Visible 처리 */
.splide :deep(.splide__track) {
  overflow: visible !important;
}
</style>
