import { Link } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles';

interface BentoItem {
  label: string;
  image?: string;
  url?: string;
  size?: 'small' | 'medium' | 'large' | 'tall';
}

interface BentoCategoryGridProps {
  id: string;
  title?: string;
  items?: BentoItem[];
  styles?: Record<string, any>;
  elementStyles?: Record<string, any>;
}

// Default demo categories if no items are provided
const DEMO_ITEMS: BentoItem[] = [
  { label: 'New Arrivals', size: 'large' },
  { label: 'Best Sellers', size: 'medium' },
  { label: 'On Sale', size: 'small' },
  { label: 'Accessories', size: 'small' },
  { label: 'Collections', size: 'tall' },
];

// Map size variants to grid span classes
const SIZE_CLASSES: Record<string, string> = {
  large:  'col-span-2 row-span-2',
  medium: 'col-span-2 row-span-1',
  tall:   'col-span-1 row-span-2',
  small:  'col-span-1 row-span-1',
};

const HEIGHT_CLASSES: Record<string, string> = {
  large:  'min-h-[280px] md:min-h-[340px]',
  medium: 'min-h-[160px] md:min-h-[180px]',
  tall:   'min-h-[280px] md:min-h-[340px]',
  small:  'min-h-[140px] md:min-h-[160px]',
};

// Colour palette cycling through for items without images
const COLOURS = [
  'from-violet-600 to-indigo-700',
  'from-rose-500 to-pink-600',
  'from-amber-500 to-orange-600',
  'from-emerald-500 to-teal-600',
  'from-sky-500 to-blue-600',
];

export function BentoCategoryGrid({
  id,
  title,
  items,
  styles,
  elementStyles,
}: BentoCategoryGridProps) {
  const sectionBg = getSectionBackground(styles);
  // Keep initial demo layout stable: merge configured items over demo items by index.
  // This prevents the preview grid from "collapsing" when the first item is added.
  const displayItems: BentoItem[] = (() => {
    if (!items || items.length === 0) return DEMO_ITEMS;

    return DEMO_ITEMS.map((demo, idx) => {
      const configured = items[idx];
      return configured ? { ...demo, ...configured } : demo;
    });
  })();

  return (
    <section
      id={id}
      className="wn-section wn-bento-grid py-12 md:py-16"
      style={sectionBg.style}
    >
      <div className="container mx-auto px-4 max-w-7xl">
        {title && (
          <h2
            className="text-3xl md:text-4xl font-bold mb-8"
            style={{ color: elementStyles?.title?.color }}
          >
            {title}
          </h2>
        )}

        {/* Bento grid — 4-column on desktop, 2-column on mobile */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 auto-rows-auto">
          {displayItems.map((item, idx) => {
            const size = item.size || 'small';
            const gradientClass = COLOURS[idx % COLOURS.length];

            const inner = (
              <div
                className={cn(
                  'relative overflow-hidden rounded-2xl group cursor-pointer',
                  HEIGHT_CLASSES[size],
                )}
              >
                {/* Background */}
                {item.image ? (
                  <img
                    src={item.image}
                    alt={item.label}
                    className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                  />
                ) : (
                  <div className={cn('absolute inset-0 bg-gradient-to-br', gradientClass)} />
                )}

                {/* Overlay */}
                <div className="absolute inset-0 bg-black/20 group-hover:bg-black/30 transition-colors duration-300" />

                {/* Label */}
                <div className="absolute inset-0 flex items-end p-5">
                  <span className="text-white font-bold text-lg md:text-xl drop-shadow-lg">
                    {item.label}
                  </span>
                </div>
              </div>
            );

            return (
              <div key={idx} className={cn(SIZE_CLASSES[size])}>
                {item.url ? (
                  <Link to={item.url} className="block h-full">
                    {inner}
                  </Link>
                ) : (
                  inner
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
