<template>
  <ClientOnly>
    <Teleport to="#wrapper">
      <Transition name="sheet">
        <div v-if="modelValue" @click="onClick" class="sheet">
          <div class="sheet-container">
            <slot />
          </div>
        </div>
      </Transition>
    </Teleport>
  </ClientOnly>
</template>

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

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

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

const stop: (() => void)[] = []

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

onUnmounted(() => {
  stop.forEach((fn) => fn())
})

function onClick(event: MouseEvent) {
  if (event.target === event.currentTarget) {
    event.stopPropagation()
    emit('close')
    emit('update:modelValue', false)
  }
}
</script>

<style scoped>
.sheet {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 30;
  display: flex;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.64);
}

.sheet-container {
  width: 100%;
  max-height: 80%;
  margin-top: auto;
  background-color: #fff;
  border-top-right-radius: 1rem;
  border-top-left-radius: 1rem;
  overflow-y: auto;
}

.sheet-enter-active,
.sheet-leave-active {
  transition: opacity 0.3s ease-in-out;
}

.sheet-enter-from,
.sheet-leave-to {
  opacity: 0;
}

.sheet-enter-active .sheet-container,
.sheet-leave-active .sheet-container {
  transition: transform 0.3s ease-in-out;
}

.sheet-enter-from .sheet-container,
.sheet-leave-to .sheet-container {
  transform: translateY(100%);
}
</style>
