"use client";

import * as React from "react";
import { Search, X } from "lucide-react";
import { cn } from "@/lib/utils";

export interface SearchBarProps {
  placeholder?: string;
  onSearch?: (query: string) => void;
  className?: string;
  autoFocus?: boolean;
}

/**
 * Site search — Sprint 2 §16. A utility-row control, not a hero-level element;
 * navigation and mega menus should make this unnecessary for most visits.
 */
export function SearchBar({ placeholder = "Search ROPTS", onSearch, className, autoFocus }: SearchBarProps) {
  const [query, setQuery] = React.useState("");

  return (
    <form
      role="search"
      onSubmit={(e) => {
        e.preventDefault();
        onSearch?.(query);
      }}
      className={cn(
        "flex items-center gap-2 rounded border border-line bg-paper px-3.5 focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/30",
        className
      )}
    >
      <Search className="size-4 text-slate" aria-hidden="true" />
      <label htmlFor="site-search" className="sr-only">
        Search
      </label>
      <input
        id="site-search"
        type="search"
        value={query}
        autoFocus={autoFocus}
        onChange={(e) => setQuery(e.target.value)}
        placeholder={placeholder}
        className="h-11 w-full bg-transparent text-body-sm text-ink placeholder:text-slate-muted focus:outline-none"
      />
      {query && (
        <button
          type="button"
          onClick={() => setQuery("")}
          aria-label="Clear search"
          className="rounded p-1 text-slate hover:text-primary"
        >
          <X className="size-4" />
        </button>
      )}
    </form>
  );
}
