import Link from 'next/link';
import type { Category } from '@/types/api';
import { fetchCategories } from '@/lib/api';

export default async function CategoriesGrid() {
  let categories: Awaited<ReturnType<typeof fetchCategories>> = [];
  try {
    categories = await fetchCategories();
  } catch (e) {
    console.error('[CategoriesGrid] fetch error:', e);
  }

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

  const icons: Record<string, string> = {
    alimentacion: '🥜',
    suplementos: '💊',
    'cosmetica-natural': '🌸',
    'limpieza-ecologica': '🌿',
    'frutos-secos': '🥜',
    aceites: '🫒',
    'hierbas-infusiones': '🍵',
    vitaminas: '💊',
    proteinas: '🏋️',
    cremas: '🧴',
    jabones: '🧼',
  };

  const colors = [
    'bg-[#70ad47]/10 text-[#70ad47]',
    'bg-[#E76F51]/10 text-[#E76F51]',
    'bg-[#F4A261]/10 text-[#F4A261]',
    'bg-[#52B788]/10 text-[#52B788]',
    'bg-[#5a9040]/10 text-[#5a9040]',
  ];

  return (
    <section className="py-16 bg-gray-50">
      <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 text-center">Explora categorías</h2>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
          {categories.map((cat, i) => {
            const totalProducts = cat.children ? cat.children.length * 5 : 5;
            const emoji = cat.emoji ?? icons[cat.slug] ?? '📦';
            const colorClass = cat.color ?? colors[i % colors.length];
            const customColors = Boolean(cat.bgColor || cat.textColor);
            return (
              <Link key={cat.id} href={`/categories/${cat.slug}`}>
                <div
                  className={`p-5 rounded-xl border border-gray-200 hover:border-[#70ad47] transition-all hover:shadow-md text-center ${customColors ? 'bg-white' : `bg-white ${colorClass}`}`}
                  style={customColors ? { backgroundColor: cat.bgColor ?? '#F1F8E9', color: cat.textColor ?? '#2D6A4F' } : undefined}
                >
                  <div className="text-4xl mb-2">{emoji}</div>
                  <h3 className="font-semibold text-sm">{cat.name}</h3>
                  <p className="text-xs text-gray-500 mt-1">{totalProducts} productos</p>
                  {cat.children && cat.children.length > 0 && (
                    <div className="mt-2 flex flex-wrap justify-center gap-1">
                      {cat.children.slice(0, 3).map((child) => (
                        <span key={child.id} className="text-xs bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded">{child.name}</span>
                      ))}
                    </div>
                  )}
                </div>
              </Link>
            );
          })}
        </div>
      </div>
    </section>
  );
}
