<template>
  <div class="inline relative">
    <ColorPicker
      picker-type="chrome"
      shape="square"
      format="hex8"
      :is-widget="false"
      v-bind="{
        ...$attrs,
        ...props
      }"
      :lang="config.lang"
      :theme="config.theme"
      ref="pickerRef"
    />
    <div class="inline flex items-center justify-center" @click="onClick">
      <slot name="trigger"></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, useSlots, onMounted } from 'vue'
import { ColorPicker, type ColorPickerProps } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import { useAppStore } from '@/store/modules/app'

const props = defineProps<ColorPickerProps>()

const appStore = useAppStore()
const config = computed(
  (): {
    lang: 'ZH-cn' | 'En'
    theme: 'black' | 'white'
  } => {
    return {
      lang: appStore.lang === 'zh_CN' ? 'ZH-cn' : 'En',
      theme: appStore.theme === 'dark' ? 'black' : 'white'
    }
  }
)

const pickerRef = ref<InstanceType<typeof ColorPicker>>()
const slots = useSlots()

const onClick = () => {
  pickerRef.value?.onShowPicker()
}

onMounted(() => {
  if (slots.trigger && pickerRef.value?.colorCubeRef?.style) {
    pickerRef.value.colorCubeRef.style.width = '1px'
    pickerRef.value.colorCubeRef.style.height = '0px'
    pickerRef.value.colorCubeRef.style.position = 'absolute'
  } else if (pickerRef.value?.colorCubeRef?.style) {
    pickerRef.value.colorCubeRef.style.width = '24px'
    pickerRef.value.colorCubeRef.style.borderRadius = '4px'
  }
})
</script>
