import { useCallback, useState } from 'react';
import { useSyncedRef } from '../useSyncedRef/index.js';
import { resolveHookState } from '../util/resolveHookState.js';
export function useMediatedState(initialState, mediator) {
    const [state, setState] = useState(() => {
        return mediator ? mediator(resolveHookState(initialState)) : initialState;
    });
    const mediatorRef = useSyncedRef(mediator);
    return [
        state,
        useCallback((value) => {
            if (mediatorRef.current) {
                setState((previousState) => mediatorRef.current?.(resolveHookState(value, previousState)));
            }
            else {
                setState(value);
            }
        }, []),
    ];
}
