<script setup>
const props = defineProps({
  modelValue: Boolean,
  title: String,
  source: String,
  type: String,
  width: Number,
  height: Number
})

const emit = defineEmits(['update:modelValue'])

const showAttachmentModal = ref(props.modelValue || false)
const mediaControlRef = ref(null)
const closeAttachmentModal = () => {
  if(mediaControlRef.value) {
    mediaControlRef.value.pause()
  }
  showAttachmentModal.value = false
  emit('update:modelValue', false)
}
watch(() => props.modelValue, () => {
  showAttachmentModal.value = props.modelValue

  if(document?.body && showAttachmentModal.value) {
    document.body.addEventListener('keydown', function(e) {
      if (e.key == 'Escape') {
        closeAttachmentModal()
      }
    })
  }
})
</script>

<template>
  <div class="modal" :class="{'active': showAttachmentModal}" :style="{display: showAttachmentModal ? 'block' : 'none'}">
    <div class="modalDialog modalCenter modalFullscreen">
      <div class="modalContent overflow-auto" style="background: transparent;">
        <div class="modalHeader" style="background: rgba(255, 255, 255, 0.8);">
          <h3 class="modalTitle">{{ title ?? '' }}</h3>
          <div class="cursor-pointer" @click="closeAttachmentModal">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody d-grid placeItems-center m-0px p-0px" style="height: calc(100vh - 48px);" @click.self="closeAttachmentModal">
          <template v-if="type?.startsWith('video/') && source">
            <video ref="mediaControlRef" controls style="height: calc(100vh - 144px); width: auto; overflow: hidden;">
              <source :src="source" :type="type" />
            </video>
          </template>
          <template v-else-if="type?.startsWith('audio/') && source">
            <audio ref="mediaControlRef" controls style="width: auto; overflow: hidden;">
              <source :src="source" :type="type" />
            </audio>
          </template>
          <template v-else-if="type?.startsWith('image/') && source && (width <= 1366 || height <= 768)">
            <embed :type="type" :src="source" :width="width ?? 'auto'" :height="height ?? 'auto'" style="overflow: hidden;" />
          </template>
          <template v-else-if="type?.startsWith('image/') && source && height > 768">
            <embed :type="type" :src="source" height="100%" style="width: auto; overflow: hidden;" />
          </template>
          <template v-else-if="type?.includes('/') && source">
            <embed :type="type" :src="source" width="100%" height="100%" />
          </template>
        </div>
        <!--<div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="closeAttachmentModal">Close</button>
          </div>
        </div>-->
      </div>
    </div>
  </div>
</template>