<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import WxShare from '~/components/shared/wxShare.vue'

const props = defineProps<{
  title?: string
  desc?: string
  imgUrl?: string
}>()

const route = useRoute()
const toast = useToast()
const { copy, copied } = useClipboard()

// SSR 安全：不要直接使用 window，改用 useRequestURL().origin
const requestURL = useRequestURL()
const origin = computed(() => requestURL.origin)

const mdcLink = computed(() => `${origin.value}${decodeURIComponent(route.path)}`)
const markdownLink = computed(() => `${origin.value}/raw${decodeURIComponent(route.path)}.md`)

const enableWxShare = ref(false)

const shareTitle = computed(() => props.title ?? (import.meta.client ? (document.title || 'Estel Docs') : ''))
const shareDesc = computed(() => props.desc ?? (import.meta.client ? (document.title || 'Estel Docs') : ''))
const shareImg = computed(() => props.imgUrl ?? '/images/default-blog.jpg')

const items = [
  {
    label: '复制链接',
    icon: 'lucide-link',
    onSelect() {
      copy(mdcLink.value)

      toast.add({
        title: '文档链接已复制到剪贴板',
        icon: 'lucide-check-circle',
        color: 'success'
      })
    }
  },
  {
    label: '分享到微信',
    icon: 'simple-icons:wechat',
    onSelect() {
      enableWxShare.value = true
      toast.add({
        title: '已为本页配置微信分享，请在微信内点击右上角分享',
        icon: 'lucide-check-circle',
        color: 'success'
      })
    }
  },

  {
    label: '查看 Markdown',
    icon: 'simple-icons:markdown',
    target: '_blank',
    to: markdownLink.value
  },
  {
    label: '在 ChatGPT 中打开',
    icon: 'simple-icons:openai',
    target: '_blank',
    to: `https://chatgpt.com/?hints=search&q=${encodeURIComponent(`Read ${markdownLink.value} so I can ask questions about it.`)}`
  },
  {
    label: '在 Claude 中打开',
    icon: 'simple-icons:anthropic',
    target: '_blank',
    to: `https://claude.ai/new?q=${encodeURIComponent(`Read ${markdownLink.value} so I can ask questions about it.`)}`
  }
]
</script>

<template>
  <UButtonGroup size="sm">
    <UButton
      label="复制链接"
      :icon="copied ? 'lucide-copy-check' : 'lucide-copy'"
      color="neutral"
      variant="outline"
      :ui="{
        leadingIcon: [copied ? 'text-primary' : 'text-neutral', 'size-3.5']
      }"
      @click="copy(mdcLink)"
    />

    <UDropdownMenu
      size="sm"
      :items="items"
      :content="{
        align: 'end',
        side: 'bottom',
        sideOffset: 8
      }"
      :ui="{
        content: 'w-48'
      }"
    >
      <UButton
        icon="lucide-chevron-down"
        color="neutral"
        variant="outline"
      />
    </UDropdownMenu>
  </UButtonGroup>

  <!-- 懒加载式挂载微信分享逻辑，避免在非微信环境造成无谓请求 -->
  <ClientOnly>
    <WxShare
      v-if="enableWxShare"
      :url="mdcLink"
      :title="shareTitle"
      :desc="shareDesc"
      :img-url="shareImg"
    />
  </ClientOnly>
</template>
