<template>
  <Dialog :open="isOpen" @update:open="setOpen">
    <DialogContent
      @pointer-down-outside="(event) => event.preventDefault()"
      @focus-outside="(event) => event.preventDefault()"
      @focusin="handleFocusIn"
      class="login-dialog max-w-[300px] overflow-visible rounded-4xl bg-[#DDDDDD] p-[14px] md:max-w-[390px]"
      :style="dialogViewportStyle"
      :showCloseButton="false"
    >
      <DialogHeader class="py-2 pl-2">
        <DialogTitle class="text-left text-base md:text-2xl">代理登录/注册</DialogTitle>
        <DialogDescription class="text-left text-base text-[#999999]">
          请输入您的邮箱并通过验证码登录，如您第一次使用将自动为您创建Hi快高能合伙人帐号。
        </DialogDescription>
      </DialogHeader>
      <LoginForm @close="isOpen = false" />
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import LoginForm from './LoginForm.vue'

const isOpen = ref(false)
const visualViewportTop = ref(window.visualViewport?.offsetTop ?? 0)
const visualViewportHeight = ref(window.visualViewport?.height ?? window.innerHeight)
let focusTimer: ReturnType<typeof setTimeout> | undefined

const syncVisualViewport = () => {
  const viewport = window.visualViewport
  visualViewportTop.value = viewport?.offsetTop ?? 0
  visualViewportHeight.value = viewport?.height ?? window.innerHeight
}

const dialogViewportStyle = computed(() => ({
  top: `${visualViewportTop.value + visualViewportHeight.value / 2}px`,
  maxHeight: `${Math.max(visualViewportHeight.value - 24, 0)}px`,
}))

const setOpen = (value: boolean) => {
  isOpen.value = value
  if (value) nextTick(syncVisualViewport)
}

const show = () => {
  setOpen(true)
}

const hide = () => {
  isOpen.value = false
}

const handleFocusIn = () => {
  if (focusTimer) clearTimeout(focusTimer)
  focusTimer = setTimeout(() => {
    syncVisualViewport()
  }, 300)
}

onMounted(() => {
  syncVisualViewport()
  window.visualViewport?.addEventListener('resize', syncVisualViewport)
  window.visualViewport?.addEventListener('scroll', syncVisualViewport)
})

onBeforeUnmount(() => {
  if (focusTimer) clearTimeout(focusTimer)
  window.visualViewport?.removeEventListener('resize', syncVisualViewport)
  window.visualViewport?.removeEventListener('scroll', syncVisualViewport)
})

defineExpose({
  show,
  hide,
})
</script>

<style scoped>
.login-dialog {
  will-change: top, max-height;
  scrollbar-width: none;
}

.login-dialog::-webkit-scrollbar {
  display: none;
}
</style>
