<template>
  <div
    ref="boxRef"
    :style="styleMap?.mainStyle"
    class="w-full h-full relative overflow-hidden box-border flex items-center"
    :class="
      styleMap?.mainStyle?.textAlign === 'left'
        ? 'justify-start'
        : styleMap?.mainStyle?.textAlign === 'right'
          ? 'justify-end'
          : 'justify-center'
    "
  >
    <ImageBg :src="styleMap?.mainStyle?.imageSrc" :imageStyle="styleMap?.mainStyle?.imageStyle" />
    <span
      ref="txtRef"
      class="z-2 lv_button_txt whitespace-pre!"
      :style="{ fontFamily: textStyle.fontFamily, fontSize: textStyle.fontSize }"
      v-html="innerText"
    ></span>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { symbols } from '@/constants'
import { useWidgetStyle } from '../hooks/useWidgetStyle'
import ImageBg from '../ImageBg.vue'
import { useLongMode } from '../hooks/useLongMode'
import { useLanguage } from '../hooks/useLanguage'

const props = defineProps<{
  width: number
  height: number
  text?: string
  styles: any
  state?: string
  part?: string
  longMode?: 'circular' | 'clip' | 'dot' | 'scroll' | 'wrap'
}>()

const txtRef = ref<HTMLSpanElement>()
const boxRef = ref<HTMLDivElement>()
const { resolveText, getTextStyle } = useLanguage()

// 处理symbol图标
const innerText = computed(() => {
  const text = resolveText(props.text, true).text
  const pattern = /\{LV[^}]*\}/g
  const matches = text.match(pattern)
  const map: Record<string, string> = {}
  matches?.forEach((match) => {
    const key = match.replace('{', '').replace('}', '')
    const value = symbols.find((item) => item.label === key)?.value
    map[match] = value || match
  })
  return text.replace(pattern, (match) => `<i class="lvgl-icon not-italic" >${map[match]}</i>`)
})

const textStyle = getTextStyle(
  () => undefined,
  () => props.text
)

const styleMap = useWidgetStyle({
  widget: 'lv_button',
  props
})

useLongMode(txtRef, boxRef, props)
</script>

<style scoped>
.lv_button_txt::-webkit-scrollbar {
  display: none;
}
</style>
