"use client";
import { BASE_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 recentPullsRef = useRef(null);
  const sliderRef = useRef(null);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);
  const [data, setData] = useState([]);


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

 
   const isAtStart = () => {
    const slider = sliderRef.current;
    if (!slider) return false;
    return slider.scrollLeft <= 0;
  };

  const isAtEnd = () => {
    const slider = sliderRef.current;
    if (!slider) return false;
    return slider.scrollLeft >= slider.scrollWidth - slider.clientWidth - 1;
  };

  // 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";
    }
  };


  // Touch handlers for mobile

  const handleMouseMove = (e) => {
    if (!isDragging) return;

    const slider = sliderRef.current;
    if (!slider) return;

    const x = e.pageX - slider.offsetLeft;
    const walk = (x - startX) * 2;

    // 🚫 LEFT boundary
    if (walk > 0 && isAtStart()) return;

    // 🚫 RIGHT boundary
    if (walk < 0 && isAtEnd()) return;

    e.preventDefault();
    slider.scrollLeft = scrollLeft - walk;
  };

  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);
  };

  async function f() {
    try {
      const res = await fetch(BASE_URL + "/api/pulls-home", {
        method: "POST", // ✅ POST
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ f: 1 }), // ✅ payload
      });

      if (!res.ok) {
        return;
      }

      const json = await res.json();
      setData(json);
    } catch (err) {
      
    }
  }

  useEffect(() => {
    // if (!user) return;
    f();
  }, []);

  return (
    <>
    
    <div className="z-0 overflow-visible">
      <div className="flex flex-col mt-10 items-center justify-center overflow-visible">
        <h1 className="mb-3 md:mb-5  font-extrabold text-base md:text-2xl 2xl:text-2xl flex justify-center items-center gap-2">
          <span className="w-2 h-2 rounded-full bg-white"></span>
          <span>LIVE SUPER PULLS</span>
        </h1>

        <div className="relative w-full z-40 overflow-visible">
          
          <div
            ref={sliderRef}
            className="flex gap-2 overflow-x-auto scrollbar-hide h-74.75 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 shrink-0 group hover:z-999 cursor-pointer select-none text-center"
                >
                  <Image
                    src={`/cards${card.image}`}
                    alt={card.title}
                    width={200}
                    height={300}
                    quality={75}
                    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  hover:z-999 group-active:scale-125 group-active:-rotate-6 active:!z-[99999999]"
                    style={{
                      userSelect: "none",
                      WebkitUserDrag: "none",
                      pointerEvents: "none",
                    }}
                  />
                  <span className="text-white z-10 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>
      </div>
    </div>
    </>
  );
}
