import type { CSSProperties } from "react";
import { motion, type MotionStyle, type Transition } from "motion/react";

import { cn } from "@/lib/utils";

interface BorderBeamProps {
  size?: number;
  duration?: number;
  delay?: number;
  colorFrom?: string;
  colorTo?: string;
  transition?: Transition;
  className?: string;
  style?: CSSProperties;
  reverse?: boolean;
  initialOffset?: number;
  borderWidth?: number;
}

/**
 * Border Beam (Magic UI) — mesma lógica do registry oficial; estilos de máscara/borda
 * em inline CSS para compatibilidade com Tailwind 3 (o doc do Magic UI usa utilitários v4).
 */
export const BorderBeam = ({
  className,
  size = 50,
  delay = 0,
  duration = 6,
  colorFrom = "#ffaa40",
  colorTo = "#9c40ff",
  transition,
  style,
  reverse = false,
  initialOffset = 0,
  borderWidth = 1,
}: BorderBeamProps) => {
  const maskWrapperStyle: CSSProperties = {
    borderWidth: `${borderWidth}px`,
    borderStyle: "solid",
    borderColor: "transparent",
    maskImage: "linear-gradient(transparent, transparent), linear-gradient(#000, #000)",
    maskClip: "padding-box, border-box",
    maskComposite: "intersect",
    maskRepeat: "no-repeat",
    WebkitMaskImage: "linear-gradient(transparent, transparent), linear-gradient(#000, #000)",
    WebkitMaskClip: "padding-box, border-box",
    WebkitMaskComposite: "source-in",
  };

  const beamGradient: CSSProperties = {
    width: size,
    offsetPath: `rect(0 auto auto 0 round ${size}px)`,
    backgroundImage: `linear-gradient(to left, ${colorFrom}, ${colorTo}, transparent)`,
  };

  return (
    <div
      className="pointer-events-none absolute inset-0 rounded-[inherit]"
      style={maskWrapperStyle}
    >
      <motion.div
        className={cn("absolute aspect-square", className)}
        style={{ ...beamGradient, ...style } as MotionStyle}
        initial={{ offsetDistance: `${initialOffset}%` }}
        animate={{
          offsetDistance: reverse
            ? [`${100 - initialOffset}%`, `${-initialOffset}%`]
            : [`${initialOffset}%`, `${100 + initialOffset}%`],
        }}
        transition={{
          repeat: Infinity,
          ease: "linear",
          duration,
          delay: -delay,
          ...transition,
        }}
      />
    </div>
  );
};
