import Link from 'next/link';
import { getAllProducts } from '@/lib/mdx';

interface RelatedProductsProps {
  currentSlug: string;
  categories: string[];
  locale: string;
}

export default async function RelatedProducts({ currentSlug, categories, locale }: RelatedProductsProps) {
  const allProducts = await getAllProducts(locale);
  
  // Filter products: same category, not current product
  const related = allProducts
    .filter(p => 
      p.slug !== currentSlug && 
      p.frontmatter.categories.some(cat => categories.includes(cat))
    )
    .slice(0, 4); // Limit to 4

  if (related.length === 0) return null;

  return (
    <div className="mt-16 pt-8 border-t border-neutral-dark">
      <h2 className="text-2xl font-bold text-primary-dark mb-6">Related Products</h2>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        {related.map((product) => (
          <Link 
            key={product.slug} 
            href={`/${locale}/products/${product.slug}`}
            className="group block bg-white rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow border border-neutral-dark"
          >
            <div className="aspect-[4/3] relative bg-neutral-light">
              {product.frontmatter.images?.[0] ? (
                <img
                  src={product.frontmatter.images[0]}
                  alt={product.frontmatter.title}
                  className="w-full h-full object-contain p-4 group-hover:scale-105 transition-transform duration-300"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-text-secondary">
                  No Image
                </div>
              )}
            </div>
            <div className="p-4">
              <h3 className="font-semibold text-lg text-text-primary group-hover:text-primary transition-colors">
                {product.frontmatter.title}
              </h3>
              <div className="mt-2 flex flex-wrap gap-1">
                {product.frontmatter.categories.slice(0, 1).map((cat, idx) => (
                  <span key={idx} className="text-xs bg-neutral text-text-secondary px-2 py-1 rounded">
                    {cat}
                  </span>
                ))}
              </div>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
