<script setup>
import { ref, onMounted } from 'vue'

//const router = useRouter()
const config = useRuntimeConfig()
const attachmentPreview = useAttachmentPreview()
const attachmentParam = useAttachmentParam()

const props = defineProps({
  params: Object
})

const strapiProduct = ref({})
const productGalleries = ref([])
onMounted(async () => {
  if(props.params.data.strapiProductId) {
    const res = await $fetch(`/api/materials/products/${props.params.data.strapiProductId}/galleries`)
    if(res?.data) {
      strapiProduct.value = res.data
      productGalleries.value = res.data?.image ?? []
    }
  }
})
const defaultGallery = computed(() => {
  let newGallery = productGalleries.value?.[0] ?? {}
  if(strapiProduct.value?.Main_Image && strapiProduct.value?.Main_Image != 0) {
    newGallery = productGalleries.value.filter(i => i.id == strapiProduct.value.Main_Image)?.[0] ?? {}
  }
  return newGallery
})
const viewAttachmentViewer = () => {
  attachmentParam.value = productGalleries.value?.[0] || {}
  if(attachmentParam.value?.name) {
    attachmentPreview.value = true
  }
}
</script>

<template>
  <div v-if="defaultGallery?.id" @click="viewAttachmentViewer">
    <div class="productThumbnail">
      <img :src="config.public.strapi+'/files-api/'+(defaultGallery?.formats?.thumbnail?.hash ?? '') + (defaultGallery?.formats?.thumbnail?.ext ?? '')" :alt="defaultGallery?.name ?? ''" />
    </div>
  </div>
</template>

<style scoped>
.productThumbnail {
  width: 26px;
  height: 26px;
  overflow: hidden;
  position: relative;
  border-radius: 20%;
}

.productThumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>