import { useReducer as S, useRef as y, useEffect as R, useCallback as d } from "../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
function C({ name: t, control: e, rules: u, render: g }) {
  const [, a] = S((r) => r + 1, 0), { required: c } = u ?? {}, f = y(c);
  R(() => {
    const r = e.subscribe(() => {
      a();
    });
    let s = () => {
    };
    if (u && (s = e.register(t, u)), f.current !== c) {
      f.current = c;
      const i = e.getFieldState(t);
      i.isTouched && i.error && e.trigger(t);
    }
    return () => {
      r(), s();
    };
  }, [e, t, u, c]);
  const b = e.getValue(t), h = e.getFieldState(t), l = e.getFormState(), p = d(
    (r) => {
      let s = r;
      if (r && typeof r == "object" && "target" in r) {
        const i = r.target;
        switch (i.type) {
          case "checkbox":
            s = i.checked;
            break;
          case "file":
            s = i.files;
            break;
          case "select-multiple":
            s = Array.from(i.selectedOptions, (o) => o.value);
            break;
          default:
            s = i.value;
        }
      }
      e.setValue(t, s);
    },
    [e, t]
  ), k = d(() => {
    e.setTouched(t, !0), e.trigger(t);
  }, [e, t]), n = d(() => {
    e.trigger(t);
  }, [e, t]);
  return g({
    field: {
      name: t,
      value: b,
      onInput: p,
      onBlur: k,
      triggerValidation: n
    },
    fieldState: h,
    formState: l
  });
}
export {
  C as Controller
};
