"use client";

import Image from "next/image";

import { isNextImageOptimizedSrc } from "@/lib/media/next-image-src";
import { cn } from "@/lib/utils";

type CmsImageProps = {
  src: string;
  alt: string;
  className?: string;
  fill?: boolean;
  width?: number;
  height?: number;
  sizes?: string;
  priority?: boolean;
  focalX?: number;
  focalY?: number;
};

export function CmsImage({
  src,
  alt,
  className,
  fill,
  width,
  height,
  sizes = "(max-width: 768px) 100vw, 50vw",
  priority,
  focalX = 0.5,
  focalY = 0.5,
}: CmsImageProps) {
  const objectPosition = `${focalX * 100}% ${focalY * 100}%`;
  const style = { objectPosition };

  if (isNextImageOptimizedSrc(src)) {
    return (
      <Image
        src={src}
        alt={alt}
        fill={fill}
        width={fill ? undefined : width}
        height={fill ? undefined : height}
        className={cn(className)}
        sizes={sizes}
        priority={priority}
        loading={priority ? undefined : "lazy"}
        style={style}
      />
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      alt={alt}
      width={width}
      height={height}
      className={cn(fill && "absolute inset-0 size-full object-cover", className)}
      loading={priority ? "eager" : "lazy"}
      decoding="async"
      style={style}
    />
  );
}
