import { fetchHeaderFooterHomeData, getGlobalParams } from "../../../lib/serverFetch";
import { getWorkshopDetailAction } from "../../../lib/actions/workshopDetailAction";
import { extractLanguage } from "../../../lib/utils/domain";
import Image from "next/image";
import { withCDN, optimizedImage } from "@/src/lib/utils";
import AutoScrollSlider from "../../../components/ui/AutoScrollSlider";
import Accordion from "../../../components/ui/Accordion";
import FooterForm from "../../../components/layout/FormLazyWrapper";
import AnimatedScroll from "../../../components/ui/Animated-Scroll/AnimatedScroll";
import Footer from "../../../components/layout/Footer";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";
import { findHighlightRange } from "@/src/lib/utils/headingHighlight";
import { splitDuration } from "@/src/lib/utils/duration";
import { aiBadgeParts } from "@/src/lib/utils/aiBadge";

import Breadcrumbs from "../../../components/layout/Breadcrumbs";
import BackButton from "../../../components/layout/BackButton";
import NavLabel from "../../../components/layout/NavLabel";
import ClickableImage from "../../../components/ui/ClickableImage";
import WorkshopDetailClient from "../../../components/workshops/WorkshopDetailClient";
import type { WorkshopDetailData, WorkshopDetailDataWithTranslations } from "../../../lib/services/workshopDetailService";
import AIFeatureSection from "../../../components/ui/AIFeatureSection";
import FitText from "../../../components/ui/FitText";
import { toUrlSlug } from "../../../lib/utils/detailHref";
import type { Metadata } from "next";
import ProgramGallerySlider from "../../../components/programs/ProgramGallerySlider";

interface WorkshopDetailPageProps {
  params: Promise<{
    id: string;
  }>;
  searchParams: Promise<Record<string, string | string[]>>;
}

export const dynamic = 'force-dynamic';

// Per-workshop SEO. Reads the backend seo_title / seo_description (falling back
// to the workshop title/description). Mirrors the page's fetch args so the
// cached request is reused — no extra backend call.
export async function generateMetadata({ params, searchParams }: WorkshopDetailPageProps): Promise<Metadata> {
  try {
    const { id } = await params;
    const sParams = await searchParams;
    const { lang: globalLang, franchiseeId: globalFranchiseeId } = await getGlobalParams();
    const language = extractLanguage(sParams) || globalLang;
    const franchiseeId = (sParams.franchiseeId as string) || globalFranchiseeId;

    const { success, data } = await getWorkshopDetailAction(id, language, franchiseeId);
    if (!success || !data) return {};

    const workshop: WorkshopDetailData | undefined = data.translated || data.default;
    if (!workshop) return {};

    const title =
      workshop.seoTitle?.trim() ||
      (workshop.title ? `${workshop.title} | Young Engineers` : undefined);
    const description =
      workshop.seoDescription?.trim() ||
      (workshop.description
        ? workshop.description.replace(/\s+/g, " ").trim().slice(0, 160)
        : undefined);
    // Match the site's link convention (lowercased/hyphenated slug) so the
    // canonical matches the URLs actually linked/crawled.
    const slugPath = toUrlSlug(workshop.slug);
    const canonical = slugPath
      ? `/workshops/${id}/${slugPath}`
      : `/workshops/${id}`;

    return {
      // `absolute` bypasses the layout's "%s | Young Engineers" template so the
      // seo_title (or our fallback) is used verbatim — no doubled suffix.
      title: title ? { absolute: title } : undefined,
      description,
      alternates: { canonical },
      openGraph: {
        title: title || workshop.title,
        description,
        images: workshop.imageSrc ? [workshop.imageSrc] : undefined,
      },
    };
  } catch {
    return {};
  }
}

// Create workshop detail content render function
function createWorkshopDetailContent(workshopData: WorkshopDetailData, id: string, headerFooterHomeData: any, translated = false) {
  // Highlights are optional content. Blank rows are dropped, and when nothing is
  // left the whole section — heading, artwork and background — is omitted rather
  // than rendered as an empty shell.
  const workshopHighlightItems = (workshopData.workshopHighlights || []).filter(
    (highlight) =>
      (highlight?.title || "").trim() !== "" ||
      (highlight?.description || "").trim() !== ""
  );

  return (
    <main className={`workshop-detail workshop-${workshopData.title}`}>

      {/*=================Hero-Bnner========================= */}
      <section
        className="relative w-full overflow-hidden  py-6 md:py-16 lg:py-25
    min-h-[600px] md:min-h-[600px] lg:min-h-[620px] xl:min-h-[730px]
    px-4 md:px-8 lg:px-18 xl:px-34 sm:p b-0 pb-[80px] workshop-banner"
      >
        {/* Background */}
        <div className="absolute inset-0 -z-10 md:min-h-[690px]">
          <div
            className="block md:hidden w-full h-full bg-cover bg-bottom" 
             style={{
                 backgroundImage: `url('${optimizedImage(workshopData.heroBgMobile, 828)}')`,
                 backgroundRepeat: "no-repeat",
               }}
          />
          <div
            className="hidden md:block w-full h-full bg-cover bg-bottom lg:h-[830px]"
            style={{ backgroundImage: `url('${optimizedImage(workshopData.heroBgDesktop, 1920)}')` }}
          />
        </div>

        {/* Overlay */}
        <div className="pointer-events-none absolute inset-0" />

        {/* Main Content */}
        <div className="relative z-10 mx-auto md:flex flex-col justify-center lg:py-[0px]  xl:pt-[0px] lg:py-0 md:py-[12px] max-[767px]:pt-[0px]">
          {/* <p className="text-white lg:pb-[28px] pb-[16px] xl:text-[16px] md:text-[14px] font-light md:mt-4 mt-10 lg:mt-0">Home - Workshops - <span className="font-normal">{workshopData.title}</span></p> */}
          <NavLabel label={workshopData.title} />
          <BackButton className="mb-4" />
          <Breadcrumbs currentTitle={workshopData.title} />

          {/* CARD */}
          <div className="relative bg-white rounded-[32px] shadow-md md:h-[320px] xl:h-[410px] w-full 2xl:w-[1300px]  mx-auto flex flex-col md:flex-row overflow-hidden sm:overflow-visible mt-[20px] lg:mt-[10px] workshop-card-container">
            {/* LEFT RIBBON */}
            <div className="md:wsNa-[145px] xl:w-[200px] w-[120px] hidden md:flex 2xl:ml-12 ml-5 relative ribbon-wrapper" id={`ribbon-${workshopData.title}`}>
              <div
                className="absolute top-[-2] w-[200px] md:left-0
            h-[400px] md:w-[140px] md:h-[calc(100%+50px)]
            xl:w-[10.9rem] xl:h-[calc(100%+70px)]
            bg-cover bg-center bg-no-repeat
            flex flex-col items-center justify-start text-white gap-3"
                style={{ backgroundImage: `url('${optimizedImage(workshopData.ribbonImage, 384)}')` }}
              >
                <div className="flex flex-col items-center gap-2 mt-3 overflow-visible w-full">
                  <div className="relative w-14 h-14 md:w-28 md:h-28 lg:w-[100px] lg:h-[80px] xl:w-[152px] xl:h-[110px] md:w-[86px] md:h-[62px] workshop-ribbon-logo">
                    <Image src={workshopData.iconSrc} alt={workshopData.title} fill className="object-cover" />
                  </div>

                  <div className="w-full md:w-[94%] xl:w-full min-w-0 bg-[linear-gradient(90deg,rgba(34,107,32,1)_0%,rgba(114,167,35,1)_50%,rgba(149,193,31,1)_100%)] p-1 text-center bg-work" style={{ backgroundImage: `linear-gradient(90deg, ${workshopData.borderColor}dd 0%, ${workshopData.borderColor} 50%, ${workshopData.borderColor}99 100%)` }}>
                    <FitText minFontSize={10} className="text-[20px] md:text-[20px] uppercase text-[#fff]" id={`heading-${workshopData.title}`}>{workshopData.tag || workshopData.categoryTag}</FitText>
                  </div>

                  {/* AGE SECTION */}
                  <div className="text-xs md:text-sm leading-snug w-full xl:mt-5 py-0 xl:px-7 md:px-3 md:mt-0">
                    <p className="opacity-80 text-[12px] text-[#58585A]">{workshopData.createdFor}</p>
                    {/* Added flex items-baseline here to keep age numbers and label aligned */}
                    <div className="flex items-baseline gap-1 age-range">
                      {workshopData.ageRange && (
                        <span className="font-bold text-[28px] xl:text-[30px] txt-pro" style={{ color: workshopData.borderColor }}>{workshopData.ageRange}</span>
                      )}
                      {workshopData.ageLabel && (
                        <span className="text-[14px]" style={{ color: workshopData.borderColor }}>{workshopData.ageLabel}</span>
                      )}
                    </div>
                  </div>

                  {/* DURATION SECTION */}
                  {workshopData.duration && (
                    <div className="w-full text-xs md:text-lg leading-snug xl:mt-2 lg:mt-0 py-0 xl:px-7 md:px-3">
                      <p className="opacity-80 text-[12px] text-[#58585A]">{workshopData.durationHeading}</p>
                      {/* Removed the <p> tag and used a flex container to keep them on the same row */}
                      <div className="flex items-baseline gap-1 age-box flex-wrap">
                        <span className="font-bold text-[28px] xl:text-[30px] s1" style={{ color: workshopData.borderColor }}>{workshopData.duration}</span>
                        <span className="text-[14px] s2" style={{ color: workshopData.borderColor }}>{workshopData.durationUnit}</span>
                      </div>
                    </div>
                  )}

                </div>
              </div>
            </div>

            {/* MOBILE RIBBON */}
            <div className="md:wsNa-[125px] w-full block md:hidden relative grid grid-cols-12 items-center" id={`Mobile-ribbon-${workshopData.title}`}>
              <div
                className="col-span-5
                h-[158px]
                bg-cover bg-bottom bg-no-repeat
                flex flex-col items-center justify-start text-white gap-3 mob-ribbon"
                style={{ backgroundImage: `url('${optimizedImage(workshopData.mobileRibbonImage, 384)}')` }}
              >
                <div className="flex flex-col items-center gap-2 mt-3 w-full max-[380px]:mt-0">
                  <div className="relative w-[90px] h-[90px] bg-[#fff] rounded-full overflow-hidden mob-ribbon-logo">
                    <Image src={workshopData.iconSrc} alt={workshopData.title} fill className="object-cover" />
                  </div>
                  {/*
                  <div className="w-[86%] bg-[linear-gradient(90deg,rgba(34,107,32,1)_0%,rgba(114,167,35,1)_50%,rgba(149,193,31,1)_100%)] p-1 text-center" style={{ backgroundImage: `linear-gradient(90deg, ${workshopData.borderColor}dd 0%, ${workshopData.borderColor} 50%, ${workshopData.borderColor}99 100%)` }}>
                    <h4 className="text-[20px] md:text-[16px] uppercase text-[#fff] w-full max-[360px]:text-[15px]" id={`ribbon-${workshopData.title}`}>{workshopData.tag || workshopData.categoryTag}</h4>
                  </div>
                  */}
                </div>
              </div>
              <div className="col-span-7 pl-2">
                <p className="text-[30px] xl:text-[50px] font-bold uppercase leading-none block md:hidden mb-2 max-[360px]:text-[26px]" style={{ color: workshopData.borderColor }}>
                  {workshopData.title}
                </p>
                <h4 className="text-[20px] md:text-[16px] uppercase text-[#58585A] w-full max-[360px]:text-[15px] border-l-4 pl-2" id={`ribbon-${workshopData.title}`} 
                style={{ borderLeftColor: workshopData.borderColor }}>{workshopData.tag || workshopData.categoryTag}</h4>
              </div>
            </div>



            {/* CENTER CONTENT */}
            <div
              className="flex-1 px-5 md:px-6 md:py-0 lg:px-8 xl:px-1 2xl:px-2
       md:pr-[280px] lg:pr-[280px] xl:pr-[260px]   2xl:pr-[540px]
        min-h-auto xl:w-[27.25rem] xl:pr-[400px] md:w-[19.35rem] xl:pl-[30px] work-inner-content"
            >
              <div className="h-full sm:h-full lg:h-full pr-0 mt-[10px] md:mt-[30px] lg:mt-[30px] xl:mt-[50px] mb-[18px] flex flex-col justify-center md:justify-start xl:h-[100%] content-div">
                <h1 className="text-[30px] xl:text-[50px] font-bold uppercase leading-none hidden md:block" style={{ color: workshopData.borderColor }}>
                  {workshopData.title}
                </h1>

               <p className="mt-0 md:mt-3 text-[18px] xl:text-[20px] uppercase text-[#58585A] leading-tight max-[767px]:text-[20px] max-[767px]:font-semibold">
  {workshopData.subtitle.split(" ").map((word, index) => (
    <span key={index}>
      {index > 0 && " "}

      {aiBadgeParts(word) ? (
<>{aiBadgeParts(word)!.prefix}
        <span
          className="inline-flex items-center justify-center text-white px-3 py-[1px] rounded-[10px] text-[20px] xl:text-[18px] xl:leading-[28px] leading-[30px] max-[330px]:text-[17px] max-[330px]:leading-[24px] max-[330px]:px-2 gradient-bg"
          style={{
            background: workshopData.borderColor,
          }}
        >
          {aiBadgeParts(word)!.badge}
        </span></>
      ) : (
        word
      )}
    </span>
  ))}
</p>

                <div className="block md:hidden border-b border-t border-[#CACACA] mt-2 mb-3"  id={`Mobile-${workshopData.title}`}>
                   <div className="grid grid-cols-12 py-2 gap-3">
                  <div className="col-span-5 text-xs md:text-sm leading-snug w-full xl:mt-5 py-0 xl:px-7 md:px-3 md:mt-0 wokshop-left">
                    <p className="opacity-80 text-[12px] text-[#58585A] hidden md:block">{workshopData.createdFor}</p>
                    {/* English keeps its short phone label; the translated version shows
                        its own "created for" text instead of English. */}
                    <p className="opacity-80 text-[16px] text-[#58585A] block md:hidden  mb-1">{translated ? workshopData.createdFor : "Created for"}</p>
                    <div className="flex items-end gap-1">
                    {workshopData.ageRange && (
                      <><span className="font-bold text-[30px] pro-txt t1 leading-[30px]" style={{ color: workshopData.borderColor }}>{workshopData.ageRange}</span><br /></>
                    )}
                    {workshopData.ageLabel && (
                      <span className="text-[16px]" style={{ color: workshopData.borderColor }}> {workshopData.ageLabel}</span>
                    )}
                    </div>
                  </div>

                  {workshopData.duration && (
                    <div className="col-span-7 w-[99%] text-xs md:text-lg leading-snug xl:mt-2 lg:mt-0 py-0 xl:px-7 md:px-3 wokshop-right">
                      <p className="opacity-80 text-[16px] text-[#58585A] mb-1">{workshopData.durationHeading}</p>
                      <div className={`flex items-end gap-1 mob-durations${(workshopData.durationUnit || "").trim().length > 10 ? " duration-long" : ""}`}>
                      <div className="flex items-end gap-1">
                      <span className="font-bold text-[30px] leading-[30px] pro-txt" style={{ color: workshopData.borderColor }}>
                      {splitDuration(workshopData.duration).amount}</span>
                      <span
                        className="font-bold text-[16px] leading-[20px]"
                        style={{ color: workshopData.borderColor }}
                      >
                        {splitDuration(workshopData.duration).unit}
                      </span>
                      </div>
                      <p className="opacity-80 text-[16px]" style={{ color: workshopData.borderColor }}>
                        <span style={{ color: workshopData.borderColor }} className="text-[16px] leading-[20px] max-[324px]:text-[11px]">{workshopData.durationUnit}</span>
                      </p>
                      </div>
                    </div>
                  )}
                </div>
                </div>

                <p className="mt-3 text-[18px] md:text-[14px] lg:text-[16px] 2xl:text-[16px] text-[#58585A] font-light leading-relaxed max-w-[500px] md:overflow-y-auto md:scroll-thin md:h-[92px] lg:h-[95px] xl:h-[80px] work-desc">
                  {workshopData.description}
                </p>

                <div className="mt-4">
                  <LanguageAwareLink
                    href="#footerForm"
                    className="inline-flex items-center gap-2 rounded-full border border-[#0097DC] cursor-pointer px-[20px] justofy-center
                    px-4 py-2 text-[15px] uppercase bg-[#0097DC] text-white transition  max-[991px]:w-[100%] max-[991px]:justify-center hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1] active:shadow-[10px_14px_14px_#0000000D] max-[360px]:text-[14px] btn-work-shop">                    
                    <Image src={withCDN("/programs-page/AllPrograms/Vector.svg")} alt="arrow" width={26} height={26} className="h-[23px] w-auto sm:h-[25px] xl:h-[25px] max-[360px]:w-[20px] max-[360px]:h-[20px]" />
                    <span>{workshopData.ctaText}</span>
                  </LanguageAwareLink>
                </div>
              </div>
            </div>

            {/* RIGHT IMAGE */}
            <div className="relative w-[100%] right-0 mx-auto mt-2 xl:right-0 h-[217px] rounded-[30px] overflow-hidden
        md:absolute md:top-1/2 md:right-2 md:-translate-y-1/2 md:w-[240px] md:h-[360px] lg:h-[350px]
        2xl:w-[29.375rem] xl:w-[22.375rem] xl:h-[453px] mr-5 2xl:mr-12 max-[767px]:w-[98%] max-[767px]:right-[-1%] max-[767px]:mb-1 work-inner-image">
              <ClickableImage src={workshopData.imageSrc} alt={workshopData.title} className="object-cover" />
            </div>

          </div>
        </div>
      </section>



      {/*=============== Workshop Objectives section==================== */}
      <section className=" relative w-full overflow-hidden
       pb-10 md:pb-16 lg:pb-[80px]
       pt-5 md: pt-0
       px-4 md:px-8 lg:px-18 xl:px-34 sm:-mt-[120px] md:-mt-[130px] lg:mt-[-110px] lg:pt-[70px] xl:pt-[50px] work-objectives">
        {/* Background */}
        <div className="absolute inset-0 -z-10 ">
          <div
            className="block md:hidden w-full h-full bg-cover bg-bottom"
            /*style={{ backgroundImage: `url('${workshopData.objectivesBgMobile}')` }}*/
          />
          <div
            className="hidden md:block w-full h-full bg-cover bg-top"
            style={{ backgroundImage: `url('${optimizedImage(workshopData.objectivesBgDesktop, 1920)}')` }}
          />
        </div>

        <div className="max-w-[1300px] mx-auto grid grid-cols-1 sm:grid-cols-12 gap-2 mb-4 xl:min-h-[550px] max-[1279px]:items-center max-[1024px]:pt-[60px] max-[767px]:pt-[10px]">
          <div className="sm:col-span-6 xl:mt-[140px] objective-text">
            <h2 className="uppercase 2xl:text-[50px] xl:text-[45px] text-[30px] text-[#58585A] leading-tight font-bold mb-5">{workshopData.objectivesHeading}</h2>
            {(workshopData.objectives || []).map((objective, index) => (
              <div key={index} className="flex items-center mb-4 lg:mr-[50px]">
                <Image src={objective.icon} alt={objective.title} width={64} height={64} className="h-[54px] w-auto sm:h-[64px]" />
                <p className="mt-0 xl:text-[18px] 2xl:text-[22px] text-[18px] text-[#58585A] font-light leading-relaxed ml-4">{objective.description}</p>
              </div>
            ))}
          </div>
         
          <div className="sm:col-span-6 lg:mt-[20px] xlider">
              <ProgramGallerySlider slides={workshopData.gallerySlides} />
          </div>

          {/*<div className="sm:col-span-6 relative w-full h-[500px] xl:h-[600px] min[1800px]:h-[800px] max-[767px]:h-[300px] xl:absolute xl:left-[20%] object-img">
            <Image
              src={workshopData.highlightsImageSrc}
              alt={workshopData.title}
              fill
              className="object-contain  max-[767px]:object-contain"
            />
          </div> */}
        </div>

        {/* CTA section */}
        <div className="max-w-[1300px] mx-auto w-full grid grid-cols-1 sm:grid-cols-12 gap-[10px] xl:gap-10 md::gap-5 mb-4 min[1800px]:mt-[-110px] mt-[0px] lg:mt-[50px] items-center z-[99] relative workshop-cta-row">
          <div className="sm:col-span-7 lg:col-span-8">
            {(() => {
              const headingClass = "uppercase text-[30px] lg:text-[36px] 2xl:text-[40px] md:text-[30px] text-[#58585A] md:leading-tight lg:leading-relaxed leading-tight none font-bold mb-1";
              const fullHeading = workshopData.seeInActionHeading || "";
              const coloredTerm = workshopData.seeInActionHeadingColoredPart || workshopData.title;
              const range = findHighlightRange(fullHeading, coloredTerm);

              // The heading is one finished sentence from the API and the
              // workshop's name is somewhere inside it - whole ("Build Up") or
              // only partly ("Camps", "BIRTHDAYS"). Colour just that slice.
              if (range) {
                const [start, end] = range;
                return (
                  <h2 className={headingClass}>
                    {fullHeading.slice(0, start)}
                    <strong style={{ color: workshopData.borderColor }}>{fullHeading.slice(start, end)}</strong>
                    {fullHeading.slice(end)}
                  </h2>
                );
              }

              // No API heading, so name and heading are held as two separate
              // pieces ("Mechanics Camps" + "THAT SPARK IMAGINATION"): the
              // coloured name leads and the heading completes the sentence.
              return (
                <h2 className={headingClass}>
                  <span style={{ color: workshopData.borderColor }}>{workshopData.seeInActionHeadingColoredPart}</span> {fullHeading}
                </h2>
              );
            })()}
            <p className="mt-0 text-[18px] xl:text-[18px] 2xl:text-[22px] text-[#58585A] font-light  leading-relaxed">{workshopData.seeInActionDescription}</p>
          </div>
          <div className="sm:col-span-5 lg:col-span-4 text-center lg:text-right max-[767px]:mt-4 max-[767px]:mb-6">
            <LanguageAwareLink
              href="#footerForm"
              className="inline-flex items-center gap-5 rounded-full border border-[#0097DC] w-full md:w-max h-[45px] lg:width-full cursor-pointer lg:h-[60px]  justify-center
              px-4 py-2 xl:text-[24px] lg:text-[18px] text-[16px] uppercase bg-[#0097DC] justify-center text-center text-white transition px-[30px] hover:shadow-[10px_14px_14px_#0000000D] active:bg-[#0084C1] active:shadow-[10px_14px_14px_#0000000D]
              max-[767px]:gap-2 workshop-action-btn"
            >
              <Image src={withCDN("/programs-page/AllPrograms/Vector.svg")} alt="arrow" width={37} height={37} className="h-[23px] w-auto sm:h-[37px] max-[360px]:w-[20px]" />
              <span>{workshopData.ctaText}</span>
            </LanguageAwareLink>
          </div>
        </div>
      </section>

      {/* Image slider section */}
      <section className=" relative w-full overflow-hidden">
        <div className="flex items-center pt-0">
          <AutoScrollSlider images={workshopData.autoScrollSliderImages || []} />
        </div>
        <div className="flex items-center pt-0 lg:pt-5 max-[767px]:pt-0">
          <AnimatedScroll items={workshopData.animatedScrollItems || []}
            textColor={workshopData.borderColor} />
        </div>
      </section>
       
      {/* AI section - absent when the admin switched it off */}
      {workshopData.featureSection && (
        <div id={`AI-${workshopData.slug}`}>
           <AIFeatureSection data={workshopData.featureSection} />
        </div>
      )}

      {/* =================What Kids Discover section================== */}
      <section className="relative w-full
  sm:pb-10 md:pb-16 lg:pb-28
  pt-[100px]
  px-4 md:px-8 lg:px-18 xl:px-34 pb-10 md:pb-0 kid-discover-section">

        {/* Background */}
        <div className="absolute inset-0 -z-10  kid-discover-bg">
          <div
            className="block md:hidden w-full h-full bg-cover bg-top"
            style={{ backgroundImage: `url('${optimizedImage(workshopData.discoveriesBgMobile, 828)}')` }}
          />
          <div
            className="hidden md:block w-full h-full bg-cover bg-top"
            style={{ backgroundImage: `url('${optimizedImage(workshopData.discoveriesBgDesktop, 1920)}')` }}
          />
        </div>

        <div className="max-w-[1300px] mx-auto w-full grid grid-cols-1 sm:grid-cols-12 gap-10 mb-4 mt-2 items-center sm:mt-[0px] lg:mt-[30px] max-[767px]:gap-0">
          <div className="sm:col-span-6 sm:mt-0 mt-0 xl:mt-[-40px]">
            <h2 className="uppercase text-[30px] 2xl:text-[50px] lg:text-[45px] md:text-[30px] leading-tight font-bold mb-5 structure-heading" style={{ color: workshopData.discoverTextColor || "#fff" }}>{workshopData.whatKidsDiscoverHeading}</h2>
            {(workshopData.whatKidsDiscover || []).map((discovery, index) => (
              <div key={index} className="flex items-center mb-4  xl:mr-[60px] discover-box">
                <Image src={discovery.icon} alt="discovery" width={37} height={37} className="h-[30px] w-auto sm:h-[37px]" />
                <p className="mt-0 xl:text-[18px] text-[18px] 2xl:text-[22px] font-regular leading-relaxed ml-4" id={`text-${workshopData.title}-${index + 1}`} style={{ color: workshopData.discoverTextColor || "#fff" }}>
                  {discovery.text}
                </p>
              </div>
            ))}
          </div>
          <div className="sm:col-span-6 relative w-full h-[300px] lg:h-[500px] xl:h-[575px] xl:w-[700px] md:h-[360px] discover-gall">
            <Image
              src={workshopData.galleryImageSrc}
              alt={workshopData.title}
              fill
              className="object-contain md:object-contain"
            />
          </div>
        </div>
      </section>


      {/*=================accordion section — omitted when there are no highlights==================*/}
      {workshopHighlightItems.length > 0 && (
      <section className="relative w-full
        pb-10 md:pb-1 lg:pb-5
        pt-0
        px-4 md:px-8 lg:px-18 xl:px-34 mt-[-120px] md:mt-[-150px] 2xl:mt-[-174px] z-10 max-[767px]:mt-[-110px] accordion-workshop" id={`wrapper-${workshopData.title}`}>

        {/* Background */}
        <div className="absolute inset-0 -z-10">
          <div
            className="block md:hidden w-full h-full bg-cover bg-top"
            style={{ backgroundImage: `url('${optimizedImage(workshopData.highlightsBgMobile, 828)}')` }}
          />
          <div
            className="hidden md:block w-full h-full bg-cover bg-top accordion-bg"
            style={{ backgroundImage: `url('${optimizedImage(workshopData.highlightsBgDesktop, 1920)}')` }}
          />
        </div>


        <div className="max-w-[1300px] mx-auto w-full grid grid-cols-1 md:grid-cols-12 gap-10 mb-4 mt-8 items-center xl:min-h-[600px] ">
          <div className="md:col-span-7 sm:pt-[140px] pt-[0px] z-9 head-wrapper-top">
            <h2 className=" hidden md:block uppercase text-[50px] xl:text-[50px] md:text-[30px] text-[#58585A] leading-tight font-bold mb-5 xl:mt-5">{workshopData.workshopHighlightsHeading}</h2>

            {/* mobile-heading*/}
            <div className="py-1 grid grid-cols-12 block md:hidden items-center">
              <h2 className="col-span-7 uppercase text-[30px] text-[#58585A] leading-tight font-bold -mb-[50px] max-[360px]:text-[28px]">{workshopData.workshopHighlightsHeading}</h2>
              <div className="relative col-span-5 w-[200px] h-[190px] mt-[-30px] ml-[-30px] workshop-highlight-mob" >
                <Image
                  src={workshopData.highlightsMobileImageSrc}
                  alt={workshopData.title}
                  fill
                  className="object-contain w-[200px] h-[190px]"
                />
              </div>
            </div>

            <div className="py-1" id={`accordion-${workshopData.title}`}>
              <Accordion
                items={workshopHighlightItems.map(item => ({
                  title: item.title,
                  content: item.description
                }))}
                borderColor={workshopData.borderColor}
              />
            </div>
          </div>
          <div className="md:col-span-5 z-[-1] relative w-full h-[500px]  hidden md:block lg:w-[450px] lg:h-[600px]  mt-[-60px] xl:mt-0 
             xl:absolute xl:right-[0%] xl:z-[-1] xl:w-[890px] xl:h-[630px] work-highlight-box"  id={`image-${workshopData.title}`}>
            <Image
              src={workshopData.highlightsDesktopImageSrc}
              alt={workshopData.title}
              fill
              className="object-contain"
            />
          </div>
        </div>
      </section>
      )}

      {/* bottom sections */}
      {/* No overflow-hidden here. Footer-Form pulls its own content up by 370px
          (mt-[-70px] on its section + mt-[-300px] on the background div) so the
          decorative form-footer graphic sits behind the teacher photo. Against
          this wrapper's 360px padding that lands 10px ABOVE the section's top
          edge, and overflow-hidden was clipping it flat — which read as the
          section above "cropping" the image. The programs detail page wraps the
          same component in a plain div with no clipping, which is why it renders
          correctly there. Horizontal overflow is already handled globally by
          overflow-x-clip on html/body in layout.tsx. */}
      <section className="relative w-full mt-[0px] pt-[460px] md:pt-[300px] xl:pt-[380px] max-[767px]:pt-[360px]" id="footerForm">
        {/* eager: the registration form is the primary CTA here, so it must not
            depend on an intersection that a reload can miss. See FormLazyWrapper. */}
        <FooterForm eager page="workshop" generalSettings={headerFooterHomeData.general_settings} tenant={headerFooterHomeData.tenant} cwProgramId={workshopData.cwProgramId} />
        {/* Spacer restoring the vertical room the removed bottom slider provided,
            so the registration form clears the footer. Phones had 80px - more
            than the md and lg steps below it - which left an obvious empty band
            between the Next button and the footer curve; 24px clears the curve
            with no overlap. Adjust if needed. */}
        <div className="h-[24px] md:h-[40px] lg:h-[60px] xl:h-[180px]" aria-hidden="true" />
        <Footer footerData={headerFooterHomeData} />
      </section>

    </main>
  );
}

export default async function WorkshopDetailPage({ params, searchParams }: WorkshopDetailPageProps) {
  const { id } = await params;
  const sParams = await searchParams;

  // Utilize global context for silent persistence fallback
  const { lang: globalLang, franchiseeId: globalFranchiseeId } = await getGlobalParams();

  // Unified language extraction (URL param takes precedence)
  const language = extractLanguage(sParams) || globalLang;
  const franchiseeId = (sParams.franchiseeId as string) || globalFranchiseeId;

  // Fetch workshop detail data from service with language parameter
  const { success, data: workshopData } = await getWorkshopDetailAction(id, language, franchiseeId);
  const headerFooterHomeData = await fetchHeaderFooterHomeData(sParams);

  if (!success || !workshopData) {
    return (
      <main className="flex items-center justify-center min-h-[100dvh]">
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-800 mb-4">Workshop Not Found</h1>
          <p className="text-gray-600">The workshop you're looking for doesn't exist.</p>
        </div>
      </main>
    );
  }

  // Render both default and translated content on the server
  const defaultContent = createWorkshopDetailContent(workshopData.default, id, headerFooterHomeData);
  const translatedContent = workshopData.translated ? createWorkshopDetailContent(workshopData.translated, id, headerFooterHomeData, true) : null;

  return (
    <WorkshopDetailClient
      defaultContent={defaultContent}
      translatedContent={translatedContent}
    />
  );
}
