"use client";

import Link from "next/link";
import { motion } from "framer-motion";
import { Play, Image as ImageIcon, FileImage } from "lucide-react";

export interface ProductView {
  _id: string;
  title: string;
  slug: string;
  description?: string;
  mediaFileId: string;
  mediaType: "image" | "gif" | "video";
}

export default function ProductCard({ product }: { product: ProductView }) {
  const url = `/api/files/${product.mediaFileId}`;

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: "-30px" }}
      transition={{ duration: 0.4 }}
      whileHover={{ y: -3 }}
      className="group glass rounded-xl overflow-hidden hover:border-brand-400/60 transition-all"
    >
      <Link href={`/portfolio/${product.slug}`} className="block">
        <div className="relative aspect-square bg-brand-900/40 overflow-hidden">
          {product.mediaType === "video" ? (
            <video
              src={url}
              autoPlay
              muted
              loop
              playsInline
              preload="metadata"
              className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
            />
          ) : (
            <img
              src={url}
              alt={product.title}
              loading="lazy"
              className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
            />
          )}

          <div className="absolute top-2 left-2">
            <MediaTypeBadge type={product.mediaType} />
          </div>

          <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition bg-gradient-to-t from-black/60 via-black/20 to-transparent" />
        </div>

        <div className="p-3">
          <h3 className="text-sm font-semibold text-white truncate">
            {product.title}
          </h3>
          {product.description && (
            <p className="mt-0.5 text-xs text-brand-300 line-clamp-1">
              {product.description}
            </p>
          )}
        </div>
      </Link>
    </motion.div>
  );
}

function MediaTypeBadge({
  type,
}: {
  type: "image" | "gif" | "video";
}) {
  const map = {
    image: { label: "PNG", icon: <ImageIcon className="w-3 h-3" /> },
    gif: { label: "GIF", icon: <FileImage className="w-3 h-3" /> },
    video: { label: "MP4", icon: <Play className="w-3 h-3" /> },
  } as const;
  const info = map[type];
  return (
    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-bold bg-black/60 text-white border border-white/10 backdrop-blur-sm">
      {info.icon}
      {info.label}
    </span>
  );
}
