"use client" import { useMemo } from "react" import { useSearchParams } from "next/navigation" import { readUptimeUrl, readResourceUrl, patchUptimeUrl, type ResourceTypeFilter, type UptimeTab, type ProbeStatusFilter, type UrlSetter } from "@/lib/data-filters/uptime-url-state" export function useUptimeUrlState() { const raw = useSearchParams().toString() const state = useMemo(() => readUptimeUrl(new URLSearchParams(raw)), [raw]) const resource = useMemo(() => readResourceUrl(new URLSearchParams(raw)), [raw]) function write(changes: Record, replace = false) { const href = patchUptimeUrl(new URLSearchParams(window.location.search), changes) + window.location.hash if (href === window.location.pathname + window.location.search + window.location.hash) return if (replace) window.history.replaceState(null, "", href) else window.history.pushState(null, "", href) } const setStatusFilter: UrlSetter = value => { const current = readUptimeUrl(new URLSearchParams(window.location.search)).status const next = typeof value === "function" ? value(current) : value write({ status: next === "all" ? null : next }) } const setServerFilter: UrlSetter = value => { const current = readUptimeUrl(new URLSearchParams(window.location.search)).servers const next = typeof value === "function" ? value(current) : value write({ servers: next.length ? JSON.stringify(next) : null }) } return { resource, setResourceSearch: (rq: string) => write({ rq }, true), setResourceType: (type: ResourceTypeFilter) => write({ rtype: type === "all" ? null : type }), resetResources: () => write({ rq: null, rtype: null }), tab: state.tab, search: state.search, statusFilter: state.status, serverFilter: state.servers, error: state.error, setTab: (tab: UptimeTab) => write({ tab: tab === "probes" ? null : tab }), setSearch: (q: string) => write({ q }, true), setStatusFilter, setServerFilter, resetFilters: () => write({ q: null, status: null, servers: null }), resetUrl: () => write({ tab: null, q: null, status: null, servers: null }), } }