"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;
  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,
    years_old_text,
  } = program;

  const skillsLabel = skills_text || "Skills";
  const creativeThinkingLabel = creative_thinking_text || "Creative Thinking";
  const moreInfoLabel = more_info_text || "More Info";
  const yearsOldLabel = years_old_text || "Years Old Program";

  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/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/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;

  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");


  const isMobile =
    typeof window !== "undefined" && window.innerWidth < 768;

  return (
    <div
      className={`slider-card relative z-60 flex w-full items-center justify-center overflow-visible rounded-md bg-transparent cursor-pointer ${
        isActive ? "is-active" : "is-inactive"
      }`}
    >
      <motion.div
        initial={
          isMobile
            ? { height: "90%", opacity: 0.8 }
            : false
        }
        animate={{
          height: isActive ? "100%" : "90%",
          opacity: isActive ? 1 : 0.8,
        }}
        // Swiper renders duplicate cards for wraparound. Replaying this
        // viewport animation on each duplicate makes the card shrink twice.
        // Mobile focus scaling is handled by the swiper slide wrapper.
        whileInView={undefined}
        viewport={{
          once: false,
          amount: 0.3,
        }}
        transition={{
          type: "spring",
          stiffness: 150,
          damping: 20,
        }}
        className="program-card-inner relative flex w-full flex-col overflow-visible rounded-md"
      >

        {/* Top image section */}
        <div
          className={`program-card-top ${title} relative flex min-h-0 w-full flex-1 items-center justify-between overflow-visible rounded-t-md ${
            bgGradient ? "" : bgColor
          } bg-cover bg-center bg-no-repeat`}
          style={{ backgroundImage: cardBackgroundImage }}
        >
          {/* Program logo */}
          <div className="around-logo relative flex h-full items-center justify-center">
            <Image
              src={staticHeaderImage}
              alt={title}
              className="icon-logo mx-auto h-[120px] w-[200px] object-cover md:h-[55px] md:w-[110px] lg:h-[90px] lg:w-[160px]"
              width={80}
              height={80}
              loading="lazy"
            />
          </div>

          {/* Program model and age */}
          <div className="flex h-full w-1/2 flex-col justify-end">
            <div className="relative flex h-full items-center justify-end">
              <Image
                src={modelImage}
                alt={title}
                className="program-toy absolute -bottom-[20px] right-3 h-[60px] w-fit md:right-1 md:-bottom-[18px] md:h-[120px] lg:right-3 lg:-bottom-[15px] lg:h-[160px]"
                width={100}
                height={100}
                loading="lazy"
              />
            </div>

            <div className="flex flex-col items-center justify-center p-1 pb-2 text-white">
              <h3 className="program-age mb-[-8px] text-[40px] font-bold uppercase md:text-[25px] lg:text-[40px]">
                {minAge && maxAge ? `${minAge}-${maxAge}` : "6-10"}
              </h3>

              <p className="program-age-label text-[10px] font-normal uppercase md:text-[7px] lg:text-[10px]">
                {yearsOldLabel}
              </p>
            </div>
          </div>
        </div>

        {/* Footer section */}
        <div className="card_footer relative z-80 flex w-full shrink-0 items-center justify-between rounded-b-md bg-[#58585A] px-[19px] py-2 md:px-[10px] md:py-[16px]">
          <div className="flex space-x-3 md:space-x-2 lg:space-x-4 xl:max-w-[170px]">
            {/* Skills */}
            <div className="flex max-w-[100px] items-center gap-1 space-x-1">
              <Image
                src="https://yefranchisees.b-cdn.net/frontend/programs-around/icon (14).svg"
                alt={skillsLabel}
                width={25}
                height={25}
                loading="lazy"
                unoptimized
              />

              <span className="text-[10px] leading-tight text-white md:text-[9px] lg:text-[10px] xl:text-[12px]">
                {skillsLabel}
              </span>
            </div>

            {/* Creative thinking */}
            <div className="flex max-w-[100px] items-center gap-1 space-x-1">
              <Image
                src="https://yefranchisees.b-cdn.net/frontend/programs-around/icon (12).svg"
                alt={creativeThinkingLabel}
                width={25}
                height={25}
                loading="lazy"
                unoptimized
              />

              <span className="text-[10px] leading-tight text-white md:text-[9px] lg:text-[10px] xl:text-[12px]">
                {creativeThinkingLabel}
              </span>
            </div>
          </div>

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

export default ProgramCard;
