import type { Metadata } from "next";
import { Suspense } from "react";
import { api } from "@/lib/api";
import { buildMetadata } from "@/lib/seo";
import { ItemBrowseClient } from "./item-browse-client";

export async function generateMetadata({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[]>>;
}): Promise<Metadata> {
  const params = await searchParams;

  const category = typeof params.category_slug === "string" ? params.category_slug : undefined;
  const brand = typeof params.brand === "string" ? params.brand : undefined;
  const q = typeof params.q === "string" ? params.q : undefined;
  const page = typeof params.page === "string" ? Number(params.page) : 1;

  // Build a descriptive title from active filters
  const parts: string[] = [];
  if (category) parts.push(category.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()));
  if (brand) parts.push(brand);
  const title = parts.length > 0 ? `${parts.join(" — ")} — Resale Items` : "Browse Resale Items";

  // noindex when there is a search query or when paginated
  const noindex = !!q || page > 1;

  // Canonical always omits page param
  const canonicalParams = new URLSearchParams();
  if (category) canonicalParams.set("category_slug", category);
  if (brand) canonicalParams.set("brand", brand);
  const qs = canonicalParams.toString();
  const canonical = `https://alqove.com/items${qs ? `?${qs}` : ""}`;

  return buildMetadata({
    title,
    description: "Browse thousands of curated resale items from verified stores. Filter by category, brand, size, condition, and more.",
    canonical,
    noindex,
  });
}

export default async function ItemsPage() {
  // Fetch category tree server-side for label resolution in filter sidebar
  const res = await api.categories.list();
  const tree = res.data;

  return (
    <Suspense fallback={<BrowseSkeleton />}>
      <ItemBrowseClient categoryTree={tree} />
    </Suspense>
  );
}

function BrowseSkeleton() {
  return (
    <div className="mx-auto max-w-7xl px-4 py-8">
      <div className="h-8 w-48 animate-pulse rounded bg-slate-200" />
      <div className="mt-6 flex gap-8">
        <div className="w-64 shrink-0 space-y-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-6 animate-pulse rounded bg-slate-200" />
          ))}
        </div>
        <div className="flex-1">
          <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
            {Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="space-y-2">
                <div className="aspect-square w-full animate-pulse rounded bg-slate-200" />
                <div className="h-4 w-3/4 animate-pulse rounded bg-slate-200" />
                <div className="h-4 w-1/2 animate-pulse rounded bg-slate-200" />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
