"use client";

import Image from "next/image";
import ProgramsMobileSlider from "./ProgramsMobileSlider";
import { detailHref } from "@/src/lib/utils/detailHref";
import { withCDN } from "@/src/lib/utils";
import { useState, useEffect, useRef } from "react";
import type { ProgramsPageBanner } from "@/src/lib/services/programsPageService";
import Breadcrumbs from "../layout/Breadcrumbs";
import BackButton from "../layout/BackButton";
import ClickableImage from "../ui/ClickableImage";
import { scrollToId } from "@/src/lib/utils/scrollToId";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { getProgramsAction } from "@/src/lib/actions/programsAction";
import { useLocalizedNavigation } from "@/src/lib/hooks/useLocalizedNavigation";

const FALLBACK_PROGRAMS = [
  {
    name: "ALGO BUDDY",
    age: "4–6",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_algo_buddy.svg"),
    slug: "ALGO_BUDDY",
  },
  {
    name: "BIG BUILDERS",
    age: "4–6",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_big_builders.svg"),
    slug: "BIG_BUILDERS",
  },
  {
    name: "BRICKS CHALLENGE",
    age: "6–10",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_bricks_chalenge.svg"),
    slug: "BRICKS_CHALLENGE",
  },
  {
    name: "ALGO PLAY",
    age: "6–10",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_algo_play.svg"),
    slug: "ALGOPLAY",
  },
  {
    name: "GALILEO TECHNIC",
    age: "7–10",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_galileo_technic.svg"),
    slug: "GALILEO_TECHNIC",
  },
  {
    name: "ROBO TOYS",
    age: "9–12",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_robo_toys.svg"),
    slug: "ROBO_TOYS",
  },
  {
    name: "SMARTIVO",
    age: "10–12",
    label: "Y.O. PROGRAM",
    icon: withCDN("/program-logo/logo_smartivo.svg"),
    slug: "SMARTIVO",
  },
  {
    name: "AlgoC",
    age: "13–18",
    label: "Y.O. program",
    icon: withCDN("/program-logo/logo_algo_c.svg"),
    slug: "ALGOC",
  },
];

/**
 * Slug is now fixed and simple.
 */
function extractBaseSlug(slug: string): string {
  if (!slug) return "";
  return slug;
}

function getIconBySlug(slug: string): string {
  const baseSlug = extractBaseSlug(slug);
  const matched = FALLBACK_PROGRAMS.find((p) => extractBaseSlug(p.slug) === baseSlug);
  return matched?.icon || withCDN("/programs-page/AllPrograms/logo.svg");
}

const defaultAdvantages = [
  {
    icon: withCDN("/programs-page/programs-advantage.svg"),
    value: "60+",
    title: "Countries Presence",
    description: "Countries Presence",
  },
  {
    icon: withCDN("/programs-page/programs-advantage-2.svg"),
    value: "500+",
    title: "Global Partners",
    description: "Global Partners",
  },
  {
    icon: withCDN("/programs-page/programs-advantage-3.svg"),
    value: "150+",
    title: "Engaging Lessons",
    description: "Engaging Lessons",
  },
  {
    icon: withCDN("/programs-page/programs-advantage-4.svg"),
    value: "Recognition",
    title: "Recognition",
    description: "Officially Recognized <br/>By EU & Harvard",
  },
];

/**
 * Parse stats from API banner data (JSON stringified array)
 */
function parseStatistics(statsJson?: string) {
  if (!statsJson) return defaultAdvantages;
  try {
    const stats = JSON.parse(statsJson);
    return stats.map((stat: { number: string; label: string }, index: number) => ({
      ...defaultAdvantages[index],
      value: stat.number,
      description: stat.label,
    }));
  } catch (error) {
    console.warn("[Enrichment] Failed to parse stats:", error);
    return defaultAdvantages;
  }
}

type StatProps = {
  icon: string;
  value: string;
  label: string;
};

function Stat({ icon, value, label }: StatProps) {
  return (
    <div className="flex w-[120px] md:w-[130px] lg:w-[150px] items-start gap-2">
      <div className="flex h-7 w-7 md:h-8 md:w-8 items-center justify-center rounded-full border border-[#0070c9]/40 shrink-0">
        <span className="text-base md:text-lg">{icon}</span>
      </div>

      <div className="leading-tight break-words whitespace-normal">
        <p className="text-[11px] md:text-[16px] lg:text-[20px] xl:[24px] font-bold text-slate-900">
          {value}
        </p>
        <p className="text-[8px] md:text-[9px] uppercase tracking-wide text-slate-600 break-words leading-tight">
          {label}
        </p>
      </div>
    </div>
  );
}

import { usePrograms } from "@/src/lib/context/ProgramsContext";

interface EnrichmentProps {
  bannerData?: ProgramsPageBanner;
  generalSettings?: any;
  programs?: any[];
  isLoading?: boolean;
}

export default function EnrichmentProgramsSection({ bannerData, generalSettings, programs = [], isLoading = false }: EnrichmentProps) {
  const globalPrograms = usePrograms().programs;
  
  const [selected, setSelected] = useState<string | null>(null);
  const [dynamicPrograms, setDynamicPrograms] = useState<typeof FALLBACK_PROGRAMS>([]);
  const { currentLanguage } = useLanguage();
  const router = useLocalizedNavigation();

  // Sync dynamicPrograms with incoming programs from parent or global context
  useEffect(() => {
    const listToRender = programs.length > 0 ? programs : globalPrograms;
    if (Array.isArray(listToRender) && listToRender.length > 0) {
      // ensure unique programs based on mapping slugs or titles
      const uniqueProgramsMap = new Map();
      
      listToRender.forEach((p: any) => {
        const baseSlug = extractBaseSlug(p.slug);
        if (!uniqueProgramsMap.has(baseSlug)) {
          uniqueProgramsMap.set(baseSlug, {
            id: p.id,
            name: p.title || p.name,
            age: p.age_range || "4-6",
            label: p.created_for || "Y.O. PROGRAM",
            icon: p.program_icon ? withCDN(p.program_icon) : getIconBySlug(p.slug),
            slug: p.slug
          });
        }
      });
      
      setDynamicPrograms(Array.from(uniqueProgramsMap.values()));
    } else if (!isLoading) {
      // Only set to fallback once we're sure no data is coming
      setDynamicPrograms(FALLBACK_PROGRAMS);
    }
  }, [programs, isLoading]);

  
  // Parse stats from API data
  const advantages = parseStatistics(bannerData?.stats);
  
  // Get heading and CTA from API
  const heading = bannerData?.heading || "ENRICHMENT PROGRAMS";
  const subHeading = bannerData?.subHeading || "Engaging STEM with robotics, coding and hands-on projects.";
  const ctaText = bannerData?.ctaText || "DISCOVER PROGRAMS";

  const handleProgramClick = (program: any) => {
    setSelected(program.name);
    // Navigate using the program ID
    if (program.id) {
      router.push(detailHref("/programs", program.id, program.slug));
    } else {
      // Fallback to slug if ID is missing for some reason
      router.push(`/programs/${program.slug}`);
    }
  };

  return (
    <>
    <section id="program-all"
      className="relative w-full overflow-hidden py-10 md:py-16 lg:py-25
      min-h-[1050px]    
      md:min-h-[700px]  
      lg:min-h-[1000px]
      xl:min-h-[1020px]
       px-4 md:px-8 lg:px-18 xl:px-34
      "
    >
      {/* Background Images - Mobile and Desktop */}
      <div className="absolute inset-0 w-full h-full -z-10">
        {/* Mobile Background */}
        <div
          className="block md:hidden w-full h-full"
          style={{
            backgroundImage: `url('https://yefranchisees.b-cdn.net/frontend/enrichmentMobile.png')`,
            backgroundSize: "cover",
            backgroundRepeat: "repeat",
            backgroundPosition: "center",
          }}
        />
        {/* Desktop Background */}
        <div
          className="hidden md:block w-full h-full"
          style={{
            backgroundImage: `url('https://yefranchisees.b-cdn.net/frontend/enrichmentDesktop.png')`,
            backgroundSize: "cover",
            backgroundRepeat: "repeat",
            backgroundPosition: "start", 
          }}
        />
      </div>
      {/* blue overlay */}
      <div className="pointer-events-none absolute inset-0 " />
      <div className=" relative z-10 mx-auto flex hidden md:flex justify-center md:py-[24px] lg:py-2 flex-col">
      <BackButton className="mb-4" />
      <Breadcrumbs />

        {/* CARD */}
       <div className="max-w-[1300px] mx-auto flex w-full flex-col lg:gap-10 gap-5 rounded-[28px] bg-white lg:pl-[50px] lg:pr-[30px] lg:pt-[30px] lg:pb-[43px] md:pl-[20px] md:pr-[18px] md:pt-[20px] md:pb-[22px] shadow-xl mt-[20px] lg:mt-[30px]">          {/* TOP ROW */}
          <div className="flex flex-col gap-3.5 xl:gap-4 md:flex-row lg:items-stretch">
            {/* LEFT SIDE */}
            <div className="flex-1">
              <h1 className="text-3xl md:text-[28px] xl:text-[48px] max-[1600px]:text-[50px] font-bold text-[#0097DC] leading-tight">
                {heading}
              </h1>

              <p className="  text-[14px] md:text-[14px] xl:text-[18px] font-light lg:pt-2 text-[#58585A]">
                {subHeading}
              </p>

              {/* GRID */}

              <div className="mt-2 lg:mt-3 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 md:grid-cols-4 gap-[5px] md:gap-[5px] lg:gap-[10px] xl:!gap-y-5">
                {isLoading ? (
                  Array.from({ length: 8 }).map((_, i) => (
                    <div
                      key={i}
                      className="flex flex-col pb-[8px] items-center rounded-[20px] bg-gray-50/80 animate-pulse text-center shadow-[8px_9px_12px_#00000010]"
                    >
                      <div className="h-12 md:h-[44px] w-[88px] lg:w-[100px] xl:w-[120px] xl:h-[70px] lg:w-10 bg-gray-200 mt-2 rounded-[12px]"></div>
                      <div className="mt-2 h-4 w-12 bg-gray-200 rounded-md"></div>
                      <div className="mt-1 mb-1 h-2.5 w-20 bg-gray-200 rounded-md"></div>
                    </div>
                  ))
                ) : (
                  dynamicPrograms.map((program) => (
                    <div
                      key={program.name}
                      onClick={() => handleProgramClick(program)}
                      className={`
                      flex flex-col pb-2 lg:pb-3 items-center rounded-2xl bg-white text-center shadow-[10px_10px_14px_#0000000D] cursor-pointer transition-all hover:!shadow-[10px_10px_14px_rgba(0,0,0,0.15)] hover:scale-[1.02] icon-program
                      ${selected === program.name ? "ring-2 ring-[#0070c9]" : ""}
                    `}
                    >
                      <div className="relative h-12 md:h-14 lg:h-22 w-full px-2 mt-2">
                        <Image
                          src={program.icon}
                          alt={program.name}
                          fill
                          className="object-cover"
                        />
                      </div>

                      <p className="-mt-2 text-[11px] md:text-[14px] lg:text-[18px] xl:text-[22px] font-extrabold text-[#58585A]">
                        {program.age}
                      </p>
                    </div>
                  ))
                )}
              </div>
            </div>

            {/* RIGHT SIDE IMAGE */}
            <div className="w-full md:w-[45%] flex justify-center md:justify-end">
              <div
                className="
                  relative w-[350px] rounded-[22px] overflow-hidden
                  h-48 sm:h-64 md:h-[293px] md:w-[350px] lg:w-[532px] lg:h-[410px] xl:w-[532px] xl:h-[470px]
                  z-10 md:-mt-8 lg:-mt-12
                "
              >
                <ClickableImage
                  src={bannerData?.bannerImage || withCDN("/programs-page/all%20programs_main%20photo.png")}
                  alt="Children participating in enrichment programs"
                  className="object-cover"
                />
              </div>
            </div>
          </div>

          {/* CTA + STATS */}
          <div className="flex flex-wrap md:flex-nowrap items-center md:justify-between gap-2 md:gap-5 lg:gap-[10px] xl:gap-2">
            {/* BUTTON */}
            <button
              className="
              inline-flex items-center justify-center  
              h-[40px] md:h-[35px] lg:h-auto lg:py-5 xl:h-[60px]
              px-3 md:px-6 lg:px-6 xl:px-8
              rounded-full bg-[#0097DC] gap-1.5 md:gap-2
              font-normal text-white
              shadow-md
              cursor-pointer
              whitespace-nowrap
              hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1]
            "
             onClick={()=>{
                scrollToId("all-program");}}
            >
              <Image
                src={withCDN("/gear.png")}
                alt="Gear"
                width={25}
                height={25}
                className="w-4 h-4 md:w-5 md:h-5 lg:w-6 lg:h-6 xl:h-6 xl:w-6 shrink-0"
              />
              <span className="text-[13px] md:text-[15px] lg:text-[16px] xl:text-[24px] cursor-pointer whitespace-nowrap">{ctaText}</span>
            </button>

            <div className="flex flex-nowrap items-center gap-3.5 md:gap-1 lg:gap-[10px] xl:gap-[32px] overflow-hidden">
              {advantages.map((advantage: any, index: number) => (
                <div key={index} className="flex items-center gap-1 md:gap-2 flex-shrink-0 i-box">
                  <Image
                    src={advantage.icon}
                    alt={advantage.title}
                    width={40}
                    height={40}
                    className="shrink-0 md:w-[30px] md:h-[30px] xl:w-[40px] xl:h-[40px] min-[1600px]:!w-[50px] min-[1600px]:!h-[50px]"
                  />

                  <div className="leading-tight">
                    <p className="text-[20px] md:text-[18px] lg:text-[18px] xl:text-[25px] min-[1600px]:!text-[28px] 2xl:mb-1 font-bold text-[#58585A]">
                      {advantage.value}
                    </p>
                    <p
                      className="text-[8px] md:text-[8px] md:w-[80%] lg:w-full lg:text-[8px] xl:text-[10px] min-[1600px]:!text-[11px] uppercase tracking-wide text-[#58585A] font-light leading-tight i-text"
                      dangerouslySetInnerHTML={{
                        __html: advantage.description,
                      }}
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Mobile layout */}
      {/* relative z-30: the Inspiring section below pulls itself up with
          -mt-[320px] at z-20, so its curved white background would otherwise
          paint over the bottom of this hero card (hiding the program tiles). */}
      <div className="md:hidden relative z-30 flex justify-center  py-10  md:px-8 lg:px-18 xl:px-34 flex flex-col">
      {/*<p className="text-white pb-2  text-[14px]">Home - Programs</p>*/}
        <BackButton className="mt-4" />
        <div className="w-full rounded-[28px] bg-white px-5 py-6 shadow-xl mt-[20px]">
          <h1 className="text-3xl font-bold text-[#0097DC] leading-tight">
            {heading.split(" ").map((word, index) => (
              <span key={index}>
                {word}
                <br />
              </span>
            ))}
          </h1>
          <p
            className=" text-[18px] font-light text-[#58585A] md:pr-6 max-[340px]:text-[16px]"
          >
            {subHeading}
          </p>

          {/* IMAGE */}
          <div className="mt-4">
              <div
                className="
                  relative w-full rounded-[22px] overflow-hidden h-[200px]
                  z-10 md:-mt-8 lg:-mt-12
                "
              >
                <Image
                  src={withCDN("/programs-page/all%20programs_main%20photo.png")}
                  alt="Children participating in enrichment programs"
                  fill
                  className="object-cover"
                />
              </div>
              {/*==========logo-slider============ */}
              <div className="mt-2 flex flex-nowrap overflow-x-auto no-scrollbar gap-[5px] lg:gap-[10px] h-[86px] pt-[0px]">
                {isLoading ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <div
                      key={i}
                      className="flex w-[155px] justify-around p-[10px] items-center h-[70px] flex-[0_0_auto] mr-[3px] rounded-2xl bg-gray-50/80 animate-pulse text-center shadow-[6px_6px_8px_#0000000D]"
                    >
                      <div className="relative w-[70px] h-[56px] rounded-lg bg-gray-200"></div>
                      <div className="relative flex flex-col justify-center gap-1">
                          <div className="h-4 w-8 bg-gray-200 rounded-md"></div>
                          <div className="h-2 w-12 bg-gray-200 rounded-md"></div>
                      </div>
                    </div>
                  ))
                ) : (
                  dynamicPrograms.map((program) => (
                    <div
                      key={program.name}
                      onClick={() => handleProgramClick(program)}
                      className={`
                      flex w-[135px] justify-around p-[10px] items-center h-[70px] flex-[0_0_auto] mr-[3px] rounded-2xl bg-white  text-center shadow-[6px_6px_8px_#0000000D]  cursor-pointer transition icon-program-mob
                      ${selected === program.name ? "ring-2 ring-[#0070c9]" : ""}
                    `}
                    >
                      <div className="relative w-[88px] h-[60px] lg:w-10 pro-img-bx">
                        <Image
                          src={program.icon}
                          alt={program.name}
                          fill
                          className="object-cover"
                        />
                      </div>
                      <div className="relative">
                          <p className="mt-1 text-[21px] font-bold text-[#58585A] max-[767px]:ml-[-10px]">
                            {program.age}
                          </p>
                      </div>
                    </div>
                  ))
                )}
              </div>
              {/* <ProgramsMobileSlider />*/}
          </div>

          <div className="mt-6 grid grid-cols-2 gap-x-2.5 gap-y-2.5 pro-grid">
            {advantages.map((advantage: any, index: number) => (
              <div key={index} className="flex items-center gap-2.5 pro-grid-inner">
                <Image
                  src={advantage.icon}
                  alt={advantage.title}
                  width={40}
                  height={40}
                />
                <div className="leading-tight text-left">
                  <p className="text-lg font-bold text-[#58585A]">
                    {advantage.value}
                  </p>
                  <p 
                    className="text-[8px] text-[#58585A]"
                    dangerouslySetInnerHTML={{ __html: advantage.description.replace(/<br\s*\/?>/gi, '<br />').toUpperCase() }}
                  />
                </div>
              </div>
            ))}
          </div>

          {/* FULL-WIDTH CTA BUTTON */}
          {/* FULL-WIDTH CTA BUTTON */}
          <div className="flex justify-center">
            <button
              className="
              mt-6 w-full max-w-none flex items-center justify-center h-[45px]
              rounded-full bg-[#0097DC] gap-3 lg:gap-6
              px-6 py-3 text-[18px] font-normal text-white
              shadow-md cursor-pointer
              whitespace-nowrap max-[360px]:text-[15px]
            "
            onClick={()=>{
                scrollToId("all-program");}}
            >
              <Image
                src={withCDN("/gear.png")}
                alt="Gear"
                width={25}
                height={25}
                className="w-5.5 h-5.5 xl:h-8 xl:w-8 md:w-6 md:h-6 shrink-0"
              />
              <span className="whitespace-nowrap">{ctaText}</span>
            </button>
          </div>
        </div>
      </div>
    </section>
    </>
  );
}
