import { ProductCard } from "@/components/shop/ProductCard";
import { fetchStoreProducts } from "@/lib/medusa";
import type { Product } from "@/data/products";

type Props = {
  searchParams: Promise<{ cat?: string; q?: string }>;
};

const ACCESORIO_ORDER = [
  "packaging-ot",
  "visor-ot",
  "gorra-ot",
  "bolso-duffel-ot",
  "neceser-ot",
];

function matchesQuery(p: Product, q: string) {
  const hay = [
    p.name,
    p.slug,
    p.collection,
    p.category,
    p.tagline || "",
    p.description || "",
  ]
    .join(" ")
    .toLowerCase();
  return q
    .toLowerCase()
    .split(/\s+/)
    .filter(Boolean)
    .every((term) => hay.includes(term));
}

export default async function ShopPage({ searchParams }: Props) {
  const { cat, q: rawQ } = await searchParams;
  const q = (rawQ || "").trim();
  const products = await fetchStoreProducts();

  let list = (() => {
    if (!cat) return products;
    if (cat === "mujer")
      return products.filter((p) => p.category === "mujer" || p.category === "sets");
    if (cat === "hombre") return products.filter((p) => p.category === "hombre");
    if (cat === "sets" || cat === "accesorios") {
      const filtered = products.filter((p) => p.category === cat);
      if (cat === "accesorios") {
        return [...filtered].sort((a, b) => {
          const ia = ACCESORIO_ORDER.indexOf(a.slug);
          const ib = ACCESORIO_ORDER.indexOf(b.slug);
          return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
        });
      }
      return filtered;
    }
    const filtered = products.filter(
      (p) =>
        p.category === cat ||
        p.collection.toLowerCase().includes(cat.toLowerCase()) ||
        p.slug.includes(cat)
    );
    return filtered.length ? filtered : products;
  })();

  if (q) {
    list = list.filter((p) => matchesQuery(p, q));
  }

  const isAccesorios = cat === "accesorios";
  const title = q
    ? `Resultados`
    : isAccesorios
      ? "Accesorios"
      : cat === "mujer"
        ? "Mujer"
        : cat === "hombre"
          ? "Hombre"
          : cat === "sets"
            ? "Sets"
            : cat || "Shop";

  return (
    <div className="ot-container py-12 md:py-16">
      <p className="ot-eyebrow">{q ? "Búsqueda" : isAccesorios ? "Club 1976" : "Catálogo"}</p>
      <h1 className="font-serif text-5xl md:text-6xl mt-2 capitalize">{title}</h1>
      <p className="mt-3 text-ot-muted max-w-xl">
        {q
          ? list.length
            ? `${list.length} resultado${list.length === 1 ? "" : "s"} para “${q}”.`
            : `No encontramos piezas para “${q}”. Prueba otro término.`
          : isAccesorios
            ? "Detalles de firma OT: packaging, visor, gorra y carry — para la cancha y después del partido."
            : "Productos sincronizados con Medusa · inventario y variantes reales."}
      </p>
      <div className="mt-10 grid grid-cols-2 lg:grid-cols-3 gap-4 md:gap-8">
        {list.map((p) => (
          <ProductCard key={p.id} product={p} />
        ))}
      </div>
    </div>
  );
}
