<template>
  <DialogRoot
    v-if="image"
    v-slot="{ close }"
    v-model:open="open"
    :modal="false"
  >
    <DialogTrigger as-child>
      <Motion :layout-id="layoutId" as-child :transition="{ type: 'spring', bounce: 0.15, duration: 0.5, ease: 'easeInOut' }">
        <BaseUploraImage
          :image="image"
          :class="ui.base({ class: [props.ui?.base, props.class] })"
          :alt="alt"
          :color="color"
          :aspect="aspect"
          :width="width"
          :height="height"
        />
      </Motion>
    </DialogTrigger>

    <DialogPortal>
      <AnimatePresence>
        <Motion
          v-if="open"
          :initial="{ opacity: 0 }"
          :animate="{ opacity: 1 }"
          :exit="{ opacity: 0 }"
          :class="ui.overlay({ class: [props.ui?.overlay] })"
        />

        <div v-if="open" :class="ui.content({ class: [props.ui?.content] })" @click="close">
          <Motion as-child :layout-id="layoutId" :transition="{ type: 'spring', bounce: 0.15, duration: 0.5, ease: 'easeInOut' }">
            <img
              :src="image.original"
              :alt="alt"
              :class="ui.zoomedImage({ class: props.ui?.zoomedImage })"
            >
          </Motion>
        </div>
      </AnimatePresence>
    </DialogPortal>
  </DialogRoot>
</template>

<script>
import theme from "#build/cms/prose/uplora-image";
import { useAppConfig, useCmsConfig } from "#imports";
import { useEventListener } from "@vueuse/core";
import { AnimatePresence, Motion } from "motion-v";
import { DialogPortal, DialogRoot, DialogTrigger } from "reka-ui";
import { computed, onMounted, ref, useId } from "vue";
import { tv } from "../../tv";
import { buildUploraImage } from "../../utils";
import BaseUploraImage from "../UploraImage.vue";
</script>

<script setup>
const props = defineProps({
  image: { type: String, required: false },
  class: { type: null, required: false },
  ui: { type: null, required: false },
  alt: { type: String, required: false },
  color: { type: String, required: false },
  formats: { type: Array, required: false },
  sizes: { type: Array, required: false },
  aspect: { type: String, required: false },
  width: { type: [Number, String], required: false },
  height: { type: [Number, String], required: false }
});
const appConfig = useAppConfig();
const cmsConfig = useCmsConfig();
const layoutId = computed(() => `${props.image}::${useId()}`);
const open = ref(false);
const image = computed(() => props.image ? buildUploraImage({
  id: props.image,
  formats: props.formats ?? cmsConfig?.components?.uploraImage?.formats,
  sizes: props.sizes ?? cmsConfig?.components?.prose?.uploraImage?.sizes
}) : void 0);
const ui = computed(() => tv({ extend: tv(theme), ...appConfig.cms?.prose?.uploraImage || {} })({
  open: open.value
}));
onMounted(() => {
  useEventListener(window, "scroll", () => {
    open.value = false;
  });
});
</script>
