"use client";

import { useState, useMemo, useRef, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import Image from "next/image";
import cloudinaryLoader from "@/lib/cloudinaryLoader";
import { MagnifyingGlass, Package, X } from "@phosphor-icons/react";
import { ShoppingBag } from "lucide-react";
import type { Product } from "@/types/product";
import { useCart } from "@/lib/cartStore";
import gsap from "gsap";
import { useLanguage } from "@/lib/i18n/context";

const CATEGORIES = [
  "Farines Enrichies",
  "Farines Fortifiées",
  "Fruits & Légumes Séchés en Poudre",
  "Pâte",
  "Biscrotch & Moutcha",
  "Panier",
];

function ProductsClientInner({ products }: { products: Product[] }) {
  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const searchParams   = useSearchParams();
  const categoryParam  = searchParams.get("category") ?? "";
  const [search, setSearch] = useState("");
  const [activeCategory, setActiveCategory] = useState(
    CATEGORIES.find(c => c.toLowerCase() === categoryParam.toLowerCase()) ?? ""
  );

  const badgeRef = useRef<HTMLSpanElement>(null);
  const line1Ref = useRef<HTMLDivElement>(null);
  const line2Ref = useRef<HTMLDivElement>(null);
  const paraRef  = useRef<HTMLParagraphElement>(null);
  const illusRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const badge = badgeRef.current;
    const line1 = line1Ref.current;
    const line2 = line2Ref.current;
    const para  = paraRef.current;
    const illus = illusRef.current;
    if (!badge) return;

    gsap.set(badge, { opacity: 0, y: 16 });
    gsap.set([line1, line2], { y: "108%" });
    gsap.set(para,  { opacity: 0, y: 20 });
    gsap.set(illus, { opacity: 0, x: 60 });

    const tl = gsap.timeline({ delay: 0.1 });
    tl.to(badge, { opacity: 1, y: 0,        duration: 0.7, ease: "power3.out" }, 0);
    tl.to(line1, { y: "0%",                 duration: 0.9, ease: "power4.out" }, 0.15);
    tl.to(line2, { y: "0%",                 duration: 0.9, ease: "power4.out" }, 0.28);
    tl.to(para,  { opacity: 1, y: 0,        duration: 0.8, ease: "power3.out" }, 0.42);
    tl.to(illus, { opacity: 0.45, x: 0,     duration: 1.2, ease: "power3.out" }, 0.2);
  }, []);

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim();
    if (!q) return products;
    return products.filter((p) =>
      p.name.toLowerCase().includes(q) ||
      (p.description ?? "").toLowerCase().includes(q)
    );
  }, [products, search]);

  // Group by category, preserving CATEGORIES order; filter to one category if active
  const grouped = useMemo(() => {
    const cats = activeCategory
      ? CATEGORIES.filter((c) => c === activeCategory)
      : CATEGORIES;
    return cats
      .map((cat) => ({ cat, items: filtered.filter((p) => p.category === cat) }))
      .filter(({ items }) => items.length > 0);
  }, [filtered, activeCategory]);

  return (
    <>
      {/* ─── Hero ───────────────────────────────────────────────── */}
      <section className="relative bg-brand-sand-light pt-36 pb-20 px-6 overflow-hidden">
        {/* Illustration */}
        <div ref={illusRef} className={`absolute ${isRTL ? "-left-16" : "-right-16"} bottom-0 w-[420px] h-[420px] pointer-events-none select-none`}>
          <Image
            src="/illustration/3.png"
            alt=""
            fill
            sizes="420px"
            className="object-contain"
            style={{ mixBlendMode: "multiply", opacity: 0.45 }}
          />
        </div>

        {/* Stamp */}
        <img
          src="/illustration/tampon.png"
          alt="Riche en Vitamines et Minéraux"
          className={`absolute bottom-8 ${isRTL ? "left-24" : "right-24"} w-28 h-28 lg:w-36 lg:h-36 opacity-90 pointer-events-none select-none z-10`}
          style={{ transform: "rotate(-12deg)" }}
        />

        <div className="max-w-7xl mx-auto relative">
          <span ref={badgeRef} className="inline-block bg-brand-dark text-brand-yellow px-4 py-2 rounded-full text-[11px] font-bold tracking-[0.22em] uppercase mb-6">
            {t.products.badge}
          </span>
          <h1
            className="text-5xl sm:text-6xl lg:text-7xl font-bold leading-none tracking-tight text-brand-dark"
            style={{ fontFamily: "var(--font-space,sans-serif)" }}
          >
            <span className="block overflow-hidden">
              <div ref={line1Ref}>{t.products.line1}</div>
            </span>
            <span className="block overflow-hidden opacity-40">
              <div ref={line2Ref}>{t.products.line2}</div>
            </span>
          </h1>
          <p ref={paraRef} className="text-brand-dark/60 mt-6 text-base max-w-lg leading-relaxed">
            {t.products.sub}
          </p>
        </div>
      </section>

      {/* ─── Search + category filter ────────────────────────────── */}
      <div className="bg-brand-off-white border-b border-brand-dark/8 sticky top-20 z-20">
        <div className="max-w-7xl mx-auto px-4 py-3 flex flex-col sm:flex-row gap-2 sm:gap-3 sm:items-center">

          {/* Search */}
          <div className="relative w-full sm:w-64 flex-shrink-0">
            <MagnifyingGlass
              size={15}
              weight="bold"
              className={`absolute ${isRTL ? "right-3.5" : "left-3.5"} top-1/2 -translate-y-1/2 text-brand-dark/35 pointer-events-none`}
            />
            <input
              type="search"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={t.products.searchPlaceholder}
              className={`w-full ${isRTL ? "pr-9 pl-8" : "pl-9 pr-8"} py-2 rounded-full bg-brand-sand-light text-sm text-brand-dark placeholder:text-brand-dark/30 focus:outline-none focus:ring-2 focus:ring-brand-yellow/60 transition-all`}
            />
            {search && (
              <button
                onClick={() => setSearch("")}
                className={`absolute ${isRTL ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-brand-dark/30 hover:text-brand-dark transition-colors`}
              >
                <X size={13} weight="bold" />
              </button>
            )}
          </div>

          {/* Category pills */}
          <div className="flex items-center gap-2 flex-1 overflow-x-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
            <button
              onClick={() => setActiveCategory("")}
              className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-bold tracking-wide transition-colors duration-200 ${
                activeCategory === ""
                  ? "bg-brand-dark text-brand-yellow"
                  : "bg-brand-sand-light text-brand-dark/50 hover:text-brand-dark"
              }`}
            >
              {t.products.all}
            </button>
            {CATEGORIES.map((cat) => (
              <button
                key={cat}
                onClick={() => setActiveCategory(cat)}
                className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-bold tracking-wide transition-colors duration-200 ${
                  activeCategory === cat
                    ? "bg-brand-dark text-brand-yellow"
                    : "bg-brand-sand-light text-brand-dark/50 hover:text-brand-dark"
                }`}
              >
                {t.products.categories[cat as keyof typeof t.products.categories] ?? cat}
              </button>
            ))}
          </div>

        </div>
      </div>

      {/* ─── Grouped by category ────────────────────────────────── */}
      <div className="bg-brand-sand-light min-h-[50vh]">
        {grouped.length === 0 ? (
          <div className="max-w-7xl mx-auto px-6 py-16">
            <EmptyState onReset={() => setSearch("")} />
          </div>
        ) : (
          grouped.map(({ cat, items }, idx) => (
            <section
              key={cat}
              className={`max-w-7xl mx-auto px-6 py-14 ${idx !== 0 ? "border-t border-brand-dark/8" : ""}`}
            >
              <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr] gap-10 items-start">

                {/* ── Category label ── */}
                <div className="lg:sticky lg:top-40 z-10 bg-brand-sand-light -mx-6 px-6 pt-6 pb-4 lg:mx-0 lg:px-0 lg:pt-6 lg:pb-0 lg:bg-transparent">
                  <h2
                    className="text-4xl xl:text-5xl font-bold text-brand-dark leading-tight tracking-tight"
                    style={{ fontFamily: "var(--font-space,sans-serif)" }}
                  >
                    {t.products.categories[cat as keyof typeof t.products.categories] ?? cat}
                  </h2>
                  <p className="text-brand-dark/35 text-sm mt-1 lg:mt-3">
                    {items.length} {items.length > 1 ? t.products.products : t.products.product}
                  </p>
                </div>

                {/* ── Products grid ── */}
                <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
                  {items.map((p) => (
                    <ProductCard key={p.id} product={p} />
                  ))}
                </div>

              </div>
            </section>
          ))
        )}
      </div>
    </>
  );
}

export default function ProductsClient(props: { products: Product[] }) {
  return (
    <Suspense>
      <ProductsClientInner {...props} />
    </Suspense>
  );
}

function ProductCard({ product: p }: { product: Product }) {
  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const { addItem, removeItem, items } = useCart();
  const [selectedSize, setSelectedSize] = useState(p.sizes?.[0] ?? "");
  const inCart = items.some(i => i.id === p.id && (i.size ?? "") === (selectedSize ?? ""));

  return (
    <div className="group bg-brand-sand-light rounded-3xl overflow-hidden border border-brand-dark/8 hover:shadow-xl hover:-translate-y-1 transition-all duration-400 flex flex-col">

      {/* Image */}
      <div className="relative h-52 bg-brand-peach overflow-hidden">
        {p.image_url ? (
          <Image
            loader={cloudinaryLoader}
            src={p.image_url}
            alt={p.name}
            fill
            className="object-contain p-2 group-hover:scale-105 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={48} weight="light" className="text-brand-dark/15" />
          </div>
        )}
        {p.tag && (
          <span className={`absolute top-4 ${isRTL ? "right-4" : "left-4"} bg-brand-yellow text-brand-dark text-[9px] font-bold tracking-widest uppercase px-2.5 py-1 rounded-full`}>
            {p.tag}
          </span>
        )}
      </div>

      {/* Content */}
      <div className="p-6 flex flex-col flex-1">
        <h3
          className="font-bold text-brand-dark text-base leading-snug"
          style={{ fontFamily: "var(--font-space,sans-serif)" }}
        >
          {p.name}
        </h3>

        {p.description && (
          <p className="text-brand-dark/45 text-sm leading-relaxed line-clamp-2 mt-2 flex-1">
            {(locale === "en" ? p.description_en : locale === "es" ? p.description_es : locale === "ar" ? p.description_ar : p.description) || p.description}
          </p>
        )}

        {p.sizes?.length > 0 && (
          <div className="flex flex-wrap gap-1.5 mt-3">
            {p.sizes.map((s) => (
              <button
                key={s}
                onClick={() => setSelectedSize(s)}
                className={`text-[10px] font-bold px-2 py-0.5 rounded-full border transition-colors ${
                  selectedSize === s
                    ? "bg-brand-dark text-brand-yellow border-brand-dark"
                    : "text-brand-dark/50 border-brand-dark/15 hover:border-brand-dark/40"
                }`}
              >
                {s}
              </button>
            ))}
          </div>
        )}

        {/* Price + CTA */}
        <div className="mt-4 pt-4 border-t border-brand-dark/6 flex items-center justify-between gap-3">
          <div>
            <span className="font-bold text-brand-dark text-lg" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
              {p.price > 0 ? `${Number(p.price).toLocaleString("fr-MR")} MRU` : t.products.onQuote}
            </span>
            {p.price_gros > 0 && p.min_qty_gros > 1 && (
              <p className="text-[10px] text-brand-dark/40 mt-0.5 font-semibold">
                {Number(p.price_gros).toLocaleString("fr-MR")} MRU · dès {p.min_qty_gros} pcs
              </p>
            )}
          </div>
          {inCart ? (
            <button
              onClick={() => removeItem(p.id, selectedSize || undefined)}
              className="flex items-center gap-1.5 bg-red-500/10 text-red-500 text-xs font-bold px-4 py-2.5 rounded-full hover:bg-red-500 hover:text-white transition-colors duration-200"
            >
              <ShoppingBag size={13} />
              {t.products.remove}
            </button>
          ) : (
            <button
              onClick={() => addItem({ id: p.id, name: p.name, price: p.price, ...(p.price_gros > 0 && p.min_qty_gros > 1 ? { price_gros: p.price_gros, min_qty_gros: p.min_qty_gros } : {}), image_url: p.image_url, size: selectedSize || undefined })}
              className="flex items-center gap-1.5 bg-brand-dark text-brand-yellow text-xs font-bold px-4 py-2.5 rounded-full hover:bg-brand-yellow hover:text-brand-dark transition-colors duration-200"
            >
              <ShoppingBag size={13} />
              {t.products.add}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function EmptyState({ onReset }: { onReset: () => void }) {
  const { t } = useLanguage();
  return (
    <div className="text-center py-28 bg-brand-sand-light rounded-3xl border border-brand-dark/8">
      <Package size={56} weight="light" className="text-brand-dark/15 mx-auto mb-5" />
      <h3 className="text-xl font-bold text-brand-dark mb-2" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
        {t.products.noResults}
      </h3>
      <p className="text-brand-dark/40 text-sm mb-8 max-w-xs mx-auto">
        {t.products.noResultsSub}
      </p>
      <button
        onClick={onReset}
        className="bg-brand-dark text-brand-yellow font-bold px-6 py-3 rounded-full text-sm hover:scale-105 transition-transform duration-200"
      >
        {t.products.viewAll}
      </button>
    </div>
  );
}
