---
import { Image, getImage } from "astro:assets";
import type { ImageMetadata } from "astro";

interface CTA {
  label: string;
  href: string;
  primary?: boolean;
}

interface Props {
  title?: string | string[];
  subtitle?: string[];
  description?: string;
  imageUrl?: string;
  textPosition?: "right" | "left" | "center";
  ctas?: CTA[];
}

const {
  title = [],
  subtitle = [],
  description = "",
  imageUrl = "",
  textPosition = "right",
  ctas = [],
} = Astro.props;

const imageBase = imageUrl.replace(/\.(webp|png|jpg|jpeg)$/i, "");

const images = import.meta.glob<{ default: ImageMetadata }>(
  "/src/assets/hero/**/*.webp",
  { eager: true },
);

function findImage(folder: string): ImageMetadata | null {
  const key = `/src/assets/hero/${folder}/${imageBase}-${folder}.webp`;
  return images[key]?.default ?? null;
}

const mobile = findImage("mobile");
const tablet = findImage("tablet");
const desktop = findImage("desktop");

const mobileSet = mobile
  ? await getImage({ src: mobile, widths: [480, 640], format: "webp" })
  : null;

const tabletSet = tablet
  ? await getImage({ src: tablet, widths: [768, 1024], format: "webp" })
  : null;

const desktopImg = desktop
  ? await getImage({ src: desktop, widths: [1280, 1440, 1920], format: "webp" })
  : null;
---

<section class={`f-hero f-hero--${textPosition}`}>
  <picture>
    {mobileSet && (
      <source
        srcset={mobileSet.srcSet.attribute}
        media="(max-width: 640px)"
        sizes="100vw"
      />
    )}

    {tabletSet && (
      <source
        srcset={tabletSet.srcSet.attribute}
        media="(max-width: 1024px)"
        sizes="100vw"
      />
    )}

    {desktop && (
      <Image
        src={desktop}
        alt={Array.isArray(title) ? title.join(" ") : String(title || imageBase)}
        class="f-hero-background"
        loading="eager"
        fetchpriority="high"
        decoding="async"
        format="webp"
        widths={[1280, 1440, 1920]}
        sizes="100vw"
      />
    )}
  </picture>

  <div class="f-hero-overlay"></div>

  <div class="f-hero-container">
    <div class="f-hero-content">
      {Array.isArray(title) ? (
        title.map((t) => <h1 class="f-hero-title">{t}</h1>)
      ) : (
        <h1 class="f-hero-title">{title}</h1>
      )}

      {subtitle.length > 0 && (
        <div class="f-hero-subtitles">
          {subtitle.map((s, i) => (
            <p class="f-hero-subtitle" style={`--delay:${i}`}>{s}</p>
          ))}
        </div>
      )}

      {description && <p class="f-hero-description">{description}</p>}

      {ctas.length > 0 && (
        <div class="f-hero-ctas">
          {ctas.map((cta) => (
            <a
              href={cta.href}
              class={cta.primary ? "btn btn-primary" : "btn btn-primary"}
            >
              {cta.label}
            </a>
          ))}
        </div>
      )}
    </div>
  </div>
</section>
