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

const props = defineProps({
  strapiProductId: { type: [String, Number], default: null }
})

const config = useRuntimeConfig()
const rootEl = ref(null)
const imgUrl = ref('')
const loaded = ref(false)
const failed = ref(false)
let observer = null
let fetched = false

const fetchGallery = async () => {
  if (fetched) return
  fetched = true
  if (!props.strapiProductId) { failed.value = true; return }
  try {
    const res = await $fetch(`/api/materials/products/${props.strapiProductId}/galleries`)
    const galleries = res?.data?.image ?? []
    let g = galleries[0]
    const mainId = res?.data?.Main_Image
    if (mainId && mainId != 0) {
      g = galleries.find(i => i.id == mainId) ?? g
    }
    const hash = g?.formats?.thumbnail?.hash ?? g?.formats?.small?.hash ?? null
    const ext  = g?.formats?.thumbnail?.ext  ?? g?.formats?.small?.ext  ?? ''
    if (hash) {
      imgUrl.value = `${config.public.strapi}/files-api/${hash}${ext}`
    } else {
      failed.value = true
    }
  } catch (e) {
    failed.value = true
  }
}

onMounted(() => {
  if (typeof IntersectionObserver === 'undefined') {
    // SSR/old browsers — schedule when idle so it never blocks first paint.
    const cb = () => fetchGallery()
    if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
      window.requestIdleCallback(cb, { timeout: 2000 })
    } else {
      setTimeout(cb, 300)
    }
    return
  }
  observer = new IntersectionObserver((entries) => {
    for (const e of entries) {
      if (e.isIntersecting) {
        fetchGallery()
        observer.disconnect()
        observer = null
        break
      }
    }
  }, { rootMargin: '120px' })
  if (rootEl.value) observer.observe(rootEl.value)
})

onBeforeUnmount(() => {
  if (observer) { observer.disconnect(); observer = null }
})
</script>

<template>
  <div ref="rootEl" class="lazy-thumb">
    <img
      v-if="imgUrl && !failed"
      :src="imgUrl"
      loading="lazy"
      decoding="async"
      alt=""
      @load="loaded = true"
      @error="failed = true"
    />
    <i v-else class="ti ti-photo lazy-thumb__placeholder"></i>
  </div>
</template>

<style scoped>
.lazy-thumb {
  width: 40px;
  height: 40px;
  flex: 0 0 40px;
  border-radius: 6px;
  background: var(--theme-bg-secondary, #f1f5f9);
  border: 1px solid var(--theme-border, #e6e8ec);
  overflow: hidden;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.lazy-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
.lazy-thumb__placeholder {
  font-size: 1.1rem;
  color: var(--theme-text-secondary, #94a3b8);
  opacity: 0.6;
}
[data-mode="dark"] .lazy-thumb {
  background: rgba(255, 255, 255, 0.04);
  border-color: rgba(255, 255, 255, 0.08);
}
</style>
