<template>
  <div class="cc__imageviewer__full-screen-viewer">
    <div class="cc__imageviewer__zoom-container" ref="zoomContainer">
      <img class="cc__imageviewer__loading" :src="placeholderImage" v-if="!isImageLoaded" />
      <img :src="proxyImage(url)" @load="imageLoaded" />
    </div>
  </div>
  <div class="cc__imageviewer-option cc__imageviewer-option--close" @click="dispatchCloseClickEvent">
    <CloseIcon class="w-6 h-6 text-white" />
  </div>
  <div class="cc__imageviewer-option cc__imageviewer-option--download" @click="openImage">
    <DownloadIcon class="w-6 h-6 text-white" />
  </div>
</template>

<script setup lang="ts">
import { CloseIcon, DownloadIcon } from '@bcc-code/icons-vue';
import { CometChatIcon } from '@cometchat/chat-uikit-vue';
import createPanZoom from 'panzoom';
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { proxyImage } from '../chat/data';

if (!window.customElements.get('cometchat-icon')) {
  window.customElements.define('cometchat-icon', CometChatIcon);
}

const props = defineProps({
  url: {
    type: String,
    required: true
  },
  placeholderImage: {
    type: String
  }
});

const emit = defineEmits<{
  (e: 'cc-close-clicked'): void;
}>();

const dispatchCloseClickEvent = (event: Event) => {
  event?.stopPropagation();
  emit('cc-close-clicked');
};

const openImage = () => {
  window.open(props.url, '_blank');
};

const isImageLoaded = ref(false);
const imageLoaded = () => {
  isImageLoaded.value = true;
}

const zoomContainer = ref();
let panZoomInstance: any;
onMounted(() => {
  panZoomInstance = createPanZoom(zoomContainer.value, {
    bounds: true,
    boundsPadding: 1,
    maxZoom: 10,
    minZoom: 1,
  });
});

onBeforeUnmount(() => {
  panZoomInstance.dispose();
})
</script>

<style scoped>
.cc__imageviewer__full-screen-viewer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 10000;
}

.cc__imageviewer__zoom-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.cc__imageviewer__loading {
  position: absolute;
  z-index: -1;
}

img {
  max-width: 100%;
  max-height: 100%;
}

.cc__imageviewer-option {
  position: fixed;
  cursor: pointer;
  z-index: 10001;
  padding: 10px;
}

.cc__imageviewer-option--close {
  top: 0;
  right: 0;
  margin-top: env(safe-area-inset-top);
}

.cc__imageviewer-option--download {
  top: 0;
  left: 0;
  margin-top: env(safe-area-inset-top);
}
</style>
