import React, { useEffect, useRef } from 'react'
import gsap from 'gsap'

export default function RevealCard({ children, active, id, className = "" }) {
  const cardRef = useRef(null)
  
  useEffect(() => {
    const card = cardRef.current
    if (!card) return

    // Find all target children inside the card to create a staggered entrance
    const animTargets = card.querySelectorAll(
      '.section-badge, .section-title, .section-subtitle, .section-description, .section-metrics, .section-supporting, .section-close-btn'
    )

    // The promise card (the final card) is centred, so its reveal/exit tweens
    // must preserve the -50%/-50% centring offset.
    const isCentered = id === 'promise-section'

    if (active) {
      // Clean up any ongoing animations first
      gsap.killTweensOf([card, animTargets])

      // Animate card container in
      gsap.to(card, {
        xPercent: isCentered ? -50 : 0,
        yPercent: isCentered ? -50 : 0,
        y: 0,
        scale: 1,
        opacity: 1,
        duration: 0.85,
        ease: 'power4.out',
      })

      // Stagger child elements reveal
      gsap.fromTo(
        animTargets,
        { 
          y: 15, 
          opacity: 0 
        },
        {
          y: 0,
          opacity: 1,
          duration: 0.6,
          stagger: 0.08,
          ease: 'power3.out',
          delay: 0.1, // brief delay to let card body expand first
        }
      )
    } else {
      // Kill active tweens
      gsap.killTweensOf([card, animTargets])

      // Animate card container out
      gsap.to(card, {
        xPercent: isCentered ? -50 : 0,
        yPercent: isCentered ? -50 : 0,
        y: isCentered ? 18 : 20,
        scale: 0.96,
        opacity: 0,
        duration: 0.5,
        ease: 'power3.inOut',
      })
      
      // Smoothly hide child elements
      gsap.to(animTargets, {
        y: 10,
        opacity: 0,
        duration: 0.35,
        ease: 'power2.in',
      })
    }
  }, [active, id])

  return (
    <div 
      ref={cardRef} 
      id={id} 
      className={`section-panel ${active ? 'active' : ''} ${className}`}
      style={{
        opacity: 0,
        transform: id === 'promise-section'
          ? 'translate(-50%, -50%) translateY(18px) scale(0.96)'
          : 'translateY(20px) scale(0.96)',
      }}
    >
      {children}
    </div>
  )
}
