"use client";

import { useState, useRef, useEffect, useMemo } from "react";
import Image from "next/image";
import { withCDN } from "@/src/lib/utils";
 
type Slide = {
  title: string; // program name
  age: string;
  label: string;
  imageSrc: string;
  iconSrc: string;
};
 
const slides: Slide[] = [
  {
    title: "ALGO BUDDY",
    age: "4–6",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"),
    iconSrc: withCDN("/program-logo/logo_algo_buddy.svg"),
  },
  {
    title: "BIG BUILDERS",
    age: "4–6",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"), // change to proper image
    iconSrc: withCDN("/program-logo/logo_big_builders.svg"),
  },
  {
    title: "BRICKS CHALLENGE",
    age: "6–10",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"),
    iconSrc: withCDN("/program-logo/logo_bricks_chalenge.svg"),
  },
  {
    title: "ALGO PLAY",
    age: "6–10",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"),
    iconSrc: withCDN("/program-logo/logo_algo_play.svg"),
  },
  {
    title: "GALILEO TECHNIC",
    age: "7–10",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"),
    iconSrc: withCDN("/program-logo/logo_galileo_technic.svg"),
  },
  {
    title: "ROBO TOYS",
    age: "9–12",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"),
    iconSrc: withCDN("/program-logo/logo_robo_toys.svg"),
  },
  {
    title: "ROBOTICS",
    age: "12–15",
    label: "Y.O. PROGRAM",
    imageSrc: withCDN("/programs-page/enrichImage.svg"),
    iconSrc: withCDN("/program-logo/logo_pro.svg"),
  },
];
 
export default function ProgramsMobileSlider() {
  // Start at index 1 (first real slide, index 0 is clone of last slide)
  const [current, setCurrent] = useState(1);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [currentX, setCurrentX] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(true);
  const sliderRef = useRef<HTMLDivElement>(null);
  const currentRef = useRef(1);

  // Create infinite loop slides: [last, ...slides, first]
  const infiniteSlides = useMemo(
    () => [slides[slides.length - 1], ...slides, slides[0]],
    []
  );

  // Keep ref in sync with state
  useEffect(() => {
    currentRef.current = current;
  }, [current]);

  // Handle seamless loop transitions
  useEffect(() => {
    if (!isTransitioning) return;

    const timer = setTimeout(() => {
      // If we're at the clone of last slide (index 0), jump to real last slide
      if (current === 0) {
        setIsTransitioning(false);
        setCurrent(slides.length);
        currentRef.current = slides.length;
        setTimeout(() => setIsTransitioning(true), 50);
      }
      // If we're at the clone of first slide (last index = slides.length + 1), jump to real first slide
      else if (current === slides.length + 1) {
        setIsTransitioning(false);
        setCurrent(1);
        currentRef.current = 1;
        setTimeout(() => setIsTransitioning(true), 50);
      }
    }, 300); // Wait for transition to complete

    return () => clearTimeout(timer);
  }, [current, isTransitioning, slides.length]);

  const goTo = (index: number) => {
    setIsTransitioning(true);
    setCurrent(index);
    currentRef.current = index;
  };

  const next = () => {
    const nextIndex = currentRef.current + 1;
    goTo(nextIndex);
  };

  const prev = () => {
    const prevIndex = currentRef.current - 1;
    goTo(prevIndex);
  };

  // Touch handlers
  const handleTouchStart = (e: React.TouchEvent) => {
    setIsDragging(true);
    setStartX(e.touches[0].clientX);
    setCurrentX(e.touches[0].clientX);
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isDragging) return;
    setCurrentX(e.touches[0].clientX);
  };

  const handleTouchEnd = () => {
    if (!isDragging) return;
    const diff = startX - currentX;
    const threshold = 50; // minimum swipe distance

    if (Math.abs(diff) > threshold) {
      if (diff > 0) {
        next(); // swipe left, go to next
      } else {
        prev(); // swipe right, go to previous
      }
    }

    setIsDragging(false);
    setStartX(0);
    setCurrentX(0);
  };

  // Mouse handlers
  const handleMouseDown = (e: React.MouseEvent) => {
    setIsDragging(true);
    setStartX(e.clientX);
    setCurrentX(e.clientX);
    e.preventDefault();
  };

  // Use document-level mouse events for better drag handling
  useEffect(() => {
    if (!isDragging) return;

    const handleMouseMove = (e: MouseEvent) => {
      setCurrentX(e.clientX);
    };

    const handleMouseUp = () => {
      const diff = startX - currentX;
      const threshold = 50; // minimum drag distance

      if (Math.abs(diff) > threshold) {
        if (diff > 0) {
          next(); // drag left, go to next
        } else {
          prev(); // drag right, go to previous
        }
      }

      setIsDragging(false);
      setStartX(0);
      setCurrentX(0);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, startX, currentX]);

  // Calculate transform offset during drag
  const getTransform = () => {
    if (!isDragging) {
      return `translateX(-${current * 100}%)`;
    }
    const diff = currentX - startX;
    const slideWidth = sliderRef.current?.clientWidth || 0;
    const offset = (diff / slideWidth) * 100;
    return `translateX(calc(-${current * 100}% + ${offset}%))`;
  };

  // Get the real slide index for dots (0 to slides.length - 1)
  const getRealIndex = (index: number) => {
    if (index === 0) return slides.length - 1; // Clone of last = last
    if (index === infiniteSlides.length - 1) return 0; // Clone of first = first
    return index - 1; // Real slides are offset by 1
  };

  return (
    <div className="w-full">
      {/* SLIDE TRACK */}
      <div 
        ref={sliderRef}
        className="relative w-full overflow-hidden h-[220px] rounded-[18px] bg-white shadow-[6.31px_8.83px_8.83px_0px_rgba(0,0,0,0.05)] cursor-grab active:cursor-grabbing"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        onMouseDown={handleMouseDown}
      >
        <div
          className="flex transition-transform duration-300 ease-out"
          style={{ 
            transform: getTransform(),
            transition: isDragging || !isTransitioning ? 'none' : 'transform 0.3s ease-out'
          }}
        >
          {infiniteSlides.map((slide, idx) => (
            <div key={`${slide.title}-${idx}`} className="w-full flex-shrink-0">
              {/* IMAGE */}
              <div className="relative w-full aspect-[4/3] overflow-hidden rounded-t-[18px] h-[180px]">
                <Image
                  src={slide.imageSrc}
                  alt={slide.title}
                  fill
                  className="object-cover"
                  priority={idx === 0}
                />
              </div>
 
              {/* STRIP: ICON + TEXT */}
              <div className="bg-white px-4 py-1 flex items-center justify-center">
                <div className="flex items-center gap-2">
                  <div className="relative h-8 w-18">
                    <Image
                      src={slide.iconSrc}
                      alt={slide.title}
                      fill
                      className="object-contain"
                    />
                  </div>
                  <div className="leading-tight">
                    <p className="text-[10px] text-slate-500 font-bold text-center">
                      {slide.age}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
 
      </div>

      {/* DOTS CENTERED - Outside the card */}
      <div className="flex justify-center mt-4">
        <div className="flex gap-3 items-center">
          {slides.map((_, i) => {
            const realIndex = getRealIndex(current);
            return (
              <button
                key={i}
                type="button"
                onClick={() => goTo(i + 1)} // +1 because real slides start at index 1
                className={`h-2 w-2 rounded-full transition-colors ${
                  i === realIndex ? "bg-[#0097DC]" : "bg-[#0097DC]/30"
                }`}
                aria-label={`Go to slide ${i + 1}`}
              />
            );
          })}
        </div>
      </div>
    </div>
  );
}
