"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Segmented } from "./ui";

/** Date range control that writes ?days= into the URL so server components re-render with the filter. */
export function RangePicker({ options = [7, 30, 90] }: { options?: number[] }) {
  const router = useRouter();
  const path = usePathname();
  const sp = useSearchParams();
  const days = sp.get("days") ?? "30";
  return (
    <Segmented value={days} onChange={(v) => { const q = new URLSearchParams(sp); q.set("days", v); router.push(`${path}?${q}`); }}
      options={options.map((d) => ({ value: String(d), label: `${d}d` }))} />
  );
}

export function QuerySelect({ name, options, placeholder }: { name: string; options: { value: string; label: string }[]; placeholder: string }) {
  const router = useRouter();
  const path = usePathname();
  const sp = useSearchParams();
  return (
    <select className="field w-auto py-1 text-[12.5px]" value={sp.get(name) ?? ""} onChange={(e) => { const q = new URLSearchParams(sp); if (e.target.value) q.set(name, e.target.value); else q.delete(name); router.push(`${path}?${q}`); }}>
      <option value="">{placeholder}</option>
      {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
    </select>
  );
}
