<template>
  <div
    :class="['wagtail-image', { loaded: loaded }]"
    :style="backgroundStyle"
  >
    <img
      :src="props.src"
      :srcset="props.srcset"
      :alt="props.alt"
      class="wagtail-image__image"
      :sizes="computedSizes"
      loading="eager"
      v-show="loaded"
      ref="imgElement"
      @load="handleLoad"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';

export interface Props {
  src: string;
  alt?: string;
  originalWidth: number;
  originalHeight: number;
  srcset?: string;
}

const props = withDefaults(defineProps<Props>(), {
  alt: '',
});

const imgElement = ref(null);
const width = ref(0);
const height = ref(0);
const loaded = ref(false);

const updateDimensions = () => {
  if (imgElement.value && imgElement.value.parentElement) {
    const { clientWidth, clientHeight } = imgElement.value.parentElement;
    width.value = clientWidth;
    height.value = clientHeight;
  }
};

const handleLoad = () => {
  loaded.value = true; // Set loaded to true when the image loads
};

const computedSizes = computed(() => {
  // the default set of image sizes is [160px, 320px, 800px, 1600px]
  let size = '100vw';

  if (width.value <= 300) {
    size = '160px';
  }
  if (300 < width.value && width.value <= 600) {
    size = '320px';
  }
  if (600 < width.value && width.value <= 1200) {
    size = '800px';
  }
  return size;
});

const backgroundStyle = computed(() => {
  const styles = {
    width: '100%',
    height: '100%',
  };
  if (width.value) {
    const scalingFactor = width.value / props.originalWidth;
    const scaledHeight = Math.round(props.originalHeight * scalingFactor);
    const scaledWidth = Math.round(props.originalWidth * scalingFactor);

    if (props.originalWidth) {
      styles.width = `${scaledWidth}px`;
    }
    if (props.originalHeight) {
      styles.height = `${scaledHeight}px`;
    }
  }
  return styles;
});

onMounted(() => {
  updateDimensions();
  window.addEventListener('resize', updateDimensions);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateDimensions);
});
</script>

<style scoped lang="scss">
@import 'styles/helpers';

.wagtail-image {
  overflow: hidden;
  width: 100%;
  height: 100%;
  background-color: $color-silver-light;

  &__image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
  }
}

.wagtail-image.loaded {
  background-color: white;
}
</style>
