import Link from "next/link";
import Container from "@/components/ui/Container";
import StoreSubNav from "@/components/shop/StoreSubNav";
import { getStoreProducts, type StoreProduct } from "@/lib/api";

export const metadata = { title: "Collections | allBETs" };
export const revalidate = 300;

function titleCase(v: string): string {
  return v.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}

interface Tile {
  title: string;
  caption: string;
  count: number;
  query: string;
  featured?: boolean;
}

/** Builds the collection tile grid straight from the live catalog's taxonomy (outfitKey,
 *  fabric, gender) rather than hardcoding collection names the seeded data may not have —
 *  mirrors the reference's "grouped by fabric / outfit / gender / age" tile grid, with a
 *  highlighted "The Full Index" tile linking to the unfiltered shop. */
function buildTiles(products: StoreProduct[]): Tile[] {
  const byOutfit = groupBy(products, (p) => p.outfitKey);
  const byFabric = groupBy(products, (p) => p.fabric);
  const byGender = groupBy(products, (p) => p.gender);

  const tiles: Tile[] = [
    ...Object.entries(byOutfit)
      .slice(0, 2)
      .map(([k, v]) => ({ title: titleCase(k), caption: `Outfit — ${v.length}`, count: v.length, query: `outfit=${encodeURIComponent(k)}` })),
    ...Object.entries(byFabric)
      .slice(0, 2)
      .map(([k, v]) => ({ title: titleCase(k), caption: `Fabric — ${v.length}`, count: v.length, query: `fabric=${encodeURIComponent(k)}` })),
    ...Object.entries(byGender)
      .slice(0, 2)
      .map(([k, v]) => ({ title: titleCase(k), caption: `Gender — ${v.length}`, count: v.length, query: `gender=${encodeURIComponent(k)}` }))
  ];

  tiles.push({
    title: "The Full Index",
    caption: `Everything, ${products.length} products`,
    count: products.length,
    query: "",
    featured: true
  });

  return tiles;
}

function groupBy(products: StoreProduct[], pick: (p: StoreProduct) => string | null): Record<string, StoreProduct[]> {
  const out: Record<string, StoreProduct[]> = {};
  for (const p of products) {
    const key = pick(p);
    if (!key) continue;
    (out[key] ||= []).push(p);
  }
  return out;
}

export default async function CollectionsPage() {
  const products = await getStoreProducts();
  const tiles = buildTiles(products);

  return (
    <>
      <StoreSubNav active="collections" />

      <section className="border-b border-[rgba(29,39,57,0.18)]">
        <div className="grid grid-cols-1 lg:grid-cols-2">
          <div className="px-6 lg:px-10 py-14 lg:py-20 max-w-xl">
            <p className="text-[11px] font-bold uppercase tracking-[0.15em] text-[#6f7885]">
              Drop 04 — allBETs Go / Shipping worldwide
            </p>
            <h1 className="mt-4 font-black uppercase leading-[0.92] tracking-tight text-4xl sm:text-5xl lg:text-6xl">
              <span className="text-[#1d2739] block">Play Loud.</span>
              <span className="text-[#b08968] block">Wear The Proof.</span>
            </h1>
            <p className="mt-6 text-sm text-[#515a68] border-t border-[rgba(29,39,57,0.18)] pt-6 max-w-sm">
              {products.length} products for people who back themselves out loud — court kit, fleece, paddles and
              the game-night essentials.
            </p>
            <div className="mt-6 flex flex-wrap gap-3">
              <Link
                href="/shop"
                className="inline-flex items-center justify-center bg-[#b08968] hover:bg-[#8f6d51] text-white text-xs font-bold uppercase tracking-wide px-6 py-3 transition-colors"
              >
                Shop the index
              </Link>
              <Link
                href="/lookbook"
                className="inline-flex items-center justify-center border border-[#1d2739] text-[#1d2739] text-xs font-bold uppercase tracking-wide px-6 py-3 hover:bg-[#1d2739] hover:text-white transition-colors"
              >
                Lookbook
              </Link>
            </div>
          </div>
          <div className="relative min-h-[260px] lg:min-h-full bg-[#f0f2f5] border-t lg:border-t-0 lg:border-l border-[rgba(29,39,57,0.18)] flex items-end justify-end p-4">
            <span className="text-[10px] font-semibold uppercase tracking-wide text-[#6f7885] bg-white/80 px-2 py-1">
              Fig. 01 — Featured drop
            </span>
          </div>
        </div>
      </section>

      <section className="py-10">
        <Container>
          <div className="flex items-baseline justify-between border-b border-[rgba(29,39,57,0.18)] pb-4">
            <h2 className="text-lg font-black uppercase tracking-tight text-[#1d2739]">Collections</h2>
            <p className="text-[11px] font-semibold uppercase tracking-wide text-[#6f7885]">
              By fabric, outfit, gender and age
            </p>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 divide-x divide-y divide-[rgba(29,39,57,0.18)] border-x border-b border-[rgba(29,39,57,0.18)]">
            {tiles.map((tile) => (
              <Link
                key={tile.title}
                href={tile.query ? `/shop?${tile.query}` : "/shop"}
                className={`group block px-6 py-10 transition-colors ${
                  tile.featured ? "bg-[#1d2739] text-white" : "bg-white hover:bg-[#f5f6f8]"
                }`}
              >
                <h3 className={`font-black uppercase text-xl leading-tight ${tile.featured ? "text-white" : "text-[#1d2739]"}`}>
                  {tile.title}
                </h3>
                <p
                  className={`mt-6 text-[10px] font-semibold uppercase tracking-wide ${
                    tile.featured ? "text-white/70" : "text-[#6f7885]"
                  }`}
                >
                  {tile.caption}
                </p>
              </Link>
            ))}
          </div>
        </Container>
      </section>
    </>
  );
}
