import { ref, onMounted, onUnmounted } from 'vue'
import WebApp from '@twa-dev/sdk'

export function useTelegramBackButton(onClick?: () => void) {
  const isVisible = ref(false)

  const show = () => {
    // 直接调用 WebApp 的方法显示返回按钮
    WebApp.BackButton.show()
    isVisible.value = true
  }

  const hide = () => {
    WebApp.BackButton.hide()
    isVisible.value = false
  }

  const handleBackClick = () => {
    if (onClick) {
      onClick()
    } else {
      // 默认行为
      history.back()
    }
  }

  onMounted(() => {
    // 确保 WebApp 已经加载
    WebApp.ready()
    // 显式调用显示方法
    show()
    // 绑定点击事件
    WebApp.BackButton.onClick(handleBackClick)
  })

  onUnmounted(() => {
    hide()
    WebApp.BackButton.offClick(handleBackClick)
  })

  return {
    isVisible,
    show,
    hide,
  }
}
