"use client";

import Image from "next/image";
import { motion } from "framer-motion";
import React from "react";
import { ProcessedProgram } from "@/src/lib/types/programs";
import { withCDN } from "@/src/lib/utils";
import LanguageAwareLink from "@/src/lib/utils/LanguageAwareLink";

interface ProgramCardProps {
  program: ProcessedProgram;
  isActive?: boolean;
  /** Preferred: a real link so the CTA supports right-click "open in new tab". */
  href?: string;
  onMoreInfo?: () => void;
}

const ProgramCard: React.FC<ProgramCardProps> = ({
  program,
  isActive = false,
  href,
  onMoreInfo,
}) => {
  const {
    title,
    slug,
    header_image,
    program_icon,
    minAge,
    maxAge,
    skills_text,
    creative_thinking_text,
    more_info_text,
  } = program;

  const skillsLabel = skills_text || "Skills";
  const creativeThinkingLabel = creative_thinking_text || "Creative Thinking";
  const moreInfoLabel = more_info_text || "More Info";

  /**
   * Slug mapping for fixed program names.
   * Handles both exact match and prefix/suffix contains.
   */
  const getMappedSlug = (s: string) => {
    const sl = s.toUpperCase();
    if (sl.includes("ALGOC")) return "ALGOC";
    if (sl.includes("ALGOPLAY")) return "ALGOPLAY";
    if (sl.includes("ALGO_BUDDY")) return "ALGO_BUDDY";
    if (sl.includes("BRICKS_CHALLENGE") || sl.includes("BRICKS CHALLENGE")) return "BRICKS_CHALLENGE";
    if (sl.includes("BIG_BUILDERS") || sl.includes("BIG BUILDERS")) return "BIG_BUILDERS";
    if (sl.includes("ROBO_TOYS")) return "ROBO_TOYS";
    if (sl.includes("ROBOBRICKS")) return "ROBOBRICKS";
    if (sl.includes("GALILEO_TECHNIC") || sl.includes("GALILEO TECHNIC")) return "GALILEO_TECHNIC";
    if (sl.includes("SMARTIVO")) return "SMARTIVO";
    if (sl.includes("PRO")) return "PRO";
    return sl;
  };

  const baseSlug = slug ? getMappedSlug(slug) : "";

  const programMapping: Record<string, { color: string; model: string; header_image: string; gradient?: string }> = {
    "ALGOC": {
      color: "bg-[#0091D6]",
      gradient: "linear-gradient(180deg, #DC4B63 0%, #E89163 100%)",
      model: withCDN("/Program-detail/algoc/pct-6.png"),
      header_image: withCDN("/program-logo/logo_algo_c.svg")
    },
    "ALGOPLAY": {
      color: "bg-[#9E358C]",
      model: withCDN("/program-logo/model%20(3).png"),
      header_image: withCDN("/program-logo/logo_algo_play.svg")
    },
    "ALGO_BUDDY": {
      color: "bg-[#0091D6]",
      model: withCDN("/program-logo/model.png"),
      header_image: withCDN("/program-logo/logo_algo_buddy.svg")
    },
    "BRICKS_CHALLENGE": {
      color: "bg-[#95C11F]",
      model: withCDN("/program-logo/model%20(2).png"),
      header_image: withCDN("/program-logo/logo_bricks_chalenge.svg")
    },
    "BIG_BUILDERS": {
      color: "bg-[#F49800]",
      model: withCDN("/program-logo/model%20(1).png"),
      header_image: withCDN("/program-logo/logo_big_builders.svg")
    },
    "ROBO_TOYS": {
      color: "bg-[#01A498]",
      model: withCDN("/program-logo/model%20(6).png"),
      header_image: withCDN("/program-logo/logo_robo_toys.svg")
    },
    "ROBOBRICKS": {
      color: "bg-[#01A498]",
      model: withCDN("/program-logo/model%20(7).png"),
      header_image: withCDN("/program-logo/logo_robo_bricks.svg")
    },
    "GALILEO_TECHNIC": {
      color: "bg-[#DD043E]",
      model: withCDN("/program-logo/model%20(5).png"),
      header_image: withCDN("/program-logo/logo_galileo_technic.svg")
    },
    "SMARTIVO": {
      color: "bg-[#0091D6]",
      model: withCDN("/program-logo/model%20(4).png"),
      header_image: withCDN("/program-logo/logo_smartivo.svg")
    },
    "PRO": {
      color: "bg-[#15395F]",
      model: withCDN("/home/Models/robotics-model.png"),
      header_image: withCDN("/program-logo/logo_pro.svg")
    },
  };

  const currentMapping = baseSlug ? programMapping[baseSlug] : null;
  const bgColor = currentMapping?.color || "bg-red-500";
  const bgGradient = currentMapping?.gradient;
  // The mask SVG sits on top; the gradient (when present) is layered behind it so it
  // shows through the mask's transparent area, just like the flat background-color does.
  const cardBackgroundImage = bgGradient
    ? `url('${withCDN("/mask_group.svg")}'), ${bgGradient}`
    : `url('${withCDN("/mask_group.svg")}')`;
  const modelImage = currentMapping?.model || program_icon || withCDN("/testing_toy.png");
  const staticHeaderImage = program_icon ? withCDN(program_icon) : (currentMapping?.header_image || header_image || withCDN("/testing_logo.png"));

  return (
    <motion.div
      // initial={{ scale: 0.9, opacity: 0.8 }}
      animate={{
        scale: isActive ? 1 : 0.9,
        opacity: isActive ? 1 : 0.8,
      }}
      transition={{ type: "spring", stiffness: 150, damping: 20 }}
      className="rounded-md overflow-visible z-60 bg-transparent flex flex-col w-[300px] h-[170px] md:w-[250px] md:h-[150px] lg:w-[295px] xl:w-[320px] lg:h-[215px] cursor-pointer slider-card"    >
      {/* Top image (takes all space above footer) */}
      <div className="relative w-full h-full flex-grow overflow-visible rounded-md z-70" >
        <div
          className={`w-full h-full ${bgGradient ? "" : bgColor} bg-cover bg-center bg-no-repeat flex items-center justify-between h-full rounded-t-md`}
          style={{ backgroundImage: cardBackgroundImage }}
        >
          <div className="around-logo relative h-full flex items-center justify-center">
            <Image
              src={staticHeaderImage}
              alt={title}
              className="w-[160px] h-[90px] md:w-[110px] md:h-[55px] lg:w-[160px] lg:h-[90px] object-cover mx-auto icon-logo"
              width={80}
              height={80}
              loading="lazy"
            />
          </div>
          <div className="flex flex-col h-full w-1/2 justify-end">
            <div className=" relative h-full l flex items-center justify-end">
              <Image
                src={modelImage}
                alt={title}
                className={`absolute program-toy -bottom-[20px] right-3 md:right-1 lg:right-3 lg:bottom-[-6px] md:bottom-[-28] h-[160px] w-fit ${isActive ? "h-[60px] md:h-[120px] lg:h-[160px] lg:bottom-[-15px]" : "h-[60px] md:h-[100px] lg:h-[160px] lg:bottom-[-12px] md:bottom-[1px]"}`}
                width={100}
                height={100}
                loading="lazy"
              />
            </div>
            <div className="flex flex-col items-center justify-center text-white p-1 pb-2">
              <h3 className="text-white lg:text-[40px]  md:text-[25px] text-[40px] font-bold uppercase -mb-[8px]">
                {minAge && maxAge ? `${minAge}-${maxAge}` : '6-10'}
              </h3>
              <p className={`text-[10px] ${isActive ? 'md:text-[7px] lg:text-[10px]' : 'md:text-[5px] lg:text-[8px]'} uppercase font-normal`}>Years Old Program</p>
            </div>
          </div>
        </div>
      </div>

      {/* Footer section */}
      <div className="bg-[#58585A] z-80 flex justify-between items-center px-[19px] md:px-[10px]  md:py-[16px] py-2 rounded-b-md card_footer">
        <div className="flex lg:space-x-4 md:space-x-2 space-x-3 xl:max-w-[170px]">
          <div className="flex items-center space-x-1 max-w-[100px] gap-1">
            <Image
              src="https://yefranchisees.b-cdn.net/frontend/programs-around/icon (14).svg"
              alt={skillsLabel}
              width={25}
              height={25}
              loading="lazy"
            />
            <span className={`text-white leading-tight ${isActive ? "text-[10px] md:text-[9px] lg:text-[10px] xl:text-[12px]" : " text-[10px] md:text-[9px] lg:text-[10px] xl:text-[12px]"}`}>
              {skillsLabel}
            </span>
          </div>
          <div className="flex items-center space-x-1 max-w-[100px] gap-1">
            <Image
              src="https://yefranchisees.b-cdn.net/frontend/programs-around/icon (12).svg"
              alt={creativeThinkingLabel}
              width={25}
              height={25}
              loading="lazy"
            />
            <span className={`text-white leading-tight ${isActive ? "text-[10px] md:text-[9px] g:text-[10px] xl:text-[12px]" : " text-[10px] md:text-[9px] lg:text-[10px] xl:text-[12px]"}`}>
              {creativeThinkingLabel}
            </span>
          </div>
        </div>

        {href ? (
          <LanguageAwareLink
            href={href}
            className="bg-white text-[#0097DC] text-[10px] md:text-[8px] lg:text-[10px] uppercase font-semibold px-3 md:px-2 lg:px-3 py-2  whitespace-nowrap rounded-[10px] cursor-pointer"
          >
            {moreInfoLabel}
          </LanguageAwareLink>
        ) : (
          <button
            onClick={onMoreInfo}
            className="bg-white text-[#0097DC] text-[10px] md:text-[8px] lg:text-[10px] uppercase font-semibold px-3 md:px-2 lg:px-3 py-2  whitespace-nowrap rounded-[10px] cursor-pointer"
          >
            {moreInfoLabel}
          </button>
        )}
      </div>
    </motion.div>
  );
};

export default ProgramCard;
