"use client";

import Image from "next/image";
import { useRef, useState } from "react";
import ProgramsMobileSlider from "./ProgramsMobileSlider";
import { withCDN } from "@/src/lib/utils";
import type { ProgramsPageSection } from "@/src/lib/services/programsPageService";
import ImageLightbox from "../ui/ImageLightbox";
import { scrollToId } from "@/src/lib/utils/scrollToId";

interface InspiringYounMindsProps {
  inspiringMindData?: ProgramsPageSection;
}

const defaultData = {
  id: 1,
  contentTitle: "INSPIRING YOUNG MINDS AROUND THE GLOBE",
  description:
    "Young Engineers offers interactive enrichment programs, immersing students in the joys of hands-on learning. Designed by our dedicated research and development team, our sets enable students to build intriguing machines,models and robots, reinforcing the notion that education can be a thrilling adventure.",
  ctaButtonText: "Get Your Free Ticket",
  mainImage: withCDN("/programs-page/InspiringYoung/IMG_2147%201.png"),
  
  thumbnails: [
    withCDN("/discover/discover-1.png"),
    withCDN("/discover/discover-2.png"),
    withCDN("/discover/discover-5.png"),
    withCDN("/discover/discover-6.png"),
  ],
};

/**
 * Parse images from API data (JSON stringified array)
 */
function parseImages(imagesJson?: string) {
  if (!imagesJson) return null;
  try {
    const images = JSON.parse(imagesJson);
    if (Array.isArray(images) && images.length > 0) {
      return images;
    }
    return null;
  } catch (error) {
    console.warn("[InspiringYounMinds] Failed to parse images:", error);
    return null;
  }
}

export default function InspiringYounMinds({ inspiringMindData }: InspiringYounMindsProps) {
  // Parse images from API with fallback to defaults
  const apiImages = parseImages(inspiringMindData?.images);
  const finalImages = apiImages || [defaultData.mainImage, ...defaultData.thumbnails];
  
  const currentData = {
    id: 1,
    contentTitle: inspiringMindData?.heading || defaultData.contentTitle,
    description: inspiringMindData?.description || defaultData.description,
    ctaButtonText: inspiringMindData?.ctaButtonText || defaultData.ctaButtonText,
    mainImage: finalImages[0],
     allImages: finalImages,
  };

  // For mobile slider - combine main image with thumbnails
const allImages = currentData.allImages;
  const [currentSlide, setCurrentSlide] = useState(0);
  const [mainImage, setMainImage] = useState(currentData?.mainImage);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  const nextSlide = () => {
    setCurrentSlide((prev) => (prev + 1) % allImages.length);
  };

   const prevSlide = () => {
    setCurrentSlide((prev) => {if (prev <= 0) { return prev; }
    return prev - 1;
    });
  };


const touchStartX = useRef<number | null>(null);
const touchStartY = useRef<number | null>(null);
const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
  const touch = e.touches[0];
  touchStartX.current = touch.clientX;
  touchStartY.current = touch.clientY;
};

const handleTouchEnd = ( e: React.TouchEvent<HTMLDivElement>) => {
  if (
    touchStartX.current === null ||
    touchStartY.current === null
  ) {
    return;
  }

  const touch = e.changedTouches[0];
  const deltaX = touch.clientX - touchStartX.current;
  const deltaY =touch.clientY - touchStartY.current;
  // Reset touch position
  touchStartX.current = null;
  touchStartY.current = null;
  // Ignore vertical scrolling
  if (Math.abs(deltaY) > Math.abs(deltaX)) {
    return;
  }
  // Minimum swipe distance
  const SWIPE_THRESHOLD = 50;
  if (Math.abs(deltaX) < SWIPE_THRESHOLD) {
    return;
  }
  // Swipe LEFT → Next slide
  if (deltaX < 0) {
    nextSlide();
  }

  // Swipe RIGHT → Previous slide
  if (deltaX > 0) {
    prevSlide();
  }
};


  return (
    <section
      className="
      relative w-full overflow-hidden z-20 py-24 xl:h-[1000px] 2xl:h-[1130px] h-[1060px] md:h-[660px] lg:h-[810px] xl:h-[1130px] max-[400px]:h-[1050px]
      -mt-[240px]
      md:-mt-[100px]
      lg:-mt-[300px]
      xl:-mt-[250px]
      inspiring-block
    "
    >
      {/* Curved Background Image */}
      <div className="absolute inset-0 w-full h-full -z-10">
        {/* Desktop / Large */}
        <Image
          src={"https://yefranchisees.b-cdn.net/frontend/home/bg-desktop.png"}
          alt="Curved background"
          fill
          className="object-fit object-top hidden lg:block"
          priority
        />

        {/* Tablet */}
        <Image
          src={"https://yefranchisees.b-cdn.net/frontend/home/bg-desktop.png"}
          alt="Curved background for tablet"
          fill
          className="object-cover object-top hidden md:block lg:hidden"
          priority
        />

        {/* Mobile */}
        <Image
          src={"https://yefranchisees.b-cdn.net/frontend/home/bg-mobile.png"}
          alt="Curved background for mobile"
          fill
          className="object-cover object-top block md:hidden"
          priority
        />
      </div>
      <div className="max-w-[1300px] mx-auto w-full flex flex-col md:flex-row gap-4 md:gap-4 lg:gap-6 items-center lg:items-start mt-[-80] lg:mt-20 xl:mt-36 2xl:mt-17 md:mt-16  2xl:py-20   px-4 md:px-10 lg:px-18 xl:px-0">
        
        <h2 className="md:hidden text-[30px] leading-[1] font-[700] text-[#0097DC] uppercase mb-4 mt-25">
              {currentData?.contentTitle}
        </h2>

        {/* MOBILE SLIDER - Shows first on mobile */}
        <div className="block md:hidden w-full">
        <div className=" flex items-center justify-center gap-4 mt-0 touch-pan-y"
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
         >

        {/* Left Arrow */}
        <button
          onClick={prevSlide}
          className="flex-shrink-0"
           aria-label="Previous slide"
         >
        <Image
           src={withCDN("/arrow left.png")}
           alt="Previous"
           width={23}
           height={23}
           className="object-contain"
          />
        </button>
         
       {/* Image */}
      <div className=" relative flex-1 h-[170px] max-w-[340px] rounded-2xl overflow-hidden  bg-gray-200" >
      <img
        src={allImages[currentSlide]}
        alt={`Slide ${currentSlide + 1}`}
        className=" w-full h-full object-cover cursor-pointer select-none "
        draggable={false}
        onClick={() => setLightboxIndex(currentSlide)}
      />
    </div>

    {/* Right Arrow */}
    <button
      onClick={nextSlide}
      className="flex-shrink-0"
      aria-label="Next slide"
    >
      <Image
        src={withCDN("/arrow right.png")}
        alt="Next"
        width={23}
        height={23}
        className="object-contain"
      />
    </button>

  </div>

</div>

        {/* LEFT - Content */}
        <div className="w-full md:flex-1 flex flex-col gap-6  md:w-[45%] lg:w-[40%] xl:w-[40%]">
          <div className="w-full 2xl:w-[470px] xl:mt-[-50px]">
            <h2 className="hidden md:block md:text-md text-[30px] leading-[1] xl:text-[50px] xl:leading-[55px] xl:w-[90%] font-[700] text-[#0097DC] uppercase mb-4 mt-1 md:mt-[-30] lg:mt-[-1]">
              {currentData?.contentTitle}
            </h2>
            <p className="text-base md:text-sm text-[18px] font-[300] text-[#58585A] leading-none xl:text-[22px] md:text-[16px] text-gray-600 leading-relaxed">
              {currentData?.description}
            </p>
          </div>

          <button
          onClick={()=>{
              scrollToId("program-from");}}
              className="inline-flex items-center text-[18px] md:text-[15px] lg:text-[18px] 2xl:text-[24px] xl:h-[60px] cursor-pointer uppercase justify-center gap-2 md:gap-2 bg-[#0097DC] hover:bg-[#0097DC] hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1] text-white font-medium text-center leading-tight px-4 py-2 md:px-5 md:py-3 rounded-full transition md:w-fit w-full max-[767px]:min-h-[50px] max-[360px]:text-[14px]">            <img
              src={withCDN("/ticket.png")}
              alt="Ticket Icon"
              className="w-5 h-5 object-contain shrink-0"
            />
            {currentData.ctaButtonText}
          </button>
        </div>

        {/* RIGHT - Main Image and Thumbnails (Desktop only) */}
        <div className="hidden md:flex w-auto gap-2 md:w-[55%] lg:w-[60%] xl:w-[59%]">
          {/* MAIN IMAGE */}
          <div className="w-[340px] h-[269px] 2xl:w-[604px] 2xl:h-[464px] md:w-[310px] lg:w-[450px] lg:h-[324px] rounded-[32px] overflow-hidden bg-gray-200 flex-shrink-0 young-mind-image">
            <img
              src={mainImage}
              alt="Main content"
              className="w-full h-full object-cover cursor-pointer"
              onClick={() =>
                setLightboxIndex(Math.max(0, allImages.indexOf(mainImage)))
              }
            />
          </div>

          {/* THUMBNAILS */}
          <div className="flex w-auto flex-col gap-2 xl:gap-5 flex-shrink-0">
            {currentData?.allImages?.map((thumbnail, index) => {
              const isSelected = thumbnail === mainImage;
              return (
                <div
                  key={index}
                  className="w-[80px] h-[60px] lg:h-[75px] xl:w-[130px] xl:h-[100px] rounded-xl overflow-hidden relative cursor-pointer flex-shrink-0"
                  onClick={() => setMainImage(thumbnail)}
                >
                  <img
                    src={thumbnail}
                    alt={`Thumbnail ${index + 1}`}
                    className={`w-full h-full object-cover transition ${
                      isSelected
                        ? "brightness-75 scale-[1.02]"
                        : "brightness-100"
                    }`}
                  />

                  {/* ✅ Overlay */}
                  {isSelected && (
                    <div className="absolute inset-0 flex items-center justify-center bg-[#34343480]">
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <ImageLightbox
        images={allImages}
        index={lightboxIndex}
        onClose={() => setLightboxIndex(null)}
      />
    </section>
  );
}