import Link from 'next/link';
import Image from 'next/image';
import type { Product } from '@/types/api';
import { fetchProducts } from '@/lib/api';
import { formatRichText } from '@/lib/format-rich-text';

function formatPrice(cents: number): string {
  return `€${(cents / 100).toFixed(2)}`;
}

export default async function FeaturedProducts() {
  let allProducts: Awaited<ReturnType<typeof fetchProducts>> = [];
  try {
    allProducts = await fetchProducts();
  } catch (e) {
    console.error('[FeaturedProducts] fetch error:', e);
  }
  const products = allProducts.slice(0, 4);

  if (products.length === 0) {
    return (
      <section className="py-16 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <p className="text-center text-gray-500">Cargando productos...</p>
        </div>
      </section>
    );
  }

  return (
    <section className="py-16 bg-white">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-8">Productos destacados</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {products.map((product) => (
            <Link key={product.id} href={`/products/${product.slug}`} className="group block">
              <div className="bg-gray-50 rounded-xl overflow-hidden border border-gray-100 hover:border-[#70ad47] transition-colors">
                <div className="relative aspect-square w-full bg-white flex items-center justify-center overflow-hidden">
                  {product.images?.[0] ? (
                    <Image src={product.images[0].url} alt={product.name} fill className="object-contain" sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw" />
                  ) : (
                    <span className="text-5xl">🌿</span>
                  )}
                </div>
                <div className="p-4">
                  {product.brandId && <p className="text-xs text-[#70ad47] font-medium uppercase tracking-wide mb-1">Marca</p>}
                  <h3 className="font-semibold text-gray-900 group-hover:text-[#70ad47] transition-colors line-clamp-2">{product.name}</h3>
                  {product.description && (
                    <div
                      className="text-gray-500 text-sm mt-1 line-clamp-2 rich-text prose prose-xs max-w-none"
                      dangerouslySetInnerHTML={{ __html: formatRichText(product.description) }}
                    />
                  )}
                  <div className="mt-3 pr-2">
                    <span className="text-lg font-bold text-[#70ad47]">{formatPrice(0)}</span>
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
        <div className="text-center mt-8">
          <Link href="/products" className="text-[#70ad47] font-medium hover:text-[#5a9040] transition-colors">
            Ver todos los productos →
          </Link>
        </div>
      </div>
    </section>
  );
}
