"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useTransition } from "react";

export function SearchBar({ defaultValue = "" }: { defaultValue?: string }) {
  const router = useRouter();
  const params = useSearchParams();
  const [, startTransition] = useTransition();

  return (
    <form
      className="relative w-full max-w-md"
      onSubmit={(e) => {
        e.preventDefault();
        const fd = new FormData(e.currentTarget);
        const q = String(fd.get("q") ?? "").trim();
        const next = new URLSearchParams(params.toString());
        if (q) next.set("q", q);
        else next.delete("q");
        startTransition(() => {
          router.push(`/?${next.toString()}#library`);
        });
      }}
    >
      <input
        name="q"
        type="search"
        defaultValue={defaultValue}
        placeholder="Search games…"
        className="w-full border border-line bg-elevated/80 px-4 py-3 text-sm text-foreground outline-none placeholder:text-muted focus:border-accent"
      />
    </form>
  );
}
