"use client";

import * as React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

/**
 * Liest und schreibt die Such-/Filter-Parameter in die URL-Query OHNE Reload
 * (`router.replace`, scroll: false). Textänderungen werden debounced, damit die
 * URL nicht bei jedem Tastendruck neu geschrieben wird. Die URL ist die einzige
 * Quelle der Wahrheit (teilbar, reload-stabil — Plan WS5 Verifikation 9).
 */
export function useSearchUrl(debounceMs = 350) {
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  const current = React.useMemo(
    () => new URLSearchParams(params?.toString() ?? ""),
    [params],
  );

  const commit = React.useCallback(
    (next: URLSearchParams) => {
      const qs = next.toString();
      router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
    },
    [router, pathname],
  );

  /** Setzt (oder entfernt bei null/leer) einen Parameter sofort. */
  const setParam = React.useCallback(
    (key: string, value: string | null) => {
      const next = new URLSearchParams(current.toString());
      if (value === null || value === "") next.delete(key);
      else next.set(key, value);
      commit(next);
    },
    [current, commit],
  );

  /** Setzt mehrere Parameter atomar (verhindert Race über stale `current`). */
  const setParams = React.useCallback(
    (entries: Record<string, string | null>) => {
      const next = new URLSearchParams(current.toString());
      for (const [key, value] of Object.entries(entries)) {
        if (value === null || value === "") next.delete(key);
        else next.set(key, value);
      }
      commit(next);
    },
    [current, commit],
  );

  /** Wie setParam, aber debounced (für Texteingaben). */
  const setParamDebounced = React.useCallback(
    (key: string, value: string | null) => {
      if (timer.current) clearTimeout(timer.current);
      const snapshot = new URLSearchParams(current.toString());
      timer.current = setTimeout(() => {
        if (value === null || value === "") snapshot.delete(key);
        else snapshot.set(key, value);
        commit(snapshot);
      }, debounceMs);
    },
    [current, commit, debounceMs],
  );

  /** Entfernt alle `f.*`-Filter sowie `bereit`, behält `q` und Standort. */
  const resetFilters = React.useCallback(() => {
    const next = new URLSearchParams();
    const q = current.get("q");
    const lat = current.get("lat");
    const lng = current.get("lng");
    if (q) next.set("q", q);
    if (lat) next.set("lat", lat);
    if (lng) next.set("lng", lng);
    commit(next);
  }, [current, commit]);

  React.useEffect(() => {
    return () => {
      if (timer.current) clearTimeout(timer.current);
    };
  }, []);

  return { params: current, setParam, setParams, setParamDebounced, resetFilters };
}
