import {API_URL} from "@/constants";
import Image from "next/image";
import { useRef, useState, useEffect } from "react";
import { useInView, motion } from "framer-motion";

export default function RecentPullsSlider() {
  const [isPaused, setIsPaused] = useState(false);
  const recentPullsRef = useRef(null);
  const sliderRef = useRef(null);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);

  // Control the animation using the inView state
  const isInView = useInView(recentPullsRef, {
    once: false,
    margin: "-100px 0px",
  });

  // Sample card images
  const cards = [
    "/assets/landingPage/recentPulls/1.png",
    "/assets/landingPage/recentPulls/2.png",
    "/assets/landingPage/recentPulls/3.png",
    "/assets/landingPage/recentPulls/4.png",
    "/assets/landingPage/recentPulls/6.png",
    "/assets/landingPage/recentPulls/7.png",
    "/assets/landingPage/recentPulls/8.png",
    "/assets/landingPage/recentPulls/9.png",
    "/assets/landingPage/recentPulls/10.png",
  ];
  const duplicatedCards = [...cards, ...cards, ...cards];

  // Animation variants
  const containerVariants = {
    hidden: { opacity: 0, y: 50 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.8,
        ease: "easeOut",
        when: "beforeChildren",
        staggerChildren: 0.1,
      },
    },
  };

  // Infinite scroll loop
  useEffect(() => {
    const slider = sliderRef.current;
    if (!slider) return;

    const handleScroll = () => {
      const maxScroll = slider.scrollWidth / 3;
      
      // Reset to beginning when reached the end of first set
      if (slider.scrollLeft >= maxScroll * 2) {
        slider.scrollLeft = maxScroll;
      }
      // Reset to end when scrolled before the beginning
      else if (slider.scrollLeft <= 0) {
        slider.scrollLeft = maxScroll;
      }
    };

    slider.addEventListener('scroll', handleScroll);

    return () => {
      slider.removeEventListener('scroll', handleScroll);
    };
  }, []);

  // Mouse drag handlers
  const handleMouseDown = (e) => {
    setIsDragging(true);
    setStartX(e.pageX - sliderRef.current.offsetLeft);
    setScrollLeft(sliderRef.current.scrollLeft);
    sliderRef.current.style.cursor = "grabbing";
  };

  const handleMouseLeave = () => {
    setIsDragging(false);
    if (sliderRef.current) {
      sliderRef.current.style.cursor = "grab";
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
    if (sliderRef.current) {
      sliderRef.current.style.cursor = "grab";
    }
  };

  const handleMouseMove = (e) => {
    if (!isDragging) return;
    e.preventDefault();
    const x = e.pageX - sliderRef.current.offsetLeft;
    const walk = (x - startX) * 2;
    sliderRef.current.scrollLeft = scrollLeft - walk;
  };

  // Touch handlers for mobile
  const handleTouchStart = (e) => {
    setIsDragging(true);
    setStartX(e.touches[0].pageX);
    setScrollLeft(sliderRef.current.scrollLeft);
  };

  const handleTouchMove = (e) => {
    if (!isDragging) return;
    const x = e.touches[0].pageX;
    const walk = (startX - x) * 2;
    sliderRef.current.scrollLeft = scrollLeft + walk;
  };

  
  const handleTouchEnd = () => {
    setIsDragging(false);
  };

  const [data, setData] = useState([])
  async function f() {
            try {
                const res = await fetch(API_URL + "pulls-home", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ 
                        f:1
                     }),
                });
    
                const data = await res.json();
                setData(data);
            } catch (err) {
                
            }
    }
    
    useEffect(()=>{
        f();
    }, []);

  return (
    <div className="z-0 overflow-visible">
      {/* <motion.div
        ref={recentPullsRef}
        variants={containerVariants}
        initial="hidden"
        animate={isInView ? "visible" : "hidden"}
        className="overflow-visible"
      > */}
        <div className="flex flex-col mt-5 items-center justify-center overflow-visible">
          <h2 className="text-center text-white VCR-font-family font-normal text-sm px-2 sm:text-2xl drop-shadow-[0_0_6px_rgba(255,255,255,0.6)] ">
            RECENT PULLS
          </h2>

          {/* Slider Container - Added padding top and bottom for hover expansion */}
          <div className="relative w-full z-40 overflow-visible">
            <div
              ref={sliderRef}
              className="flex gap-2 overflow-x-auto scrollbar-hide h-[299px] cursor-grab select-none overflow-y-visible"
              style={{
                width: "100%",
                scrollBehavior: isDragging ? "auto" : "smooth",
                userSelect: "none",
                WebkitUserSelect: "none",
                MozUserSelect: "none",
                msUserSelect: "none",
              }}
              onMouseDown={handleMouseDown}
              onMouseLeave={handleMouseLeave}
              onMouseUp={handleMouseUp}
              onMouseMove={handleMouseMove}
              onTouchStart={handleTouchStart}
              onTouchMove={handleTouchMove}
              onTouchEnd={handleTouchEnd}
            >
              <div className="flex gap-2 pt-8 2xl:py-9">
                {data.map((card, index) => (
                  <div
                    key={index}
                    className="relative flex-shrink-0 group hover:!z-[99999999] cursor-pointer select-none text-center"
                    onMouseEnter={() => setIsPaused(true)}
                    onMouseLeave={() => setIsPaused(false)}
                  >
                    <Image
                      src={card.image}
                      alt={`Card ${index + 1}`}
                      width={200}
                      height={300}
                      quality={100}
                      draggable={false}
                      className="w-32 sm:w-36 h-auto 2xl:w-40 2xl:h-56 rounded-lg shadow-2xl object-cover transition-all duration-500 ease-in-out select-none group-hover:scale-125 group-hover:-rotate-6 hover:!z-[99999999] group-active:scale-125 group-active:-rotate-6 active:!z-[99999999]"
                      style={{ 
                        userSelect: "none",
                        WebkitUserDrag: "none",
                        pointerEvents: "none"
                      }}
                    />
                      <span className="text-white VCR-font-family font-normal text-sm px-2 sm:text drop-shadow-[0_0_6px_rgba(255,255,255,0.6)] ">
                          {card.date}
                      </span>
                  </div>
                ))}
              </div>
            </div>
          </div>

            {/* Hide scrollbar */}
          <style jsx>{`
            .scrollbar-hide::-webkit-scrollbar {
              display: none;
            }
            .scrollbar-hide {
              -ms-overflow-style: none;
              scrollbar-width: none;
            }
          `}</style>
        </div>
      {/* </motion.div> */}
    </div>
  );
}