/**
 * Trouve-KA — barre de recherche (homepage et en-tête des résultats)
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import { useRouter } from "next/navigation";
import { useEffect, useState, type FormEvent } from "react";
import { cn } from "@/lib/utils";

interface SearchBarProps {
  initialQuery?: string;
  autoFocus?: boolean;
  size?: "md" | "lg";
  /** `inline` : bouton dans la barre; `below` : grand bouton sous la barre. */
  buttonPlacement?: "inline" | "below";
  /** Suggestions québécoises affichées en placeholder, en rotation douce. */
  placeholderSuggestions?: string[];
  className?: string;
}

const SUGGESTION_INTERVAL_MS = 4000;

export function SearchBar({
  initialQuery = "",
  autoFocus = false,
  size = "md",
  buttonPlacement = "inline",
  placeholderSuggestions,
  className,
}: SearchBarProps) {
  const router = useRouter();
  const [query, setQuery] = useState(initialQuery);
  const [suggestionIndex, setSuggestionIndex] = useState(0);

  const suggestionCount = placeholderSuggestions?.length ?? 0;

  useEffect(() => {
    if (suggestionCount < 2) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const timer = window.setInterval(
      () => setSuggestionIndex((index) => (index + 1) % suggestionCount),
      SUGGESTION_INTERVAL_MS,
    );
    return () => window.clearInterval(timer);
  }, [suggestionCount]);

  const placeholder =
    suggestionCount > 0
      ? `Essaie « ${placeholderSuggestions![suggestionIndex % suggestionCount]} »…`
      : "Rechercher…";

  function onSubmit(event: FormEvent) {
    event.preventDefault();
    const q = query.trim();
    if (!q) return;
    router.push(`/search?q=${encodeURIComponent(q)}`);
  }

  const isLarge = size === "lg";

  return (
    <form role="search" onSubmit={onSubmit} className={cn("w-full", className)}>
      <label htmlFor="champ-recherche" className="sr-only">
        Rechercher sur le web québécois
      </label>
      <div className="relative">
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          className={cn(
            "pointer-events-none absolute top-1/2 -translate-y-1/2 text-ink-3",
            isLarge ? "left-5 h-5 w-5" : "left-3.5 h-4 w-4",
          )}
        >
          <circle cx="11" cy="11" r="8" />
          <path d="m21 21-4.35-4.35" />
        </svg>
        <input
          id="champ-recherche"
          type="search"
          name="q"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          placeholder={placeholder}
          autoComplete="off"
          spellCheck={false}
          // eslint-disable-next-line jsx-a11y/no-autofocus
          autoFocus={autoFocus}
          className={cn(
            "field appearance-none",
            isLarge ? "h-14 pl-12 text-lg" : "h-10 pl-10 text-sm",
            buttonPlacement === "inline"
              ? isLarge
                ? "pr-32"
                : "pr-28"
              : isLarge
                ? "pr-6"
                : "pr-4",
          )}
        />
        {buttonPlacement === "inline" ? (
          <button
            type="submit"
            className={cn(
              "gk-display absolute right-1.5 top-1/2 -translate-y-1/2 rounded-[5px] border-[1.5px] border-ink bg-ink font-bold text-lime transition-colors hover:bg-green-deep active:translate-y-[calc(-50%+1px)]",
              isLarge ? "h-11 px-6 text-base" : "h-7 px-4 text-[13px]",
            )}
          >
            Chercher
          </button>
        ) : null}
      </div>
      {buttonPlacement === "below" ? (
        <button type="submit" className="btn btn-primary mt-8 px-9">
          Chercher
        </button>
      ) : null}
    </form>
  );
}
