"use client";

import Image from "next/image";
import useObserver from "@/hooks/useObserver";

type ThumbnailProps = {
  imageUrl?: string;
  alt?: string;
  alwaysVisible?: boolean;
  fixedAspectRatio?: boolean;
  width: number;
  height: number;
};

const Thumbnail = (props: ThumbnailProps) => {
  const {
    alwaysVisible = false,
    fixedAspectRatio = true,
    alt = "",
    imageUrl = null,
    width,
    height,
    ...rest
  } = props;
  const [ref, isVisible] = useObserver<HTMLDivElement>();

  const classes = ['thumbnail'];
  if (isVisible || alwaysVisible) classes.push('animating');

  return (
    <div ref={ref} className={classes.join(' ')}>
      {imageUrl && (
        <Image
          className={[
            "thumbnail__img",
            isVisible || alwaysVisible ? "animating__img" : "",
          ].join(" ")}
          style={
            fixedAspectRatio && width && height
              ? { aspectRatio: `${width} / ${height}` }
              : undefined
          }
          src={imageUrl}
          alt={alt}
          width={width}
          height={height}
          {...rest}
        />
      )}
    </div>
  );
};

export default Thumbnail;
