<template>
  <Teleport v-if="modelValue" to="#wrapper">
    <div
      v-frame-hm="hideMenu ? extendedContentHeightMobile : contentHeightMobile"
      v-frame-wm="contentWidthMobile"
      v-frame-xm="0"
      v-frame-ym="44"
      class="popup"
    >
      <slot />
    </div>
    <div v-if="$slots.footer" class="footer" :style="{ bottom: `${(97 / frameHeightMobile) * 100}%` }">
      <slot name="footer" />
    </div>
  </Teleport>
</template>

<script lang="ts" setup>
import { onKeyDown } from '@vueuse/core'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
})

const emit = defineEmits<{
  'update:modelValue': [boolean]
  'close': []
}>()

const popupsVisible = usePopupsVisible()
const hideMenu = useHideMenu()
const stop: (() => void)[] = []

let id = 0

watch(
  () => props.modelValue,
  (isVisible) => {
    if (isVisible) {
      id = ++popupsVisible.value
      stop.push(
        onKeyDown('Escape', () => {
          if (id === popupsVisible.value) {
            emit('close')
            emit('update:modelValue', false)
          }
        }),
      )
    } else {
      if (id) {
        popupsVisible.value--
        id = 0
      }
      stop.forEach((fn) => fn())
      stop.splice(0, stop.length)
    }
  },
  { immediate: true },
)

onUnmounted(() => {
  if (id) {
    popupsVisible.value--
    stop.forEach((fn) => fn())
  }
})
</script>

<style scoped>
.popup {
  position: absolute;
  z-index: 20;
  display: flex;
  overflow-y: auto;
  background-color: #fff;
}

.footer {
  position: absolute;
  z-index: 20;
  right: 0;
  left: 0;
}
</style>
