"use client";
import * as React from "react";
import { createEmptyCondition, getDefaultOperator, normalizeAdvancedFilterState } from "@open-mercato/shared/lib/query/advanced-filter";
import { treeReducer } from "../filters/treeReducer.js";
import { validateTreeForApply } from "../filters/filterValidation.js";
function useAdvancedFilter({ fields, onChange }) {
  const [state, setState] = React.useState({
    logic: "and",
    conditions: []
  });
  const updateState = React.useCallback((next) => {
    const normalized = normalizeAdvancedFilterState(next);
    setState(normalized);
    onChange?.(normalized);
  }, [onChange]);
  const addCondition = React.useCallback(() => {
    const newCondition = createEmptyCondition();
    if (fields.length > 0) {
      newCondition.field = fields[0].key;
      newCondition.operator = getDefaultOperator(fields[0].type);
    }
    updateState({
      ...state,
      conditions: [...state.conditions, newCondition]
    });
  }, [fields, state, updateState]);
  const removeCondition = React.useCallback((conditionId) => {
    updateState({
      ...state,
      conditions: state.conditions.filter((c) => c.id !== conditionId)
    });
  }, [state, updateState]);
  const updateCondition = React.useCallback((conditionId, updates) => {
    updateState({
      ...state,
      conditions: state.conditions.map(
        (c) => c.id === conditionId ? { ...c, ...updates } : c
      )
    });
  }, [state, updateState]);
  const toggleLogic = React.useCallback(() => {
    const nextLogic = state.logic === "and" ? "or" : "and";
    updateState({
      logic: nextLogic,
      conditions: state.conditions.map((condition, index) => index === 0 ? condition : { ...condition, join: nextLogic })
    });
  }, [state, updateState]);
  const clearAll = React.useCallback(() => {
    updateState({ logic: "and", conditions: [] });
  }, [updateState]);
  const hasActiveConditions = state.conditions.some((c) => c.field && c.operator);
  return {
    state,
    setState: updateState,
    addCondition,
    removeCondition,
    updateCondition,
    toggleLogic,
    clearAll,
    hasActiveConditions
  };
}
function useAdvancedFilterTree({
  initial,
  fields,
  onApply,
  debounceMs = 400
}) {
  const [tree, setTree] = React.useState(initial);
  const [appliedTree, setAppliedTree] = React.useState(initial);
  const [pendingErrors, setPendingErrors] = React.useState([]);
  const timerRef = React.useRef(null);
  const didMountRef = React.useRef(false);
  const onApplyRef = React.useRef(onApply);
  const fieldsRef = React.useRef(fields);
  React.useEffect(() => {
    onApplyRef.current = onApply;
  }, [onApply]);
  React.useEffect(() => {
    fieldsRef.current = fields;
  }, [fields]);
  const tryApply = React.useCallback((candidate) => {
    const result = validateTreeForApply(candidate, fieldsRef.current);
    if (result.ok) {
      setPendingErrors([]);
      setAppliedTree(candidate);
      onApplyRef.current?.(candidate);
      return true;
    }
    setPendingErrors(result.errors);
    return false;
  }, []);
  React.useEffect(() => {
    if (!didMountRef.current) {
      didMountRef.current = true;
      return;
    }
    if (timerRef.current) clearTimeout(timerRef.current);
    const timer = setTimeout(() => {
      tryApply(tree);
    }, debounceMs);
    timerRef.current = timer;
    return () => clearTimeout(timer);
  }, [tree, debounceMs, tryApply]);
  const dispatch = React.useCallback((action) => {
    setTree((prev) => treeReducer(prev, action));
  }, []);
  const flush = React.useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    tryApply(tree);
  }, [tree, tryApply]);
  const clear = React.useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    setTree((prev) => {
      const emptied = { root: { ...prev.root, children: [] } };
      setAppliedTree(emptied);
      return emptied;
    });
    setPendingErrors([]);
    onApplyRef.current?.({ root: { id: "", type: "group", combinator: "and", children: [] } });
  }, []);
  const replaceTree = React.useCallback((next) => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    setTree(next);
    setAppliedTree(next);
    setPendingErrors([]);
    onApplyRef.current?.(next);
  }, []);
  const hasActiveRules = tree.root.children.length > 0;
  return { tree, appliedTree, setTree, dispatch, pendingErrors, flush, clear, replaceTree, hasActiveRules };
}
export {
  useAdvancedFilter,
  useAdvancedFilterTree
};
//# sourceMappingURL=useAdvancedFilter.js.map
