import React, { useState, useEffect, useRef } from 'react';

export interface RevealCard {
  label: string;
  sublabel?: string;
  content: string;
}

const COLORS: Record<string, {
  text: string; activeBg: string; activeBorder: string;
  hoverBorder: string; btn: string;
}> = {
  fuchsia: { text: 'text-fuchsia-700', activeBg: 'bg-fuchsia-50', activeBorder: 'border-fuchsia-300', hoverBorder: 'hover:border-fuchsia-300', btn: 'text-fuchsia-600' },
  teal: { text: 'text-teal-700', activeBg: 'bg-teal-50', activeBorder: 'border-teal-300', hoverBorder: 'hover:border-teal-300', btn: 'text-teal-600' },
  purple: { text: 'text-purple-700', activeBg: 'bg-purple-50', activeBorder: 'border-purple-300', hoverBorder: 'hover:border-purple-300', btn: 'text-purple-600' },
  rose: { text: 'text-rose-700', activeBg: 'bg-rose-50', activeBorder: 'border-rose-300', hoverBorder: 'hover:border-rose-300', btn: 'text-rose-600' },
  indigo: { text: 'text-indigo-700', activeBg: 'bg-indigo-50', activeBorder: 'border-indigo-300', hoverBorder: 'hover:border-indigo-300', btn: 'text-indigo-600' },
  amber: { text: 'text-amber-700', activeBg: 'bg-amber-50', activeBorder: 'border-amber-300', hoverBorder: 'hover:border-amber-300', btn: 'text-amber-600' },
};

interface Props {
  cards: RevealCard[];
  columns?: 2 | 3 | 4 | 5;
  accentColor?: string;
}

const RevealCardGrid: React.FC<Props> = ({ cards, columns = 3, accentColor = 'fuchsia' }) => {
  const [revealed, setRevealed] = useState<Set<number>>(new Set());
  const [visible, setVisible] = useState(false);
  const [entered, setEntered] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const c = COLORS[accentColor] || COLORS.fuchsia;

  /* Entrance trigger — animate cards when grid scrolls into view */
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      entries => { if (entries[0]?.isIntersecting) { setVisible(true); obs.disconnect(); } },
      { threshold: 0.1 },
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  /* Clear stagger delays after entrance finishes so tap interactions are instant */
  useEffect(() => {
    if (!visible) return;
    const t = setTimeout(() => setEntered(true), Math.min(cards.length * 50, 600) + 400);
    return () => clearTimeout(t);
  }, [visible, cards.length]);

  const toggle = (i: number) =>
    setRevealed(prev => { const s = new Set(prev); s.has(i) ? s.delete(i) : s.add(i); return s; });

  const allDone = revealed.size === cards.length;

  const colCls =
    columns === 2 ? 'grid-cols-1 sm:grid-cols-2'
      : columns === 4 ? 'grid-cols-2 sm:grid-cols-4'
        : columns === 5 ? 'grid-cols-2 sm:grid-cols-5'
          : 'grid-cols-2 sm:grid-cols-3';

  return (
    <div ref={ref} className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-xs text-slate-400 font-medium">
          {revealed.size}/{cards.length} revealed
        </p>
        <button
          onClick={() => setRevealed(allDone ? new Set() : new Set(cards.map((_, i) => i)))}
          className={`text-xs font-bold ${c.btn} hover:underline transition-colors`}
        >
          {allDone ? 'Hide All' : 'Reveal All'}
        </button>
      </div>

      <div className={`grid ${colCls} gap-2`}>
        {cards.map((card, i) => {
          const open = revealed.has(i);
          return (
            <button
              key={i}
              onClick={() => toggle(i)}
              aria-expanded={open}
              className={[
                'text-left rounded-xl p-3 border transition-all duration-300 ease-out',
                visible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-3',
                open
                  ? `${c.activeBg} ${c.activeBorder} shadow-sm`
                  : `bg-slate-50 border-slate-200 ${c.hoverBorder} hover:shadow-sm`,
              ].join(' ')}
              style={{ transitionDelay: !entered ? `${Math.min(i * 50, 600)}ms` : '0ms' }}
            >
              <p className={`font-bold ${c.text} text-xs mb-0.5`}>{card.label}</p>
              {card.sublabel && (
                <p className="text-[10px] text-slate-500 font-medium mb-1">{card.sublabel}</p>
              )}
              <div className={`transition-opacity duration-200 ${open ? 'opacity-100' : 'opacity-50'}`}>
                {open ? (
                  <p className="text-xs text-slate-600 leading-relaxed">{card.content}</p>
                ) : (
                  <p className="text-xs text-slate-400 italic">tap to reveal</p>
                )}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
};

export default RevealCardGrid;
