<template>
  <button
    class="fullscreen-toggle"
    @click="toggleFullscreen"
    @keydown.esc="handleEscape"
    :aria-label="isFullscreen ? '退出全屏' : '进入全屏'"
  >
    <svg :width="w" :height="h" viewBox="0 0 24 24" :fill="color">
      <!-- 进入全屏图标 -->
      <path v-if="!isFullscreen" d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
      <!-- 退出全屏图标 -->
      <path v-else d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z" />
    </svg>
  </button>
</template>

<script setup lang="ts">
import { PropType, computed, onBeforeMount, onMounted, ref, toRefs } from 'vue'
import { CreateComponentType } from '@/packages/index.d'
import screenfull from 'screenfull'

const props = defineProps({
  chartConfig: {
    type: Object as PropType<CreateComponentType>,
    required: true
  }
})
const isFullscreen = ref(false)

const { w, h } = toRefs(props.chartConfig.attr)
const { color } = toRefs(props.chartConfig.option)
const toggleFullscreen = () => {
  if (!screenfull.isEnabled) {
    console.warn('当前浏览器不支持全屏API')
    return
  }

  screenfull.toggle(document.documentElement)
}

// 处理键盘事件
const handleKeydown = (e: any) => {
  if (e.key === 'F11') {
    e.preventDefault()
    toggleFullscreen()
  }
}

// 状态同步
const updateFullscreenStatus = () => {
  isFullscreen.value = screenfull.isFullscreen
}

const handleEscape = () => isFullscreen.value && toggleFullscreen()

onBeforeMount(() => {
  if (screenfull.isEnabled) {
    screenfull.off('change', updateFullscreenStatus)
    document.removeEventListener('keydown', handleKeydown)
  }
})

onMounted(() => {
  if (screenfull.isEnabled) {
    screenfull.on('change', updateFullscreenStatus)
    document.addEventListener('keydown', handleKeydown)
  }
})
</script>

<style scoped>
.fullscreen-toggle {
  cursor: pointer;
  padding: 8px;
  border: none;
  background: transparent;
  border-radius: 4px;
  transition: all 0.3s ease;

  &:hover {
    opacity: 0.8;
    transform: scale(1.05);
  }

  &:active {
    transform: scale(0.95);
  }
}

path {
  fill: v-bind('color');
}
</style>
