import type { Metadata } from "next";

import { ProductsExplorer } from "@/components/products/ProductsExplorer";
import { getCatalogFacets } from "@/lib/products";
import { parseSearchParams } from "@/lib/search-utils";

export const metadata: Metadata = {
  title: "Products",
  description:
    "Search the ApnaBazaar catalogue by meaning. Results are ranked with vector similarity and keyword relevance.",
};

/**
 * Product listing.
 *
 * The URL is read once, on the server, to seed the client's initial state. After
 * that the client keeps the URL in step with `history.replaceState`, so typing
 * never re-runs this server component.
 */
export default async function ProductsPage({ searchParams }: PageProps<"/products">) {
  const resolved = await searchParams;
  const parsed = parseSearchParams(new URLSearchParams(resolveSearchParams(resolved)));
  const initial = parsed.ok
    ? parsed.value
    : { query: "", filters: {}, sort: "relevance" as const, limit: 24 };

  const facets = await getCatalogFacets();

  return (
    <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
      <header className="mb-6 max-w-2xl">
        <h1 className="text-2xl font-bold tracking-tight text-slate-900 sm:text-3xl">
          Search the catalogue
        </h1>
        <p className="mt-2 text-sm text-slate-600 sm:text-base">
          Search by meaning, not just keywords. Every product is embedded once and stored as a
          vector, so a query like{" "}
          <span className="font-medium text-slate-800">“headphones for travelling”</span> finds
          products that never use the word &ldquo;travelling&rdquo;.
        </p>
      </header>

      <ProductsExplorer
        facets={facets}
        initialQuery={initial.query}
        initialFilters={initial.filters}
        initialSort={initial.sort}
      />
    </div>
  );
}

/** `searchParams` values are `string | string[] | undefined`; take the first. */
function resolveSearchParams(
  params: Record<string, string | string[] | undefined>,
): Record<string, string> {
  const resolved: Record<string, string> = {};
  for (const [key, value] of Object.entries(params)) {
    if (typeof value === "string") resolved[key] = value;
    else if (Array.isArray(value) && typeof value[0] === "string") resolved[key] = value[0];
  }
  return resolved;
}
