import type { SetupContext, MaybeRef } from 'vue'
type Events = {
  handleBackTop(): void
}
function ScrollTopComp(_: any, { emit }: SetupContext<Events>) {
  return (
    <button
      class="back-top-btn group cursor-pointer flex items-center gap-3 px-4 py-2.5 bg-gradient-to-r from-blue-50 to-indigo-50 hover:from-blue-100 hover:to-indigo-100 border border-blue-200/50 rounded-full transition-all duration-300 hover:shadow-lg hover:-translate-y-1 active:scale-95 shadow-sm"
      title="回到顶部"
      onClick={() => emit('handleBackTop')}
    >
      <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full flex items-center justify-center group-hover:rotate-15 transition-transform duration-300 shadow-sm">
        <SvgIcon name="icon_top" size="16" className="text-white" />
      </div>
      <span class=" hidden lg:block text-xs font-medium text-gray-700 group-hover:text-blue-600 transition-colors">
        回到顶部
      </span>
    </button>
  )
}

// 顺便兼容下多个的
export const useScrollTop = (
  el: MaybeRef<HTMLElement | null | Window | HTMLElement[] | [Window]>,
  options: { compatFixedHeader?: boolean } = {},
) => {
  const { compatFixedHeader = true } = options

  const handleBackTop = (currentIndex: number = 0): Promise<void> => {
    return new Promise((resolve) => {
      const initDoms = unref(el)
      if (!initDoms) {
        resolve()
        return
      }

      let doms = []

      if (!Array.isArray(initDoms)) {
        doms = [initDoms]
      } else {
        doms = initDoms
      }

      const finish = () => {
        console.log('scrollend')
        resolve()
      }

      // 手动添加一次scrollend事件
      window.addEventListener('scrollend', finish, { once: true })

      // 有时候在滚轮就在原位置 不会触发 scrollend事件 所以手动触发一次
      setTimeout(() => {
        window.removeEventListener('scrollend', finish)
        resolve()
      }, 1000)
      // 下面会触发scrollend事件一次
      const dom = doms[currentIndex] as HTMLElement | Window
      if (dom instanceof Window) {
        window.scrollTo({
          top: 0,
          behavior: 'smooth',
        })
        return
      }

      if (compatFixedHeader) {
        const top = dom?.getBoundingClientRect?.().top + window.scrollY - 52
        window.scrollTo({
          top, // 可以设置滚动的距离
          behavior: 'smooth',
        })
      } else {
        dom?.scrollIntoView?.({
          // 只能滚动到dom的顶部 不能设置滚动的距离
          behavior: 'smooth',
          block: 'start',
        })
      }
    })
  }

  return {
    ScrollTopComp: () => <ScrollTopComp onHandleBackTop={handleBackTop}></ScrollTopComp>,
    handleBackTop,
  }
}
