<script setup lang="ts">
import ModalTrigger from "./ModalTrigger.vue";

import { ref, provide, watch } from "vue";
import { useKeyboardShortcut } from "./events";
import { IProps } from "./props";

const props = withDefaults(defineProps<Pick<IProps, "modelValue" | "close">>(), {
  close: true,
});

const emits = defineEmits(["update:modelValue"]);

const isOpen = ref(props.modelValue);

function closeModal() {
  if (!props.close) return;
  isOpen.value = false;
  emits("update:modelValue", false);
}
useKeyboardShortcut("Escape", closeModal);

function openModal() {
  isOpen.value = true;
  emits("update:modelValue", true);
}
useKeyboardShortcut("m", openModal);

watch(
  () => props.modelValue,
  (newVal) => {
    isOpen.value = newVal;
  }
);

provide("close", closeModal);
provide("canClose", ref(props.close));
provide("open", openModal);
</script>

<template>
  <ModalTrigger>
    <slot name="open" />
  </ModalTrigger>

  <Transition>
    <div v-if="modelValue" class="modal-overlay" @click.self="closeModal">
      <slot />
    </div>
  </Transition>
</template>

<style scoped lang="scss">
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999999;

  width: var(--w-full);
  height: var(--w-full);

  display: flex;
  justify-content: center;
  align-items: center;

  animation: opacity 0.15s linear;

  background: rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(1.5px);

  @include size(md) {
    align-items: end;
    height: 100dvh;
  }
}
</style>
