"use client";

import { useMemo, useState, useEffect, useRef } from "react";
import Image from "next/image";
import { ProcessedProgram } from "@/src/lib/types/programs";
import ProgramCard from "../ProgramCard";
import { Button } from "@/src/components/ui/button";
import { withCDN } from "@/src/lib/utils";
import SwiperPrograms from "./SwiperPrograms";
import { ProgramsSectionData } from "@/src/lib/types/home";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";


export default function ClientPrograms({
  programs,
  initialAge = 11,
  sectionData,
  onClick,
}: {
  programs: ProcessedProgram[];
  initialAge?: number;
  sectionData: ProgramsSectionData;
  onClick?: () => void;
}) {
  const { heading, ageRangeText, ctaButtonText } = sectionData;  const MIN_AGE = 4;
  const MAX_AGE = 18;
  const [age, setAge] = useState(initialAge || 11);
  const [sliderHeight, setSliderHeight] = useState("10px");
  const [hasInteracted, setHasInteracted] = useState(false);

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

  // slider width + thumb radius for bubble alignment
  const sliderRef = useRef<HTMLInputElement | null>(null);
  const [sliderWidth, setSliderWidth] = useState(0);
  const THUMB_RADIUS = 18; // px (half of thumb size including border)

  // responsive slider height
  useEffect(() => {
    const updateSliderHeight = () => {
      if (window.innerWidth < 640) setSliderHeight("6px");
      else if (window.innerWidth < 834) setSliderHeight("8px");
      else setSliderHeight("10px");
    };

    updateSliderHeight();
    window.addEventListener("resize", updateSliderHeight);

    return () => window.removeEventListener("resize", updateSliderHeight);
  }, []);

  // measure slider width for precise bubble positioning
  useEffect(() => {
    const updateWidth = () => {
      if (sliderRef.current) {
        setSliderWidth(sliderRef.current.getBoundingClientRect().width);
      }
    };

    updateWidth();
    window.addEventListener("resize", updateWidth);
    return () => window.removeEventListener("resize", updateWidth);
  }, []);

  // which program is active for current age
  // An empty result is meaningful — it means no programme covers this age — so
  // it is passed through to SwiperPrograms as-is rather than coerced.
  const activeIndexes = useMemo(
    () =>
      programs
        .map((p, index) => (age >= p.minAge && age <= p.maxAge ? index : -1))
        .filter((index) => index !== -1),
    [age, programs]
  );

  // On first load: show first card half-cut (scroll a bit to the right)
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handle = requestAnimationFrame(() => {
      const peekPx = container.offsetWidth * 0.2; // ~20% of width
      container.scrollTo({
        left: peekPx,
        behavior: "auto",
      });
    });

    return () => cancelAnimationFrame(handle);
  }, []);

  // After interaction: center active card
  useEffect(() => {
    if (!hasInteracted) return;
    if (!activeIndexes.length) return;

    const container = containerRef.current;
    const firstActiveIndex = activeIndexes[0];
    const card = cardRefs.current[firstActiveIndex];

    if (!container || !card) return;

    const containerRect = container.getBoundingClientRect();
    const cardRect = card.getBoundingClientRect();

    const offset =
      cardRect.left -
      containerRect.left -
      (containerRect.width / 2 - cardRect.width / 2);

    container.scrollBy({
      left: offset,
      behavior: "smooth",
    });
  }, [activeIndexes, hasInteracted]);

  // progress 0 → 1
  const progress = (age - MIN_AGE) / (MAX_AGE - MIN_AGE);
  // bubble center in px, clamped to slider width
  const bubbleLeftPx =
    sliderWidth > 0
      ? THUMB_RADIUS + progress * (sliderWidth - 2 * THUMB_RADIUS)
      : 0;

  return (
    <section
      className="
        relative w-full z-30
        overflow-x-hidden overflow-y-visible
        mt-[-130px] md:mt-[-180px] xl:mt-[-300px] lg:mt-[-270px] 2xl:mt-[-220px]
        min-h-[1000px] md:min-h-[1100px] lg:min-h-[1360px]
        px-4 md:px-10 lg:px-18 xl:px-34 program-block
      "
    >
      {/* Background Images */}
      <div className="absolute inset-0 w-full h-full -z-10 hidden lg:block">
        <Image
          src={"https://yefranchisees.b-cdn.net/frontend/programs-around-you.svg"}
          alt="Programs Around You background (desktop)"
          fill
          className="object-cover object-top"
          priority
        />
      </div>

      <div className="absolute inset-0 w-full h-full -z-10 hidden md:block lg:hidden">
        <Image
          src={"https://yefranchisees.b-cdn.net/frontend/programsAroundYouTab.svg"}
          alt="Programs Around You background (tablet)"
          fill
          className="object-cover object-top"
          priority
        />
      </div>

      <div className="absolute inset-0 w-full h-full -z-10 md:hidden">
        <Image
          src={"https://yefranchisees.b-cdn.net/frontend/programsAroundYouMobile.svg"}
          alt="Programs Around You background (mobile)"
          fill
          className="object-cover object-top"
          priority
        />
      </div>

      {/* Robot */}
      <div
        className="
          absolute top-[0rem] md:top-[40px] lg:top-[0rem] xl:top-[2.5rem] 
          right-[-4rem] sm:right-0 md:right-[-8rem] lg:right-[-9rem] xl:right-[-4rem]
          block 
          z-20 overflow-hidden
        "
      >
        <img
          src={withCDN("/crawler-crane.png")}
          alt="Robot"
          className="object-contain w-[20rem] sm:w-[36rem] md:w-[39rem] lg:w-[45rem] xl:w-[50rem] h-auto"
        />
      </div>

      {/* Main Content */}
      <div className="relative max-w-[1300px] mx-auto w-full z-21 ">
        {/* Header + Age Slider */}
        <div className="mb-[44px] md:mb-0 pt-[30px] lg:pt-[50px] lg:mb-[60px]">
          <div className="text-left mb-15 sm:mb-12 md:mb-16 max-w-2xl mt-30 lg:mt-28 xl:mt-30 ">
            <h2 className="uppercase font-bold text-white leading-none text-[40px] md:text-[50px] xl:text-[80px] 2xl:text-[80px] lg:text-[80px] md:w-[60%] lg:w-full program-txt">
               {heading}
            </h2>
          </div>

          {/* Age Slider */}
          <div className="w-full max-w-2xl pt-10 mb-4 sm:mb-14 md:mb-10 lg:mb-5 flex flex-col items-left">
            <div className="relative w-[100%] sm:w-[50%] md:w-[44%] lg:w-[90%] flex flex-col ">
              <input
                ref={sliderRef}
                type="range"
                min={MIN_AGE}
                max={MAX_AGE}
                value={age}
                onChange={(e) => {
                  const val = Number(e.target.value);
                  setAge(val);
                  setHasInteracted(true);
                }}
                className="slider-progress-bar"
                style={{
                  transition: "background 0.3s ease",
                  height: sliderHeight,
                  background: "#95C11F",
                }}
              />

              {/* Bubble aligned with thumb, including at min/max */}
              <div
                className="absolute -top-[68px] flex flex-col items-center"
                style={{
                  left: `${bubbleLeftPx}px`,
                  transform: "translateX(-50%)",
                  transition: "left 0.2s ease",
                }}
              >
                <div className="relative bg-white text-[#95C11F] text-[32px] 2xl:text-[36px] font-normal px-4 py-2 rounded-md shadow-md leading-none">
                  {age}
                  <div className="absolute left-1/2 -bottom-2 w-0 h-0 -translate-x-1/2 border-l-[8px] border-r-[8px] border-t-[10px] border-l-transparent border-r-transparent border-t-white" />
                </div>
              </div>

              <div className="flex justify-between w-full text-white mt-4 sm:mt-5 md:mt-6 text-[20px] sm:text-base md:text-[20px] xl:text-[26px]">
                <span>{MIN_AGE}</span>
                <span className="text-center text-[20px] sm:text-sm md:text-[20px] xl:text-[26px]">
                  {ageRangeText}
                </span>
                <span>{MAX_AGE}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Programs Cards */}
        {/* Only show skeleton for cards - background/heading/slider are already loaded */}
        <SwiperPrograms programs={programs} activeIndexes={activeIndexes} />


        {/* CTA */}
        <div className="flex justify-center mt-8 sm:mt-16 md:mt-12">
           <LanguageAwareLink
             href={'/programs'}
             onClick={onClick}
             className="
              bg-white hover:bg-white text-[#0097DC]
              px-5 sm:px-7 md:px-8
              py-[10px] md:py-3 lg:py-3
              rounded-full
              text-sm sm:text-base md:text-lg
              uppercase font-semibold
              flex items-center justify-center gap-2 sm:gap-3 max-[480px]:w-full
              hover:shadow-[10px_14px_14px_#0000000D] 
              active:shadow-[10px_14px_14px_#0000000D] active:text-[#0084C1]
              all-program-btn
            "
          >
            <Image
              src={withCDN("/gear-blue.png")}
              alt="Gear icon"
              width={24}
              height={24}
              className="w-[23px] h-[23px] lg:w-[33px] lg:h-[33px]"
            />
            <span className="text-[18px] md:text-[24px] font-[400] text-[#0097DC] lg:text-[24px] xl:text-[24px] 2xl:text-[24px] cursor-pointer max-[360px]:text-[15px]">
            {ctaButtonText}
            </span>
          </LanguageAwareLink>
        </div>
      </div>
    </section>
  );
}
