"use client";

import { useState } from "react";
import Image from "next/image";
import { ImageOff } from "lucide-react";
import { cn } from "@/lib/utils";

/**
 * Real product media only — never a placeholder stock photo. Shows a
 * skeleton while the remote image loads, and an explicit "no image" icon
 * (not a broken-image glyph) when there's no URL or the URL fails to load,
 * so a missing/expired TikTok CDN link never looks like an app bug.
 */
export function ProductImage({
  src,
  alt,
  className,
  sizes = "(min-width: 1280px) 15vw, (min-width: 640px) 25vw, 40vw",
  fit = "cover",
}: {
  src: string | null;
  alt: string;
  className?: string;
  sizes?: string;
  fit?: "cover" | "contain";
}) {
  const [status, setStatus] = useState<"loading" | "loaded" | "error">(src ? "loading" : "error");

  if (!src || status === "error") {
    return (
      <div
        className={cn(
          "flex aspect-square shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground",
          className,
        )}
        role="img"
        aria-label={alt}
      >
        <ImageOff className="size-1/3 opacity-40" aria-hidden="true" />
      </div>
    );
  }

  return (
    <div
      className={cn("relative aspect-square shrink-0 overflow-hidden rounded-lg bg-secondary", className)}
    >
      {status === "loading" && <div className="absolute inset-0 animate-pulse bg-muted" aria-hidden="true" />}
      <Image
        src={src}
        alt={alt}
        fill
        sizes={sizes}
        loading="lazy"
        className={cn(
          fit === "contain" ? "object-contain" : "object-cover",
          "transition-opacity duration-200",
          status === "loaded" ? "opacity-100" : "opacity-0",
        )}
        onLoad={() => setStatus("loaded")}
        onError={() => setStatus("error")}
      />
    </div>
  );
}
