---
interface Props {
  id?: string;
  src: ImageMetadata | string;
  class?: string;
  alt?: string;
  position?: string;
  basePath?: string;
}

import path from "path";
import { url, urlIsLocal, urlIsPublic } from "../../utils/url-utils";

const { id, src: img, alt, position = "center", basePath = "/" } = Astro.props;
const className = Astro.props.class;

const src = typeof img === "string" ? img : img.src;

const isLocal = urlIsLocal(src);
const isPublic = urlIsPublic(src);

// TODO temporary workaround for images dynamic import
// https://github.com/withastro/astro/issues/3373
let optimizedImg: ImageMetadata;
if (isLocal && typeof img === "string") {
  const files = import.meta.glob<ImageMetadata>("../../**", {
    import: "default",
  });
  const normalizedPath = path
    .normalize(path.join("../../", basePath, src))
    .replace(/\\/g, "/");
  optimizedImg = await files[normalizedPath]();
}

const imageClass = "w-full h-full object-cover";
const imageStyle = `object-position: ${position}`;
---
<div id="image-wrapper" class:list={[className, 'overflow-hidden relative']}>
    <div class="transition absolute inset-0 dark:bg-black/10 bg-opacity-50 pointer-events-none"></div>
    {isLocal && <img src={optimizedImg!.src} alt={alt || ""} class={imageClass} style={imageStyle}/>}
    {!isLocal && <img src={isPublic ? url(src) : src} alt={alt || ""} class={imageClass} style={imageStyle}/>}
</div>

