<script setup lang="ts">
import type {
  ButtonSize,
  ButtonConfig,
  ButtonProps,
} from '#layers/types/components/button'
import type { GameDataKeyCodeCodes } from '#layers/types/api/gameData'

const props = withDefaults(defineProps<ButtonProps>(), {
  size: 'medium',
  backgroundColor: 'var(--primary)',
  textColor: 'var(--text-primary)',
  icon: '',
  disabled: false,
})

// 색상 코드 키 목록 key_code_codes
const PARSED_KEY_CODE_CODES_KEYS: (keyof GameDataKeyCodeCodes)[] = [
  'primary',
  'text-primary',
  'text-secondary',
  'alternative-01',
  'alternative-02',
]

// 버튼 크기별 설정 상수
const BUTTON_CONFIGS: Record<ButtonSize, ButtonConfig> = {
  large: {
    padding: 'px-10',
    height: 'h-16',
    text: 'text-lg',
    rounded: 'rounded-lg',
  },
  medium: {
    padding: 'px-10',
    height: 'h-14',
    text: 'text-base',
    rounded: 'rounded-lg',
  },
  small: {
    padding: 'px-10',
    height: 'h-12',
    text: 'text-sm',
    rounded: 'rounded-lg',
  },
  'extra-small': {
    padding: 'px-6',
    height: 'h-10',
    text: 'text-sm',
    rounded: 'rounded',
  },
} as const

// 색상 값을 CSS 변수로 변환하는 헬퍼 함수
const getColorValue = (color: string) =>
  PARSED_KEY_CODE_CODES_KEYS.includes(color as keyof GameDataKeyCodeCodes)
    ? `var(--${color})`
    : color

const currentConfig = computed(() => BUTTON_CONFIGS[props.size])
const buttonClasses = computed(() => [
  'group relative inline-flex items-center justify-center font-medium border border-gray-600/30 overflow-hidden',
  `${currentConfig.value.padding} ${currentConfig.value.height} ${currentConfig.value.text} ${currentConfig.value.rounded}`,
  props.disabled ? 'cursor-default' : 'cursor-pointer',
])
const buttonStyles = computed(() => ({
  backgroundColor: getColorValue(props.backgroundColor),
  color: getColorValue(props.textColor),
}))
const overlayClasses = computed(() => [
  'absolute inset-0 -m-px transition-opacity duration-200',
  props.disabled
    ? 'opacity-20 z-10'
    : 'bg-white opacity-0 group-hover:opacity-20',
  currentConfig.value.rounded,
])
const overlayDisabledStyles = computed(
  () =>
    props.disabled && {
      backgroundColor: props.textColor,
    }
)
const contentDisabledStyles = computed(() => props.disabled && { opacity: 0.2 })
</script>

<template>
  <button
    :class="buttonClasses"
    :style="buttonStyles"
    :disabled="props.disabled"
  >
    <!-- 호버 효과 / Disabled 오버레이 -->
    <span :class="overlayClasses" :style="overlayDisabledStyles" />

    <!-- 버튼 내용 -->
    <span
      class="relative flex items-center gap-2"
      :style="contentDisabledStyles"
    >
      <slot />
      <span v-if="props.icon" class="flex-shrink-0" v-html="props.icon" />
    </span>
  </button>
</template>
