import { getProperty, setProperty } from "dot-prop";
import { inject, provide, ref } from "vue";
export const SELF_BINDING = ".";
export const FORM_STATE_KEY = Symbol("shwfed-form-state");
export function provideFormState(state, kind = "form") {
  const parent = inject(FORM_STATE_KEY, void 0);
  const dirty = ref(/* @__PURE__ */ new Set());
  function write(path, value) {
    const normalized = value === void 0 ? null : value;
    if (path === SELF_BINDING) {
      state.value = normalized;
      return;
    }
    const current = state.value;
    setProperty(current, path, normalized);
    state.value = { ...current };
  }
  function markDirty(path) {
    if (!dirty.value.has(path)) dirty.value = new Set(dirty.value).add(path);
  }
  const bag = {
    kind,
    parent,
    state,
    getAt: (path) => path === SELF_BINDING ? state.value : getProperty(state.value, path),
    setAt: (path, value) => {
      write(path, value);
      markDirty(path);
    },
    setAtSilent: write,
    dirty,
    isDirty: (path) => dirty.value.has(path),
    markDirty
  };
  provide(FORM_STATE_KEY, bag);
  return bag;
}
export function useFormState() {
  const bag = inject(FORM_STATE_KEY);
  if (!bag) {
    throw new Error("[shwfed-form] useFormState() called outside a <Form> runtime host");
  }
  return bag;
}
