"use client";

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

const CATEGORY_COLORS: Record<string, string> = {
  "Farines Fortifiées":                "bg-amber-100  text-amber-800",
  "Farines Enrichies":                 "bg-yellow-100 text-yellow-800",
  "Pâte":                              "bg-orange-100 text-orange-800",
  "Fruits & Légumes Séchés en Poudre": "bg-green-100  text-green-800",
  "Biscrotch & Moutcha":               "bg-stone-100  text-stone-800",
  "Panier":                            "bg-purple-100 text-purple-800",
};

export default function Products({ products }: { products: Product[] }) {
  const { t } = useLanguage();
  const sectionRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;

    const badge   = section.querySelector<HTMLElement>('[data-r="badge"]');
    const heading = section.querySelector<HTMLElement>('[data-r="heading"]');
    const desc    = section.querySelector<HTMLElement>('[data-r="desc"]');
    const cards   = Array.from(section.querySelectorAll<HTMLElement>('[data-r="card"]'));
    const notebar = section.querySelector<HTMLElement>('[data-r="notebar"]');

    if (!badge) return;

    let tl: gsap.core.Timeline | null = null;

    const enterObs = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      tl?.kill();
      tl = gsap.timeline();
      tl.fromTo(badge,  { opacity: 0, y: 28 }, { opacity: 1, y: 0, duration: 1.1, ease: "power3.out" }, 0);
      if (heading)      tl.fromTo(heading, { opacity: 0, y: 28 }, { opacity: 1, y: 0, duration: 1.1, ease: "power3.out" }, 0.12);
      if (desc)         tl.fromTo(desc,    { opacity: 0, y: 28 }, { opacity: 1, y: 0, duration: 1.1, ease: "power3.out" }, 0.22);
      if (cards.length) tl.fromTo(cards,   { opacity: 0, y: 28 }, { opacity: 1, y: 0, duration: 1.1, ease: "power3.out", stagger: 0.1 }, 0.32);
      if (notebar)      tl.fromTo(notebar, { opacity: 0, y: 28 }, { opacity: 1, y: 0, duration: 1.1, ease: "power3.out" }, 0.55);
      enterObs.disconnect();
    }, { threshold: 0, rootMargin: "0px 0px -80px 0px" });

    enterObs.observe(badge);

    return () => { enterObs.disconnect(); };
  }, []);

  return (
    <section ref={sectionRef} id="products" className="py-28 lg:py-40 bg-brand-off-white">
      <div className="max-w-7xl mx-auto px-6">

        <div className="text-center mb-20 space-y-5">
          <span
            data-r="badge"
            style={{ opacity: 0 }}
            className="inline-block bg-brand-yellow text-brand-dark px-4 py-2 rounded-full text-[11px] font-bold tracking-[0.22em] uppercase"
          >
            {t.homeProducts.badge}
          </span>
          <h2
            data-r="heading"
            style={{ fontFamily: "var(--font-space, sans-serif)", opacity: 0 }}
            className="text-5xl lg:text-7xl font-bold leading-none tracking-tight text-brand-dark"
          >
            Njuumaan
            <span className="block text-stroke">{t.homeProducts.subtitle}</span>
          </h2>
          <p data-r="desc" style={{ opacity: 0 }} className="text-brand-dark/55 max-w-xl mx-auto leading-relaxed">
            {t.homeProducts.desc}
          </p>
        </div>

        {products.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {products.map((p) => (
              <ProductCard key={p.id} product={p} discover={t.homeProducts.discover} />
            ))}
          </div>
        ) : (
          <div className="text-center py-16 text-brand-dark/30 text-sm">
            {t.homeProducts.empty}
          </div>
        )}

        <div className="text-center mt-14">
          <Link href="/produits" className="inline-flex items-center gap-2 bg-brand-dark text-brand-yellow font-bold px-8 py-3.5 rounded-full text-sm tracking-wide hover:scale-105 transition-transform duration-300">
            {t.homeProducts.viewAll}
          </Link>
        </div>

        <div data-r="notebar" style={{ opacity: 0 }} className="mt-14 bg-brand-dark rounded-3xl px-8 py-6 flex flex-col md:flex-row items-center justify-between gap-4">
          <p className="text-white/70 text-sm leading-relaxed max-w-xl">
            <span className="text-brand-yellow font-bold">{t.homeProducts.available}</span> {t.homeProducts.notebar}
          </p>
          <a href="/produits" className="flex-shrink-0 bg-brand-yellow text-brand-dark font-bold px-6 py-3 rounded-full text-sm tracking-wide hover:scale-105 transition-transform duration-300 whitespace-nowrap">
            {t.homeProducts.order}
          </a>
        </div>
      </div>
    </section>
  );
}

function ProductCard({ product: p, discover }: { product: Product; discover: string }) {
  const catColor = CATEGORY_COLORS[p.category] ?? "bg-gray-100 text-gray-700";

  return (
    <div
      data-r="card"
      style={{ opacity: 0 }}
      className="group relative bg-brand-off-white rounded-3xl overflow-hidden border border-brand-dark/5 hover:border-transparent hover:shadow-xl transition-shadow duration-500"
    >
      <div className="absolute inset-0 bg-brand-yellow translate-y-full group-hover:translate-y-0 transition-transform duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]" />
      <div className="relative h-48 overflow-hidden">
        {p.image_url ? (
          <Image loader={cloudinaryLoader} src={p.image_url} alt={p.name} fill className="object-contain p-2 group-hover:scale-110 transition-transform duration-500" sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw" />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center">
            <Package size={52} weight="light" className="text-brand-dark/15 group-hover:text-brand-dark/25 transition-colors duration-300" />
          </div>
        )}
        {p.tag && (
          <span className="absolute top-4 left-4 z-10 bg-brand-yellow group-hover:bg-brand-dark text-brand-dark group-hover:text-brand-yellow text-[9px] font-bold tracking-widest uppercase px-2.5 py-1 rounded-full transition-colors duration-300">
            {p.tag}
          </span>
        )}
      </div>
      <div className="relative z-10 p-6 space-y-2">
        <span className={`inline-block text-[10px] font-bold tracking-wide px-2.5 py-1 rounded-full ${catColor} group-hover:bg-brand-dark/12 group-hover:text-brand-dark transition-colors duration-300`}>
          {p.category}
        </span>
        <h3 className="font-bold text-brand-dark text-lg leading-snug" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
          {p.name}
        </h3>
        {p.description && (
          <p className="text-brand-dark/55 group-hover:text-brand-dark/75 text-sm leading-relaxed line-clamp-2 transition-colors duration-300">
            {p.description}
          </p>
        )}
        <div className="flex items-center gap-1.5 text-sm font-bold text-brand-dark opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all duration-300 pt-1">
          {discover}
        </div>
      </div>
    </div>
  );
}
