import { useReducer as K, useMemo as k, useCallback as p } from "../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { useForm as B, getNestedValue as g, setNestedValue as X } from "../useForm.js";
function Z(s, o) {
  switch (o.type) {
    case "SET_STEP":
      return {
        ...s,
        currentStep: o.payload.step,
        visitedSteps: /* @__PURE__ */ new Set([...s.visitedSteps, o.payload.step])
      };
    case "NEXT_STEP": {
      const n = s.currentStep + 1;
      return {
        ...s,
        currentStep: n,
        visitedSteps: /* @__PURE__ */ new Set([...s.visitedSteps, n]),
        completedSteps: /* @__PURE__ */ new Set([...s.completedSteps, s.currentStep])
      };
    }
    case "PREVIOUS_STEP":
      return {
        ...s,
        currentStep: Math.max(0, s.currentStep - 1)
      };
    case "MARK_STEP_COMPLETED":
      return {
        ...s,
        completedSteps: /* @__PURE__ */ new Set([...s.completedSteps, o.payload.step])
      };
    case "MARK_STEP_VISITED":
      return {
        ...s,
        visitedSteps: /* @__PURE__ */ new Set([...s.visitedSteps, o.payload.step])
      };
    case "SET_STEP_VALIDATION": {
      const n = new Map(s.stepValidation);
      return n.set(o.payload.step, o.payload.isValid), {
        ...s,
        stepValidation: n
      };
    }
    case "SET_TRANSITIONING":
      return {
        ...s,
        isTransitioning: o.payload
      };
    case "RESET_WIZARD":
      return {
        currentStep: 0,
        completedSteps: /* @__PURE__ */ new Set(),
        visitedSteps: /* @__PURE__ */ new Set([0]),
        stepValidation: /* @__PURE__ */ new Map(),
        isTransitioning: !1,
        displayValues: /* @__PURE__ */ new Map()
      };
    case "SET_DISPLAY_VALUE": {
      const n = new Map(s.displayValues), { field: c, displayValue: f } = o.payload;
      return f === void 0 ? n.delete(c) : n.set(c, f), { ...s, displayValues: n };
    }
    case "RESET_DISPLAY_VALUES":
      return { ...s, displayValues: /* @__PURE__ */ new Map() };
    default:
      return s;
  }
}
function j(s) {
  const { i18n: o, steps: n, defaultValues: c, mode: f = "onBlur", onStepChange: S, validateBeforeNext: T = !0 } = s, [a, i] = K(Z, {
    currentStep: 0,
    completedSteps: /* @__PURE__ */ new Set(),
    visitedSteps: /* @__PURE__ */ new Set([0]),
    stepValidation: /* @__PURE__ */ new Map(),
    isTransitioning: !1,
    displayValues: /* @__PURE__ */ new Map()
  }), m = B({
    defaultValues: c,
    i18n: o,
    mode: f
  }), { trigger: _, getValues: d, getValueMap: w } = m, E = n.length, P = n[a.currentStep], A = a.currentStep === 0, R = a.currentStep === E - 1, V = !A && !a.isTransitioning, N = !R && !a.isTransitioning, h = k(() => n.flatMap((e) => e.fields).reduce(
    (e, r) => ({ ...e, [r.fieldName]: r }),
    {}
  ), [n]), I = p(
    async (e) => {
      const r = n[e];
      if (!r) return !1;
      if (r.isOptional) {
        const t = d();
        if (!r.fields.some(({ fieldName: Y }) => {
          const v = g(t, Y);
          return v !== void 0 && v !== "" && v !== null;
        })) return !0;
      }
      const u = r.fields.filter(({ visible: t }) => t).map(({ fieldName: t }) => t), l = await _(u);
      if (l && r.validate) {
        const t = d();
        return await r.validate(t);
      }
      return l;
    },
    [n, d, _]
  ), y = p(async () => {
    const e = await I(a.currentStep);
    return i({
      type: "SET_STEP_VALIDATION",
      payload: { step: a.currentStep, isValid: e }
    }), e;
  }, [a.currentStep, I]), M = p(
    (e) => a.stepValidation.get(e) ?? !1,
    [a.stepValidation]
  ), O = p(
    (e) => a.completedSteps.has(e),
    [a.completedSteps]
  ), D = p(
    async (e, r) => {
      if (e < 0 || e >= E)
        throw new Error(`Invalid step index: ${e}`);
      if (!r?.skipValidation && T && e > a.currentStep) {
        i({ type: "SET_TRANSITIONING", payload: !0 });
        try {
          if (!await y())
            return i({ type: "SET_TRANSITIONING", payload: !1 }), !1;
          i({ type: "MARK_STEP_COMPLETED", payload: { step: a.currentStep } });
        } catch (l) {
          return i({ type: "SET_TRANSITIONING", payload: !1 }), console.error("Wizard step validation failed:", l), !1;
        }
      }
      const u = a.currentStep;
      return i({ type: "SET_STEP", payload: { step: e } }), i({ type: "SET_TRANSITIONING", payload: !1 }), S && S(e, u), !0;
    },
    [E, T, a.currentStep, y, S]
  ), L = p(async () => {
    if (!N) return !1;
    if (i({ type: "SET_TRANSITIONING", payload: !0 }), T)
      try {
        if (!await y())
          return i({ type: "SET_TRANSITIONING", payload: !1 }), !1;
      } catch (r) {
        return console.error("Wizard step validation failed on nextStep:", r), i({ type: "SET_TRANSITIONING", payload: !1 }), !1;
      }
    const e = a.currentStep;
    return i({ type: "NEXT_STEP" }), i({ type: "SET_TRANSITIONING", payload: !1 }), S && S(e + 1, e), !0;
  }, [N, T, y, a.currentStep, S]), G = p(() => {
    if (!V) return;
    const e = a.currentStep;
    i({ type: "PREVIOUS_STEP" }), S && S(e - 1, e);
  }, [V, a.currentStep, S]), C = p(() => {
    i({ type: "RESET_WIZARD" });
  }, []), F = p((e, r) => {
    i({ type: "SET_DISPLAY_VALUE", payload: { field: e, displayValue: r } });
  }, []), x = p(() => {
    i({ type: "RESET_DISPLAY_VALUES" });
  }, []), z = p(() => {
    const e = d(), r = {};
    return n.forEach((u) => {
      const l = u.fields.filter((t) => t.visible !== !1).map((t) => ({
        label: t.label,
        value: g(e, t.fieldName),
        id: t.fieldName,
        displayValue: a.displayValues.get(t.fieldName)
      })).filter((t) => t.value !== void 0 && t.value !== null && t.value !== "");
      l.length > 0 && (r[u.id] = {
        title: u.title,
        fields: l
      });
    }), r;
  }, [n, d, a.displayValues]), U = p(() => {
    const e = w(), r = {}, u = /* @__PURE__ */ new Set();
    n.forEach((l) => {
      l.fields.forEach((t) => {
        t.includeInApiPayload === !1 && u.add(t.fieldName);
      });
    });
    for (const [l, t] of e)
      u.has(l) || t != null && t !== "" && X(r, l, t);
    return r;
  }, [n, w]), W = p(
    (e) => a.displayValues.get(e),
    [a.displayValues]
  );
  return {
    ...m,
    // Wizard state
    currentStep: a.currentStep,
    currentStepConfig: P,
    isFirstStep: A,
    isLastStep: R,
    canGoNext: N,
    canGoPrevious: V,
    fieldsConfig: h,
    // Navigation methods
    goToStep: D,
    nextStep: L,
    previousStep: G,
    resetWizard: C,
    // Validation methods
    validateStep: I,
    isStepValid: M,
    isStepComplete: O,
    // Summary data
    getSummaryData: z,
    getApiPayloadValues: U,
    // Display values
    getDisplayValue: W,
    setFieldDisplayValue: F,
    resetFieldDisplayValues: x
  };
}
export {
  j as useWizardForm
};
