import { watch } from "vue";
const STORAGE_PREFIX = "shwfed.table.query.";
export function usePersistedQuery(tableId, queryState, enabled) {
  const active = () => Boolean(tableId) && enabled() && typeof window !== "undefined";
  const key = () => `${STORAGE_PREFIX}${tableId}`;
  function restore() {
    if (!active()) return;
    try {
      const raw = window.sessionStorage.getItem(key());
      if (!raw) return;
      const parsed = JSON.parse(raw);
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
        queryState.value = parsed;
      }
    } catch {
    }
  }
  function clear() {
    if (!tableId || typeof window === "undefined") return;
    try {
      window.sessionStorage.removeItem(key());
    } catch {
    }
  }
  watch(queryState, (next) => {
    if (!active()) return;
    try {
      window.sessionStorage.setItem(key(), JSON.stringify(next));
    } catch {
    }
  }, { deep: true });
  return { restore, clear };
}
