import Image from "next/image";

import { getStockLevel, STOCK_LABELS } from "@/lib/format";
import type { Product } from "@/types/product";

/**
 * Product artwork with a graceful fallback.
 *
 * Product images are SVGs generated by `npm run build:images`. `next/image`
 * serves SVG sources unoptimized, and the `fill` + `sizes` combination lets the
 * browser pick a source for the rendered card width.
 */
export function ProductImage({
  product,
  sizes = "(min-width: 1280px) 25vw, (min-width: 768px) 33vw, 100vw",
  className = "",
  loading = "lazy",
}: {
  product: Pick<Product, "image" | "name" | "subcategory" | "stock">;
  sizes?: string;
  className?: string;
  loading?: "lazy" | "eager";
}) {
  return (
    <div
      className={`relative aspect-square w-full overflow-hidden bg-slate-100 ${className}`}
    >
      <Image
        src={product.image}
        alt={`${product.name} — ${product.subcategory}`}
        fill
        sizes={sizes}
        loading={loading}
        className="object-cover transition-transform duration-500 ease-out group-hover:scale-105"
      />
      <StockBadge stock={product.stock} />
    </div>
  );
}

function StockBadge({ stock }: { stock: number }) {
  const level = getStockLevel(stock);
  if (level === "in-stock") return null;

  return (
    <span
      className={`absolute top-3 left-3 rounded-full px-2.5 py-1 text-xs font-semibold shadow-sm backdrop-blur ${
        level === "out-of-stock"
          ? "bg-slate-900/85 text-white"
          : "bg-amber-500/90 text-amber-950"
      }`}
    >
      {STOCK_LABELS[level]}
    </span>
  );
}
