import { assertReflexAction as c, unwrap as a } from "./helpers.js";
import { $globalReflexRegister as x } from "./register.js";
import { REF as _ } from "./constants.js";
import { struct as p } from "../../../utils/struct/main.js";
import { sameValue as m } from "../../../utils/value/compare.js";
import { isNullish as b } from "../../../utils/value/is.js";
const v = (n) => {
  c(n);
  const r = new WeakMap([[n, 1]]), e = ((o) => {
    if (m(t, o)) return;
    const u = t;
    n(t = o, u);
  });
  let t = null;
  return Object.defineProperties(e, {
    [_]: { value: e },
    actions: {
      value: p({
        get: { value: r.get.bind(r) },
        size: { value: 1 }
      })
    },
    current: {
      get: () => t,
      set: e
    }
  });
}, $ = (n = x) => {
  let r, e = null, t, o = !1;
  const u = (l) => {
    r = void 0, e = null, t = l, o = !1;
  }, d = () => {
    o || (f(), o = !0);
  }, f = () => {
    try {
      if (!e) return;
      n.unbind(e, t);
    } catch {
    }
  };
  return p({
    action: { get: () => t },
    reflex: { get: () => r },
    release: { value: d },
    update: { value: (l, s) => {
      c(l), o && u(l);
      const i = b(s) ? null : s;
      if (t === l && e === i) {
        if (r) return;
      } else if (e) {
        if (m(a(e), a(i))) {
          r = n.bind(e, l), f(), t = l;
          return;
        }
        f();
      }
      t = l, e = i, r = e ? n.bind(e, t) : v(t);
    } }
  });
};
export {
  v as createIsolatedFauxReflex,
  $ as createReflexContainer
};
