"use client";

import { useRef, useEffect } from "react";
import Image from "next/image";
import cloudinaryLoader from "@/lib/cloudinaryLoader";
import Link  from "next/link";
import gsap  from "gsap";
import type { Product } from "@/types/product";
import { useLanguage } from "@/lib/i18n/context";

const THEMES = [
  { bg: "var(--color-brand-off-white)", text: "var(--color-brand-dark)", accent: "var(--color-brand-dark)", sub: "rgba(26,26,26,0.45)" },
  { bg: "var(--color-brand-peach)",     text: "var(--color-brand-dark)", accent: "var(--color-brand-dark)", sub: "rgba(26,26,26,0.45)" },
];

type Theme = (typeof THEMES)[number];

function Slide({
  product, theme, idx, total,
}: {
  product: Product; theme: Theme; idx: number; total: number;
}) {
  const { t, locale } = useLanguage();
  const slideRef   = useRef<HTMLDivElement>(null);
  const badgeRef   = useRef<HTMLSpanElement>(null);
  const nameLineRef = useRef<HTMLDivElement>(null);
  const descRef    = useRef<HTMLParagraphElement>(null);
  const ctaRef     = useRef<HTMLDivElement>(null);
  const imgRef     = useRef<HTMLDivElement>(null);

  const imgLeft = idx % 2 === 0;

  useEffect(() => {
    const slide    = slideRef.current;
    const badge    = badgeRef.current;
    const nameLine = nameLineRef.current;
    const desc     = descRef.current;
    const cta      = ctaRef.current;
    const img      = imgRef.current;
    if (!slide || !badge) return;

    // Initial states
    gsap.set(badge,    { opacity: 0, y: 14 });
    gsap.set(nameLine, { y: "108%" });
    gsap.set(desc,     { opacity: 0, y: 20 });
    gsap.set(cta,      { opacity: 0, y: 16 });
    gsap.set(img,      { opacity: 0, x: imgLeft ? -36 : 36, scale: 0.9 });

    const obs = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;

      const tl = gsap.timeline();
      // Image slides in from the side
      tl.to(img,      { opacity: 1, x: 0, scale: 1, duration: 1.0, ease: "power3.out" }, 0);
      // Badge fades up
      tl.to(badge,    { opacity: 1, y: 0,   duration: 0.65, ease: "power3.out" }, 0.08);
      // Product name clip-reveal
      tl.to(nameLine, { y: "0%",            duration: 0.9,  ease: "power4.out" }, 0.2);
      // Description
      tl.to(desc,     { opacity: 1, y: 0,   duration: 0.65, ease: "power3.out" }, 0.38);
      // CTAs
      tl.to(cta,      { opacity: 1, y: 0,   duration: 0.6,  ease: "power3.out" }, 0.5);

      obs.disconnect();
    }, { threshold: 0.3 });

    obs.observe(slide);
    return () => obs.disconnect();
  }, [imgLeft]);

  const textBlock = (
    <div className="flex flex-col justify-center space-y-5 lg:space-y-7">
      <span
        ref={badgeRef}
        style={{ color: theme.accent, borderColor: `${theme.accent}50` }}
        className="self-start border px-4 py-1.5 rounded-full text-[10px] font-bold tracking-[0.28em] uppercase"
      >
        {(t.products.categories[product.category as keyof typeof t.products.categories] ?? product.category).replace(" en Poudre", "")}
      </span>

      <h2
        style={{
          color:      theme.text,
          fontFamily: "var(--font-space, sans-serif)",
          fontSize:   "clamp(2rem, 4.5vw, 5rem)",
          lineHeight: 1.05,
        }}
        className="font-bold tracking-tight overflow-hidden"
      >
        <div ref={nameLineRef}>{product.name}</div>
      </h2>

      {product.description && (
        <p
          ref={descRef}
          style={{ color: theme.sub }}
          className="text-sm lg:text-base leading-relaxed max-w-md"
        >
          {(locale === "en" ? product.description_en : locale === "es" ? product.description_es : locale === "ar" ? product.description_ar : product.description) || product.description}
        </p>
      )}

      <div ref={ctaRef} className="flex items-center gap-5 pt-1">
        <Link
          href={`/produits?category=${encodeURIComponent(product.category)}`}
          style={{ backgroundColor: theme.accent, color: theme.bg }}
          className="inline-flex items-center gap-2 font-bold px-7 py-3.5 rounded-full text-sm tracking-wide hover:scale-105 transition-transform duration-300"
        >
          {t.homeProducts.discover}
        </Link>
        <Link
          href="/produits"
          style={{ color: theme.sub }}
          className="text-xs font-semibold tracking-wide hover:opacity-80 transition-opacity underline underline-offset-4"
        >
          {t.products.viewAll}
        </Link>
      </div>
    </div>
  );

  return (
    <div
      ref={slideRef}
      style={{
        position:        "sticky",
        top:             0,
        height:          "100vh",
        zIndex:          idx + 1,
        backgroundColor: theme.bg,
        display:         "flex",
        alignItems:      "center",
        borderRadius:    idx > 0 ? "2rem 2rem 0 0" : undefined,
        boxShadow:       idx > 0 ? "0 -8px 40px rgba(0,0,0,0.18)" : undefined,
      }}
    >
      <div className="max-w-7xl mx-auto px-6 lg:px-16 w-full">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-24 items-center">

          {imgLeft ? (
            <>
              <div ref={imgRef} className="flex items-center justify-center order-first lg:order-none">
                <ImgInner product={product} theme={theme} idx={idx} />
              </div>
              {textBlock}
            </>
          ) : (
            <>
              {textBlock}
              <div ref={imgRef} className="flex items-center justify-center">
                <ImgInner product={product} theme={theme} idx={idx} />
              </div>
            </>
          )}

        </div>
      </div>

      {/* Slide counter */}
      <span
        className="absolute bottom-9 right-8 lg:right-16 text-[9px] font-bold tracking-[0.35em] uppercase"
        style={{ color: `${theme.accent}60` }}
      >
        {String(idx + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
      </span>

    </div>
  );
}

export default function ProductShowcase({ products }: { products: Product[] }) {
  if (products.length === 0) return null;
  const n         = products.length;
  const lastTheme = THEMES[n % THEMES.length];

  return (
    <section id="products">
      {products.map((product, i) => (
        <Slide
          key={product.id}
          product={product}
          theme={THEMES[(i + 1) % THEMES.length]}

          idx={i}
          total={n}
        />
      ))}
      <div style={{ height: "30vh", backgroundColor: lastTheme.bg }} />
    </section>
  );
}

function ImgInner({ product, theme, idx }: { product: Product; theme: Theme; idx: number }) {
  const isFirst = idx === 0;
  return (
    <div className="relative w-[240px] h-[240px] sm:w-[360px] sm:h-[360px] lg:w-[460px] lg:h-[460px]">
      {isFirst ? (
        <Image
          src="/njuuman_all_packages.png"
          alt={product.name}
          fill
          sizes="(max-width: 1024px) 80vw, 45vw"
          className="object-contain"
          style={{ filter: "drop-shadow(0 40px 60px rgba(0,0,0,0.22))" }}
        />
      ) : product.image_url ? (
        <Image
          loader={cloudinaryLoader}
          src={product.image_url}
          alt={product.name}
          fill
          sizes="(max-width: 1024px) 80vw, 45vw"
          className="object-contain"
          style={{ filter: "drop-shadow(0 40px 60px rgba(0,0,0,0.22))" }}
        />
      ) : (
        <div
          className="w-full h-full rounded-3xl opacity-10"
          style={{ backgroundColor: theme.accent }}
        />
      )}
      {/* Stamp */}
      <img
        src="/illustration/tampon.png"
        alt="Riche en Vitamines et Minéraux"
        className="absolute bottom-0 right-0 w-16 h-16 sm:w-20 sm:h-20 opacity-85 pointer-events-none select-none"
        style={{ transform: "rotate(-15deg)" }}
      />
    </div>
  );
}
