"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";

export function SearchBar() {
  const router = useRouter();
  const [term, setTerm] = useState("");
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        const q = term.trim();
        router.push(q ? `/search?q=${encodeURIComponent(q)}` : "/search");
      }}
      role="search"
      aria-label="사이트 검색"
      className="relative w-full max-w-[384px]"
    >
      <svg
        width="32"
        height="32"
        viewBox="0 0 32 32"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        aria-hidden
        className="absolute right-2 top-2 w-8 h-8"
      >
        <path
          d="M21 21L17.682 17.682M17.682 17.682C18.4963 16.8676 19 15.7426 19 14.5C19 12.0147 16.9853 10 14.5 10C12.0147 10 10 12.0147 10 14.5C10 16.9853 12.0147 19 14.5 19C15.7426 19 16.8676 18.4963 17.682 17.682ZM28 16C28 22.6274 22.6274 28 16 28C9.37258 28 4 22.6274 4 16C4 9.37258 9.37258 4 16 4C22.6274 4 28 9.37258 28 16Z"
          stroke="#707070"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
      <input
        type="search"
        name="q"
        value={term}
        onChange={(e) => setTerm(e.target.value)}
        placeholder="검색어를 입력해 주세요."
        enterKeyHint="search"
        aria-label="검색어"
        onKeyDown={(e) => {
          if (e.key === "Escape") setTerm("");
        }}
        className="w-full h-12 pr-12 pl-2 rounded-2xl border border-neutral-300 bg-white"
      />
      {/* 접근성용 제출 버튼 (시각적으로는 숨김) */}
      <button type="submit" aria-label="검색" className="sr-only" />
    </form>
  );
}


