// components/listing/SearchBar.jsx
"use client";

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

export default function SearchBar({ setLoading }) {
  const [keyword, setKeyword] = useState("");
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    const existing = searchParams.get("titleKeyword");
    if (existing) setKeyword(existing);
  }, []);

  useEffect(() => {
    const delay = setTimeout(() => {
      const params = new URLSearchParams(searchParams.toString());
      if (keyword) {
        params.set("titleKeyword", keyword);
      } else {
        params.delete("titleKeyword");
      }
      params.set("page", 0);
      setLoading(true); // 👈 trigger before route change
      router.replace(`/find-trucks?${params.toString()}`);
    }, 50);
    return () => clearTimeout(delay);
  }, [keyword]);

  return (
    <input
      type="text"
      placeholder="Search by keyword, title"
      className="w-full md:w-96 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
      value={keyword}
      onChange={(e) => setKeyword(e.target.value)}
    />
  );
}
