"use client";

import { useState } from "react";
import type { MenuItemVisualKind } from "@/lib/menu-item-image";
import {
  getMenuItemImageSrc,
  menuItemPlaceholderHeroIcon,
  menuItemPlaceholderIcon,
} from "@/lib/menu-item-image";
import { cn } from "@/lib/utils";

type MenuItemMediaProps = {
  imageUrl?: string | null;
  kind: MenuItemVisualKind;
  size?: "xs" | "sm" | "md" | "hero";
  className?: string;
  imgClassName?: string;
};

const iconSize: Record<NonNullable<MenuItemMediaProps["size"]>, string> = {
  xs: "h-3 w-3",
  sm: "h-4 w-4",
  md: "h-10 w-10",
  hero: "h-8 w-8",
};

const placeholderBg: Record<MenuItemVisualKind, string> = {
  drink: "bg-[#E8F4F8]",
  food: "bg-[#F5F0EB]",
};

const placeholderIconColor: Record<MenuItemVisualKind, string> = {
  drink: "text-[#0F6E56]/45",
  food: "text-[#8B6914]/40",
};

export function MenuItemMedia({
  imageUrl,
  kind,
  size = "sm",
  className,
  imgClassName,
}: MenuItemMediaProps) {
  const src = getMenuItemImageSrc(imageUrl);
  const [loadFailed, setLoadFailed] = useState(false);
  const PlaceholderIcon =
    size === "hero" ? menuItemPlaceholderHeroIcon(kind) : menuItemPlaceholderIcon(kind);

  const showPlaceholder = !src || loadFailed;

  if (showPlaceholder) {
    return (
      <div
        className={cn(
          "flex h-full w-full items-center justify-center",
          placeholderBg[kind],
          className
        )}
        aria-hidden
      >
        <PlaceholderIcon className={cn(iconSize[size], placeholderIconColor[kind])} />
      </div>
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      alt=""
      className={cn("h-full w-full object-cover", imgClassName, className)}
      loading="lazy"
      onError={() => setLoadFailed(true)}
    />
  );
}
