<template>
  <div class="oc-image">
    <div v-if="isLoaded === false" class="loader">
      <i class="fa fa-spinner fa-spin"></i>
    </div>

    <a v-show="isLoaded" href="#" data-toggle="image" class="img-thumbnail" :id="`thumb-image-${id}`">
      <img
        :src="thumb"
           data-placeholder="/image/cache/no_image-100x100.png"
           alt="Image"
           @load="isLoaded = true"
          style="width: 100%; height: 100%;"
      >
    </a>
    <input ref="inputRef" type="hidden" value="" :id="`input-image-${id}`">
  </div>
</template>

<script setup>
import {computed, onMounted, ref, useId} from "vue";
import {getThumb} from "@/utils/helpers.js";

const id = useId();
const model = defineModel();
const emit = defineEmits(['update:modelValue']);
const inputRef = ref(null);
const isLoaded = ref(false);

const thumb = computed(() => getThumb(model.value));

onMounted(() => {
  const input = inputRef.value;
  const observer = new MutationObserver(() => {
    const val = input.value;
    console.log("Updated value: ", val);
    if (val !== model.value) {
      emit('update:modelValue', val);
    }
  });

  observer.observe(input, {attributes: true, attributeFilter: ['value']});
});
</script>

<style scoped>
.loader {
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
