"use client";

import Image from "next/image";
import { useEffect, useState, useRef } from "react";
import { withCDN } from "@/src/lib/utils";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";

import { WhyYoungEngineersData } from "@/src/lib/types/home";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
} from "../../ui/carousel";
import type { CarouselApi } from "../../ui/carousel";

export default function ClientWhyYoungEngineers({
  data,
}: {
  data: WhyYoungEngineersData;
}) {
  const {
    mainHeading = "Why Young Engineers",
    sliders = [],
    ctaButtonText = "Discover Programs",
  } = data || {};

  // Defaults
  const DEFAULT_CTA_TEXT = "Discover Programs";
  const DEFAULT_CTA_LINK = "/programs";
  const DEFAULT_SLIDER_IMAGE =
    "https://yefranchisees.b-cdn.net/frontend/pct-8.png";

  // Ensure sliders is an array
  const slidersArray = Array.isArray(sliders) ? sliders : [];

  const [activeIndex, setActiveIndex] = useState(0);
  const [carouselApi, setCarouselApi] = useState<CarouselApi>();

  const featureRefs = useRef<(HTMLDivElement | null)[]>([]);
  const containerRef = useRef<HTMLDivElement | null>(null);

  // Extract features
  const features = slidersArray.map((slide) => slide.sliderHeading);

  /* Keep activeIndex synced with swipe */

  useEffect(() => {
    if (!carouselApi) return;

    const handleSelect = () => {
      const selectedIndex = carouselApi.selectedScrollSnap();

      setActiveIndex(selectedIndex);
    };

    // Set initial index
    handleSelect();

    carouselApi.on("select", handleSelect);

    return () => {
      carouselApi.off("select", handleSelect);
    };
  }, [carouselApi]);

  /*Scroll active feature into center view*/

  useEffect(() => {
    const activeElement = featureRefs.current[activeIndex];
    const container = containerRef.current;

    if (activeElement && container) {
      const elementLeft = activeElement.offsetLeft;
      const elementWidth = activeElement.offsetWidth;
      const containerWidth = container.offsetWidth;

      const scrollLeft =
        elementLeft -
        containerWidth / 2 +
        elementWidth / 2;

      container.scrollTo({
        left: scrollLeft,
        behavior: "smooth",
      });
    }
  }, [activeIndex]);

  /* Navigation arrows */

  const goNext = () => {
    if (!slidersArray.length) return;

    if (activeIndex < slidersArray.length - 1) {
      carouselApi?.scrollNext();
    }
  };

  const goPrev = () => {
    if (!slidersArray.length) return;

    if (activeIndex > 0) {
      carouselApi?.scrollPrev();
    }
  };

  /* Change slide when feature button is clicked */
  const handleFeatureClick = (index: number) => {
    setActiveIndex(index);
    carouselApi?.scrollTo(index);
  };

  
  return (
    <section className="relative w-full overflow-hidden py-24 z-20 mt-[-128px] min-w-[1800px]:mt-[-146px] inspire-young">
      {/* CURVED BACKGROUND IMAGE*/}
      <div className="absolute inset-0 w-full h-full md:h-[125%] lg:h-full -z-10">

        {/* Desktop */}
        <Image
          src={withCDN("/Why_YE.png")}
          alt="Curved background"
          width={1920}
          height={1080}
          className="w-full h-full object-cover object-top hidden lg:block"
          priority
        />

        {/* Tablet */}
        <Image
          src={withCDN("/Why_YE.png")}
          alt="Curved background for tablet"
          width={1920}
          height={1080}
          className="
            w-full h-full
            object-cover object-top
            hidden md:block lg:hidden
            h-[125%]
          "
          priority
        />

        {/* Mobile */}
        <Image
          src={withCDN("/home/why%20ye%20(1).png")}
          alt="Curved background for mobile"
          width={1920}
          height={1080}
          className=" w-full h-full object-cover object-top block md:hidden "
          priority
        />

      </div>

      {/*CONTENT WRAPPER*/}

      <div className=" max-w-[1300px] mx-auto w-full relative my-13 min-h-[260px] md:min-h-[520px] lg:min-h-[720px] xl:min-h-[690px]
          gap-2.5 px-4 md:px-10 lg:px-18 xl:px-0 xl:mt-16 young-content-wrapper"
      >

        {/* TITLE*/}
        <h2 className="  text-[#0097DC] leading-tight text-[30px] 2xl:text-[50px] xl:text-[50px] md:text-[30px] font-bold uppercase tracking-wide mb-2.5 2xl:mb-7.5 mt-[-20px] " >
          {mainHeading}
        </h2>

        {/* FEATURE NAVIGATION */}

        <div
          ref={containerRef}
          className=" relative flex flex-nowrap items-start justify-start overflow-x-auto no-scrollbar gap-2 md:gap-1 lg:gap-2 xl:gap-2 text-[10px]
            2xl:text-[15px] md:text-[10px] xl:text-[15px] lg:text-[15px] font-normal uppercase mb-6 2xl:mb-7.5 [-webkit-overflow-scrolling:touch] "
          aria-label="Why Young Engineers features"
          >
          {features.map((text, index) => (
            <div
              key={index}
              onClick={() => handleFeatureClick(index)}
              ref={(el) => {
                featureRefs.current[index] = el;
              }}
              className="flex items-stretch first:ml-0"
            >
              <div className=" min-w-[90px] md:min-w-[90px] xl:min-w-[160px] lg:min-w-[180px] w-full flex items-stretch ">
                <span className={` w-full h-full flex items-center bg-[fff] justify-center transition-colors duration-500 leading-snug  whitespace-normal cursor-pointer text-center border
                    border-[#0097DC]  rounded-[7px] px-[10px] md:px-[22px] lg:px-[10px] py-[10px]
                    ${
                      index === activeIndex
                        ? "text-[#0097DC]"
                        : "text-[#58585A] "
                    }
                  `}
                >
                  {text}
                </span>
              </div>
            </div>
          ))}
        </div>

        {/* CAROUSEL */}
        <Carousel
          className="w-full"
          setApi={setCarouselApi}
          opts={{
            loop: false,
            watchDrag: true,
          }}
        >
          <CarouselContent>

            {slidersArray.map((slide: any, index: number) => {

              // CTA text
              const slideCtaText =
                (slide.ctaButtonText &&
                  slide.ctaButtonText.trim()) ||
                (ctaButtonText &&
                  ctaButtonText.trim()) ||
                DEFAULT_CTA_TEXT;

              // CTA link
              const slideCtaLink =
                (slide.ctaButtonLink &&
                  slide.ctaButtonLink.trim()) ||
                DEFAULT_CTA_LINK;

              // Image
              const slideImage =
                (slide.image &&
                  slide.image.trim()) ||
                DEFAULT_SLIDER_IMAGE;

              return (

                <CarouselItem
                  key={index}
                  className="transition-opacity duration-700"
                >

                  <div className=" grid grid-cols-1 md:grid-cols-[auto_1fr] items-center gap-2 xl:gap-10 text-center  md:text-left justify-items-center md:justify-items-start">

                    {/*IMAGE*/}
                    <div className=" relative w-[90%] md:w-[300px] lg:w-[340px] xl:w-[525px]  h-[270px] md:h-[300px] lg:h-[400px] flex-shrink-0">
                      <Image
                        src={slideImage}
                        alt={slide.title || "Why Young Engineers"}
                        fill
                        className="object-contain"
                        priority={index === 0}
                      />
                    </div>

                    {/* TEXT CONTENT */}

                    <div className="space-y-2 sm:space-y-2 md:space-y-3 lg:space-y-3 xl:w-[100%] md:text-center corousel-text">
                      <h3  className=" text-[#58585A] text-base text-[18px]  md:text-[20px] lg:text-[25px] xl:text-[25px] 2xl:text-[25px] font-bold
                          uppercase tracking-wide  lg:mt-2 text-left px-2 md:text-center" >
                        {(() => {
                          const [head, ...rest] =
                            (slide.title || "").split("—");

                          const tail =
                            rest.join("—").trim();

                          return (
                            <>
                              {head.trim()}
                              {tail && (
                                <>
                                  {" "}—{" "}

                                  <span className="text-[#0097DC]">
                                    {tail}
                                  </span>
                                </>
                              )}
                            </>
                          );

                        })()}
                      </h3>

                      {/* DESCRIPTION */}
                      <p className=" text-[#58585A] text-[18px] md:text-[16px] lg:text-[22px] xl:text-[22px] 2xl:text-[22px] leading-relaxed
                          break-words text-left px-2 font-light md:text-center">
                        {slide.description}
                      </p>

                      {/* CTA */}
                      <LanguageAwareLink
                        href={slideCtaLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        className=" bg-[#0097DC] text-white  hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1]
                        active:shadow-[10px_14px_14px_#0000000D] px-4 sm:px-5 md:px-6 mt-5 py-[10px]  rounded-full text-sm sm:text-base
                        uppercase font-normal inline-flex items-center justify-center gap-2  sm:gap-3 min-w-[264px] h-[43px] 2xl:min-w-[355px]
                        2xl:h-[60px] lg:min-w-[355px] lg:h-[60px] xl:min-w-[355px] xl:h-[60px] max-[480px]:w-full max-[480px]:mt-[20px] md:mx-auto" >

                        <Image
                          src={withCDN("/gear.png")}
                          alt="Gear icon"
                          width={20}
                          height={20}
                          className=" w-5.5 h-5.5 2xl:h-8 2xl:w-8 md:w-6 md:h-6  flex-shrink-0"
                        />

                        <span className="  text-[18px] md:text-[18px] lg:text-[24px] xl:text-[24px] 2xl:text-[24px] cursor-pointer whitespace-nowrap max-[360px]:text-[15px]">
                          {slideCtaText}
                        </span>
                      </LanguageAwareLink>

                      {/* NAVIGATION ARROWS */}
                       <div className="md:hidden flex justify-center items-end gap-2 w-[100%] md:w-[55%] lg:w-[55%] md:ml-auto mt-3 md:mt-0 md:mb-10 nav-view" >

                         {/* PREVIOUS */}
                         <button
                           onClick={goPrev}
                           disabled={activeIndex === 0}
                           className={` w-10 h-10 flex items-center justify-center transition lg:ml-[-25px]
                             ${
                               activeIndex === 0
                                 ? "opacity-40 cursor-not-allowed"
                                 : "cursor-pointer"
                             }
                           `}
                           aria-label="Previous slide"
                         >
                           <Image
                             src={withCDN("/arrow-left.svg")}
                             alt="Previous"
                             width={28}
                             height={28}
                           />
                         </button>

                         {/* NEXT */}
                         <button
                           onClick={goNext}
                           disabled={activeIndex === slidersArray.length - 1}
                           className={` w-10 h-10 flex items-center justify-center transition
                             ${
                               activeIndex === slidersArray.length - 1
                                 ? "opacity-40 cursor-not-allowed"
                                 : "cursor-pointer"
                             }
                           `}
                           aria-label="Next slide"
                         >
                           <Image
                             src={withCDN("/arrow-right.svg")}
                             alt="Next"
                             width={28}
                             height={28}
                           />
                         </button>

                       </div>
                    </div>
                  </div>
                </CarouselItem>
              );
            })}

          </CarouselContent>
          {/* NAVIGATION ARROWS */}
                       <div className="hidden md:flex justify-center items-end gap-2 w-[100%] md:w-[55%] lg:w-[55%] md:ml-auto mt-3 md:mt-0 md:mb-10 nav-view" >

                         {/* PREVIOUS */}
                         <button
                           onClick={goPrev}
                           disabled={activeIndex === 0}
                           className={` w-10 h-10 flex items-center justify-center transition lg:ml-[-25px]
                             ${
                               activeIndex === 0
                                 ? "opacity-40 cursor-not-allowed"
                                 : "cursor-pointer"
                             }
                           `}
                           aria-label="Previous slide"
                         >
                           <Image
                             src={withCDN("/arrow-left.svg")}
                             alt="Previous"
                             width={28}
                             height={28}
                           />
                         </button>

                         {/* NEXT */}
                         <button
                           onClick={goNext}
                           disabled={activeIndex === slidersArray.length - 1}
                           className={` w-10 h-10 flex items-center justify-center transition
                             ${
                               activeIndex === slidersArray.length - 1
                                 ? "opacity-40 cursor-not-allowed"
                                 : "cursor-pointer"
                             }
                           `}
                           aria-label="Next slide"
                         >
                           <Image
                             src={withCDN("/arrow-right.svg")}
                             alt="Next"
                             width={28}
                             height={28}
                           />
                         </button>

                       </div>
        </Carousel>

      </div>
    </section>
  );
}