import { motion } from 'framer-motion'
import { cn } from '@/lib/utils'

interface BorderBeamProps {
  className?: string
  size?: number
  duration?: number
  borderWidth?: number
  colorFrom?: string
  colorTo?: string
  delay?: number
  reverse?: boolean
}

/**
 * Animated border beam — a small light that travels around an element's border.
 *
 * - Movement is driven by framer-motion (`offsetDistance`), not a CSS keyframe.
 * - The beam is confined to a thin ring with the proven mask-composite:exclude
 *   technique (with -webkit- prefixes), applied via inline style — the Tailwind
 *   arbitrary `[mask-composite:intersect]` variant does NOT apply reliably here.
 *
 * Host element must be `position: relative` (overflow:hidden recommended).
 */
export const BorderBeam = ({
  className,
  size = 40,
  duration = 6,
  borderWidth = 1.5,
  colorFrom = '#ffaa40',
  colorTo = '#9c40ff',
  delay = 0,
  reverse = false,
}: BorderBeamProps) => {
  return (
    <div
      className="pointer-events-none absolute inset-0 rounded-[inherit]"
      style={{
        padding: borderWidth,
        WebkitMask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
        WebkitMaskComposite: 'xor',
        mask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
        maskComposite: 'exclude',
      } as React.CSSProperties}
    >
      <motion.div
        className={cn('absolute aspect-square', className)}
        style={{
          width: size,
          offsetPath: `rect(0 auto auto 0 round ${size}px)`,
          background: `linear-gradient(to left, ${colorFrom}, ${colorTo}, transparent)`,
        }}
        initial={{ offsetDistance: `${reverse ? 100 : 0}%` }}
        animate={{ offsetDistance: reverse ? ['100%', '0%'] : ['0%', '100%'] }}
        transition={{ repeat: Infinity, ease: 'linear', duration, delay: -delay }}
      />
    </div>
  )
}
