import Link from 'next/link';
import type { Metadata } from 'next';
import { fetchCategories } from '@/lib/api';
import { CmsBlock } from '@/components/content/CmsBlock';

// Categories depend on the live catalog API. Do not call the API during
// production builds: the backend may be deployed separately or unavailable.
export const dynamic = 'force-dynamic';

export const metadata: Metadata = {
  title: 'Categorías — mercadodevida',
  description: 'Explora todas las categorías de productos naturales y orgánicos.',
};

const icons: Record<string, string> = {
  alimentacion: '🥜',
  suplementos: '💊',
  'cosmetica-natural': '🌸',
  'limpieza-ecologica': '🌿',
};

const colors = [
  'from-[#70ad47] to-[#40916C]',
  'from-[#E76F51] to-[#F4A261]',
  'from-[#52B788] to-[#74C69D]',
  'from-[#5a9040] to-[#70ad47]',
];

export default async function CategoriesPage() {
  const tree = await fetchCategories();

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900" style={{ fontFamily: 'var(--font-heading)' }}>
          Categorías
        </h1>
        <p className="mt-2 text-gray-600">
          Explora nuestra selección de productos naturales y ecológicos organizados por categoría.
        </p>
        {/* Plantilla CMS editable desde Admin → CMS (slug: categories) */}
        <CmsBlock slug="categories" />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 justify-center">
        {tree.map((cat, i) => {
          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}`} className="group block">
              <div
                className={`relative overflow-hidden rounded-2xl ${customColors ? '' : `bg-gradient-to-br ${colorClass} text-white`} p-6 min-h-[140px] flex flex-col justify-between`}
                style={customColors ? { backgroundColor: cat.bgColor ?? '#F1F8E9', color: cat.textColor ?? '#2D6A4F' } : undefined}
              >
                <div className="absolute top-4 right-4 text-5xl opacity-20">{emoji}</div>
              <div>
                <h2 className="text-xl font-bold group-hover:underline">{cat.name}</h2>
                {cat.seoDescription && (
                  <p className="mt-1 text-sm opacity-80 line-clamp-2">{cat.description || cat.seoDescription}</p>
                )}
              </div>
              <div className="mt-4 flex flex-wrap gap-2">
                {cat.children?.map((child) => (
                  <span key={child.id} className="text-xs bg-white/20 px-2 py-1 rounded-full backdrop-blur-sm">
                    {child.name}
                  </span>
                ))}
                {(!cat.children || cat.children.length === 0) && (
                  <span className="text-xs bg-white/20 px-2 py-1 rounded-full backdrop-blur-sm">
                    Ver productos
                  </span>
                )}
              </div>
            </div>
          </Link>
      );
    })}
      </div>
    </div>
  );
}
