---
import type { ImageMetadata } from "astro";
import { Image } from "astro:assets";
import path from "node:path";

import { url } from "@utils/url";


interface Props {
    id?: string;
    src: string;
    class?: string;
    alt?: string;
    position?: string;
    basePath?: string;
    style?: string;
    loading?: "lazy" | "eager";
    decoding?: "async" | "auto" | "sync";
}

const { id, src, alt, position = "center", basePath = "/", style, loading = "lazy", decoding = "async" } = Astro.props;
const className = Astro.props.class;

const isLocal = !(
    src.startsWith("/") ||
    src.startsWith("http") ||
    src.startsWith("https") ||
    src.startsWith("data:")
);
const isPublic = src.startsWith("/");

// TODO temporary workaround for images dynamic import
// https://github.com/withastro/astro/issues/3373
// biome-ignore lint/suspicious/noImplicitAnyLet: <check later>
let img;
if (isLocal) {
    const files = import.meta.glob<ImageMetadata>("../../**", {
        import: "default",
    });
    let normalizedPath = path
        .normalize(path.join("../../", basePath, src))
        .replace(/\\/g, "/");
    const file = files[normalizedPath];
    if (!file) {
        console.error(
            `\n[ERROR] Image file not found: ${normalizedPath.replace("../../", "src/")}`,
        );
    } else {
        img = await file();
    }
}

const imageClass = "w-full h-full object-cover";
const imageStyle = `object-position: ${position}`;
---

<div id={id} class:list={[className, 'overflow-hidden relative']} style={style}>
    <div class="transition absolute inset-0 bg-black/3 dark:bg-black/9 pointer-events-none"></div>
    {isLocal && img && <Image src={img} alt={alt || ""} class={imageClass} style={imageStyle} loading={loading} decoding={decoding}/>}
    {!isLocal && <img src={isPublic ? url(src) : src} alt={alt || ""} class={imageClass} style={imageStyle} loading={loading} decoding={decoding}/>}
</div>