'use client';
import { useState, useEffect } from 'react';
import { Card } from '@/types';

export default function PublicGrid({ cards, maxCols = 5 }: { cards: Card[], maxCols?: number }) {
  const [activeCard, setActiveCard] = useState<Card | null>(null);

  // Prevent background scrolling when modal is open
  useEffect(() => {
    if (activeCard) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = 'unset';
    return () => { document.body.style.overflow = 'unset'; }
  }, [activeCard]);

  // Tailwind classes mapping based on the admin's chosen max columns
  const gridClasses: Record<number, string> = {
    3: 'xl:grid-cols-3 lg:grid-cols-3 md:grid-cols-2 grid-cols-1', // ADDED THIS LINE
    4: 'xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1',
    5: 'xl:grid-cols-5 lg:grid-cols-4 md:grid-cols-3 grid-cols-1',
    6: 'xl:grid-cols-6 lg:grid-cols-4 md:grid-cols-3 grid-cols-2',
    7: 'xl:grid-cols-7 lg:grid-cols-5 md:grid-cols-4 grid-cols-2',
    8: 'xl:grid-cols-8 lg:grid-cols-6 md:grid-cols-4 grid-cols-2',
  };

  const activeGridClass = gridClasses[maxCols] || gridClasses[5];

  return (
    <>
      <div className={`grid gap-4 ${activeGridClass}`}>
        {cards.map((card) => (
          <div 
            key={card.id} 
            onClick={() => setActiveCard(card)}
            className="group relative cursor-pointer overflow-hidden rounded-xl shadow-md aspect-square bg-gray-200 transition-all duration-300 hover:shadow-xl hover:-translate-y-1"
          >
            {card.imageUrl ? (
              <img src={card.imageUrl} alt={card.title} className="absolute inset-0 w-full h-full object-cover" />
            ) : (
              <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-blue-100 to-gray-200 text-gray-400">No Image</div>
            )}
            <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/30 to-transparent flex flex-col justify-end p-5 text-white">
              <h3 className="text-xl font-bold drop-shadow-md">{card.title}</h3>
              <p className="text-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300 line-clamp-2 mt-1 text-gray-200 drop-shadow">
                {card.shortDescription}
              </p>
            </div>
          </div>
        ))}
      </div>

      {/* Improved Modal Pop-up */}
      {activeCard && (
        <div 
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-md p-4 transition-opacity"
          onClick={() => setActiveCard(null)} // Click outside to close
        >
          <div 
            className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto shadow-2xl animate-in fade-in zoom-in-95 duration-200"
            onClick={(e) => e.stopPropagation()} // Prevent clicks inside modal from closing it
          >
            <div className="relative h-72 w-full bg-gray-100">
               {activeCard.imageUrl && (
                 <img src={activeCard.imageUrl} className="w-full h-full object-cover rounded-t-2xl" alt="" />
               )}
               {/* Improved Close Button */}
               <button 
                 onClick={() => setActiveCard(null)}
                 className="absolute top-4 right-4 bg-black/60 text-white w-10 h-10 flex items-center justify-center rounded-full hover:bg-black hover:scale-110 transition-all shadow-lg"
                 title="Close"
               >
                 ✕
               </button>
            </div>
            <div className="p-8">
              <div className="text-xs text-blue-600 font-bold tracking-wider uppercase mb-2">{activeCard.cardType.replace('_', ' ')}</div>
              <h2 className="text-3xl font-bold mb-4 text-gray-900">{activeCard.title}</h2>
              {activeCard.fullContent ? (
                <div className="prose max-w-none text-gray-700" dangerouslySetInnerHTML={{ __html: activeCard.fullContent }} />
              ) : (
                <p className="text-gray-500 italic text-lg">{activeCard.shortDescription}</p>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}