import { ReactNode, useMemo } from 'react'
import { motion, useReducedMotion, Variants } from 'framer-motion'

// ── 스크롤 리빌: 섹션 진입 시 부드러운 페이드업 ──
export function Reveal({
  children,
  delay = 0,
  y = 24,
  className = '',
  as = 'div',
}: {
  children: ReactNode
  delay?: number
  y?: number
  className?: string
  as?: 'div' | 'section' | 'li'
}) {
  const reduce = useReducedMotion()
  const MotionTag = (motion as any)[as]
  return (
    <MotionTag
      className={className}
      initial={reduce ? false : { opacity: 0, y }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: '-60px' }}
      transition={{ duration: 0.7, delay, ease: [0.22, 1, 0.36, 1] }}
    >
      {children}
    </MotionTag>
  )
}

// ── stagger 컨테이너 + 아이템 (상품 그리드 등장) ──
export const staggerParent: Variants = {
  hidden: {},
  show: { transition: { staggerChildren: 0.07, delayChildren: 0.05 } },
}
export const staggerChild: Variants = {
  hidden: { opacity: 0, y: 22 },
  show: { opacity: 1, y: 0, transition: { duration: 0.6, ease: [0.22, 1, 0.36, 1] } },
}

export function StaggerGrid({ children, className = '' }: { children: ReactNode; className?: string }) {
  const reduce = useReducedMotion()
  return (
    <motion.div
      className={className}
      variants={reduce ? undefined : staggerParent}
      initial={reduce ? false : 'hidden'}
      whileInView="show"
      viewport={{ once: true, margin: '-40px' }}
    >
      {children}
    </motion.div>
  )
}

export function StaggerItem({ children, className = '' }: { children: ReactNode; className?: string }) {
  const reduce = useReducedMotion()
  return (
    <motion.div className={className} variants={reduce ? undefined : staggerChild}>
      {children}
    </motion.div>
  )
}

// ── 꽃잎 흩날림 레이어 (히어로/배경) ──
// CSS keyframes 기반, 외부 의존성 최소. prefers-reduced-motion 시 자동 숨김.
const PETAL_KINDS = ['', 'sage', 'cream'] as const
export function PetalLayer({ count = 14, className = '' }: { count?: number; className?: string }) {
  const reduce = useReducedMotion()
  const petals = useMemo(
    () =>
      Array.from({ length: count }).map((_, i) => {
        const size = 8 + Math.round(Math.random() * 14)
        return {
          left: Math.round(Math.random() * 100),
          size,
          delay: +(Math.random() * 12).toFixed(2),
          duration: +(10 + Math.random() * 10).toFixed(2),
          kind: PETAL_KINDS[i % PETAL_KINDS.length],
        }
      }),
    [count],
  )
  if (reduce) return null
  return (
    <div className={`petal-layer ${className}`} aria-hidden="true">
      {petals.map((p, i) => (
        <span
          key={i}
          className={`petal ${p.kind}`}
          style={{
            left: `${p.left}%`,
            width: `${p.size}px`,
            height: `${p.size}px`,
            animationDelay: `${p.delay}s`,
            animationDuration: `${p.duration}s`,
          }}
        />
      ))}
    </div>
  )
}

// ── 마이크로 인터랙션: 부드러운 호버/탭 버튼 래퍼 ──
export function Pressable({
  children,
  className = '',
  onClick,
  type = 'button',
  disabled,
}: {
  children: ReactNode
  className?: string
  onClick?: () => void
  type?: 'button' | 'submit'
  disabled?: boolean
}) {
  const reduce = useReducedMotion()
  return (
    <motion.button
      type={type}
      onClick={onClick}
      disabled={disabled}
      className={className}
      whileHover={reduce || disabled ? undefined : { scale: 1.03, y: -1 }}
      whileTap={reduce || disabled ? undefined : { scale: 0.97 }}
      transition={{ type: 'spring', stiffness: 380, damping: 22 }}
    >
      {children}
    </motion.button>
  )
}
