import type { Metadata } from "next";
import { getProducts } from "@/lib/db";
import { ProductGrid } from "@/components/ProductGrid";

export const metadata: Metadata = {
  title: "Search",
  robots: { index: false, follow: true },
};

export default function SearchPage({
  searchParams,
}: {
  searchParams: { q?: string };
}) {
  const q = (searchParams.q ?? "").trim();
  const all = getProducts();

  const results = q
    ? all.filter((p) => {
        const haystack = `${p.name} ${p.brand} ${p.category}`.toLowerCase();
        return haystack.includes(q.toLowerCase());
      })
    : all;

  return (
    <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
      <h1 className="font-display text-2xl font-bold text-brand-ink">
        {q ? (
          <>
            Results for &ldquo;{q}&rdquo;{" "}
            <span className="font-normal text-black/45">({results.length})</span>
          </>
        ) : (
          "All products"
        )}
      </h1>

      <div className="mt-7">
        <ProductGrid
          products={results}
          emptyTitle={`No results for "${q}"`}
          emptyDescription="Try checking your spelling, or search by category, e.g. 'phones' or 'laptops'."
        />
      </div>
    </div>
  );
}
