"use client";

import { motion, useAnimation, useMotionValue } from "framer-motion";
import { useEffect, useRef } from "react";

interface MarqueeScrollProps {
  children: React.ReactNode[];
  speed?: number; // Lower = faster
  direction?: "left" | "right";
  className?: string;
  pauseOnHover?: boolean;
}

/**
 * MarqueeScroll - Infinite horizontal scrolling content
 * Inspired by Lama Lama's horizontal showcase sections
 */
export default function MarqueeScroll({
  children,
  speed = 40,
  direction = "left",
  className = "",
  pauseOnHover = true,
}: MarqueeScrollProps) {
  const controls = useAnimation();
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const startAnimation = async () => {
      await controls.start({
        x: direction === "left" ? "-50%" : "50%",
        transition: {
          duration: speed,
          ease: "linear",
          repeat: Infinity,
        },
      });
    };

    startAnimation();
  }, [controls, speed, direction]);

  const handleMouseEnter = () => {
    if (pauseOnHover) controls.stop();
  };

  const handleMouseLeave = () => {
    if (pauseOnHover) {
      controls.start({
        x: direction === "left" ? "-50%" : "50%",
        transition: {
          duration: speed,
          ease: "linear",
          repeat: Infinity,
        },
      });
    }
  };

  return (
    <div
      ref={containerRef}
      className={`overflow-hidden ${className}`}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <motion.div
        className="flex"
        animate={controls}
        style={{
          width: "fit-content",
        }}
      >
        {[...children, ...children]} // Duplicate for seamless loop
      </motion.div>
    </div>
  );
}
