---
import type { ImageMetadata } from "astro";

interface Props {
  images: Record<string, () => Promise<{ default: ImageMetadata }>>;
  transitionStyle?: string;
}

const { images, transitionStyle = "ease-in-out" } = Astro.props as Props;

const imagesArray = await Promise.all(
  Object.values(images).map(async (image) => image())
);
---

<div class="absolute -z-50 h-full w-full bg-black"></div>
<img
  src={imagesArray[0].default.src}
  class:list={[
    "object-no-repeat absolute -z-50 h-full w-full object-cover object-center transition duration-2000",
    transitionStyle
  ]}
  id="hero-image-1"
/>
<img
  src={imagesArray[1].default.src}
  class:list={[
    "object-no-repeat absolute -z-50 h-full w-full object-cover object-center transition duration-2000",
    transitionStyle
  ]}
  id="hero-image-2"
/>

<script define:vars={{ imagesArray }}>
  let currentIndex = 2; // Start at 2 since first two are already shown
  let visibleIndex = 0; // 0 or 1 — tracks which image is currently visible

  const changeImage = () => {
    const currentImage = document.getElementById(
      `hero-image-${visibleIndex + 1}`
    );
    const nextImage = document.getElementById(
      `hero-image-${1 - visibleIndex + 1}`
    );

    if (currentImage && nextImage) {
      // Prepare next image
      nextImage.src =
        imagesArray[currentIndex % imagesArray.length].default.src;
      nextImage.classList.remove("opacity-0"); // fade it in
      currentImage.classList.add("opacity-0"); // fade it out

      // Once transition is done, update the image that faded out
      setTimeout(() => {
        currentIndex = (currentIndex + 1) % imagesArray.length;
        visibleIndex = 1 - visibleIndex; // swap visible image index
      }, 2000); // match this to the fade duration
    }
  };

  setInterval(changeImage, 5000);
</script>
