"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { withCDN } from "@/src/lib/utils";
import PhotosCarousel from "./PhotosCarousel";
import { JoinFreeClassData } from "@/src/lib/types/home";
import { scrollToId } from "@/src/lib/utils/scrollToId";

export default function ClientJoinFreeClass({ data }: { data: JoinFreeClassData }) {
  const { title, subtitle, ctaText, photos, description } = data;
  const [scrollPosition, setScrollPosition] = useState(0);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);
  const scrollerRef = useRef<HTMLDivElement | null>(null);
  const [bgImage, setBgImage] = useState(
    withCDN("/join-free-class/join free class.png")
  );

  useEffect(() => {
    const updateBackground = () => {
      const width = window.innerWidth;

      if (width < 539) {
        setBgImage(withCDN("/join-free-class/mobile/join free class.svg"));
      } else if (width >= 540 && width < 1500) {
        setBgImage(withCDN("/join-free-class/tab/joinFreeClassTab.svg"));
      } else {
        setBgImage(withCDN("/join-free-class/join free class.png"));
      }
    };

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

  // Keep scroll state in sync
  const updateScrollState = useCallback(() => {
    const container = scrollerRef.current;
    if (!container) return;
    setScrollPosition(container.scrollLeft);
    setCanScrollLeft(container.scrollLeft > 0);
    setCanScrollRight(
      container.scrollLeft + container.clientWidth + 1 < container.scrollWidth
    );
  }, []);

  useEffect(() => {
    const c = scrollerRef.current;
    updateScrollState();
    if (!c) return;
    c.addEventListener("scroll", updateScrollState, { passive: true });
    window.addEventListener("resize", updateScrollState);
    return () => {
      c.removeEventListener("scroll", updateScrollState);
      window.removeEventListener("resize", updateScrollState);
    };
  }, [updateScrollState]);

  // Scroll one card at a time (card width + gap)
  const scrollCarousel = (direction: "left" | "right") => {
    const container = scrollerRef.current;
    if (!container) return;

    // Find the first carousel item to measure card width
    const firstItem = container.querySelector<HTMLElement>(
      "[data-carousel-item]"
    );
    if (!firstItem) {
      // fallback to a fraction of container width
      const fallback = Math.round(container.clientWidth * 0.8);
      container.scrollBy({
        left: direction === "left" ? -fallback : fallback,
        behavior: "smooth",
      });
      return;
    }

    // Width of the card (includes padding/border)
    const cardRect = firstItem.getBoundingClientRect();
    const cardWidth = Math.round(cardRect.width);

    // Read gap from the flex container computed style. Fallback to 0.
    const gapVal =
      getComputedStyle(container).gap ||
      (getComputedStyle(container).columnGap ?? "0px");
    const gap = Math.round(parseFloat(gapVal)) || 0;

    const step = cardWidth + gap;

    container.scrollBy({
      left: direction === "left" ? -step : step,
      behavior: "smooth",
    });

    // Note: scrollLeft will update asynchronously; rely on scroll event to sync state
  };

  return (
    <section
      className="
        relative max-w-full h-fit sm:h-[1000px]
        md:h-[800px] lg:h-[800px] xl:h-[880px] 2xl:h-[980px]
        overflow-visible z-[40]
        py-10 max-[767px]:pb-0
        sm:bg-transparent sm:py-16 xl:mt-[-320px] lg:mt-[-380px] md:mt-[-680px] mt-[-550px] sm:mt-[-530px] z-99
  "
    >
      {/* ✅ Responsive Background Layer (desktop / tablet / mobile) */}
      <div
        className="
      sm:absolute inset-0 w-full h-full
      -z-10 pointer-events-none select-none overflow-hidden
    "
      >
        {/* Desktop */}
        <div className="hidden lg:block">
          <Image
            src={withCDN("/join_free_class.png")}
            alt="Join Free Class background (desktop)"
            fill
            className="object-cover object-top"
            loading="lazy"
          />
        </div>

        {/* Tablet */}
        <div className="hidden md:block lg:hidden">
          <Image
            src={withCDN("/join-free-class/join free classTab.svg")}
            alt="Join Free Class background (tablet)"
            fill
            className="object-cover object-top"
            loading="lazy"
          />
        </div>

        {/* Mobile */}
        <div className="relative block md:hidden w-full h-[400px] z-10">
          <Image
            src={withCDN("/join-free-class/joinMobile.svg")}
            alt="Join Free Class background (mobile)"
            fill
            className="object-cover object-top"
            loading="lazy"
          />
        </div>
      </div>

      {/* ✅ Your original content remains unchanged */}
      <div className="relative sm:mt-82 md:mt-1 px-4 md:px-6 lg:px-14 xl:px-0 overflow-visible sm:z-70  max-w-[1300px] !mx-auto w-full  py-1 md:ml-[12px]">
        {/* Headline + CTA */}
        <div className="gap-8 sm:gap-4  items-center">
          <div className="relative sm:mt-1  overflow-visible sm:z-70  max-w-full py-1 ">
            {" "}
            <div className="flex flex-col gap-0 pt-10 lg:pt-2 xl:pt-14 md:pt-32 2xl:pt-30">
              <h1 className="text-[30px] sm:ml-0 md:text-[30px] 2xl:text-[50px] lg:text-[50px] xl:text-[50px] font-bold uppercase text-[#0097DC] leading-tight max-w-full md:max-w-[400px] lg:max-w-[600px] xl:max-w-[750px] 2xl:max-w-[700px] break-words hh">
                {title}
              </h1>

              <p
                className="
               text-xl text-[20px] lg:text-[24px] xl:text-[40px] 2xl:text-[40px] md:text-[20px]
                font-light text-[#58585A] 
               max-w-[300px] md:max-w-[300px] lg:max-w-[400px] xl:max-w-[530px] 2xl:max-w-[600px]
                sm:px-0 sm:text-left ml-0 sm:ml-0 mb-3 subtitle-index
              "
                dangerouslySetInnerHTML={{ __html: subtitle }}
              />
            </div>
            <button
              onClick={() => {
                scrollToId("home-from");
              }}
              className="
              flex items-center justify-center gap-1 sm:gap-3
              w-fit sm:w-fit xl:h-[60px]
              px-5 sm:px-6 md:px-8
              py-1 sm:py-3 md:py-2
              ml-2 sm:ml-0 mt-[30px]
              text-xs sm:text-base md:text-lg
              bg-[#0097DC] text-white rounded-full
              hover:opacity-100 transition-opacity shadow-md hover:shadow-lg
              cursor-pointer text-center leading-tight max-[480px]:w-full max-[480px]:ml-0 max-[767px]:min-h-[45px]
              hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1] active:shadow-[10px_14px_14px_#0000000D]
            "
            >
              <img
                src={withCDN("/ticket.png")}
                alt="Ticket Icon"
                className="w-5 h-5 object-contain shrink-0"
              />
              <span className="text-[18px] md:text-[18px] lg:text-[24px] xl:text-[24px] 2xl:text-[24px] font-regular uppercase py-1 md:py-0 max-[360px]:text-[15px]">
                {ctaText}
              </span>
            </button>
          </div>
        </div>

        {/* Photos carousel */}
        <div className="mt-10 md:mt-26 lg:mt-18 xl:mt-25 2xl:mt-31 -mr-0 md:-mr-8 lg:-mr-16 xl:mr-0 2xl:pt-18 xl:pt-18 ">
          <p
            className="text-[16px] md:text-[14px] lg:text-[20px] xl:text-[20px] 2xl:text-[20px] font-bold text-[#0097DC] uppercase tracking-wide"
            dangerouslySetInnerHTML={{ __html: description }}
          />

          {/* Full-bleed slider */}
          {/* Full-bleed slider */}

          {/* Single Arrow (left position but acts as Next) */}
          <PhotosCarousel photos={photos} />


        </div>
      </div>
    </section>
  );
}
