;
{
  try {
    let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
    n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "f0e672b5-bb9d-4875-bd97-dc90ab220fbe", e._sentryDebugIdIdentifier = "sentry-dbid-f0e672b5-bb9d-4875-bd97-dc90ab220fbe");
  } catch (e) {
  }
}
;
import { useState, useEffect, useMemo } from "preact/hooks";
import { p as useAnalyticsContext, a3 as createLogger } from "./StoreProvider-CqQrndhS.js";
import { s as summaryStep } from "./Summary-6z7-keBb.js";
import { t as trackNavigation } from "./trackNavigation-db_h46BT.js";
import { jsx } from "preact/jsx-runtime";
import { F as FormRouterContext } from "./ErrorPanel-D-VMcBB9.js";
import { f as formDebugInfo } from "./debugStore-BvbyN1Oi.js";
const getOpeningStep = (forms, remediationActions) => {
  if (remediationActions && Object.keys(remediationActions).length > 0) {
    const allRemediationActions = Object.values(remediationActions).flat().filter((rem) => rem.forms?.length > 0);
    if (allRemediationActions.length === 1 && allRemediationActions[0]?.forms.length === 1) {
      const form = forms.find((form2) => form2?.formId === allRemediationActions[0]?.forms[0]);
      if (form) return form;
    }
    return forms[forms.length - 1];
  }
  return forms[0];
};
const useFormComposer = ({
  problems,
  navigationTrackingParams,
  forms,
  externalBackClick,
  onSubmit,
  triggerValidation
}) => {
  const userEvents = useAnalyticsContext();
  const [shouldValidate, setShouldValidate] = useState(false);
  const [activeForm, setActiveForm] = useState(forms[0]);
  const isFormSummaryStep = (form) => form.formId === summaryStep.formId;
  const getFormIndex = (formId) => forms.findIndex((form) => form.formId === formId);
  const currentStep = getFormIndex(activeForm.formId);
  const totalSteps = forms.length;
  const isFinalStep = currentStep === totalSteps - 1;
  const isFirstStep = currentStep === 0;
  const firstStepId = forms[0]?.formId;
  useEffect(() => {
    setActiveForm(
      (activeForm2) => forms.find(({ formId }) => formId === activeForm2.formId) ?? activeForm2
    );
  }, [forms]);
  useEffect(() => {
    userEvents.updateSharedEventProperties({ page: activeForm?.formName });
  }, [activeForm?.formName]);
  useEffect(() => {
    const openingStep = getOpeningStep(forms, problems?.remediationActions);
    setActiveForm(openingStep);
  }, [firstStepId, problems?.remediationActions]);
  const gotoFormByFormIndex = (nextFormIndex, currentForms) => {
    setActiveForm(currentForms?.[nextFormIndex] ?? forms[nextFormIndex]);
  };
  const trackSubmitClick = () => {
    trackNavigation({
      userEvents,
      actionType: "submit",
      label: "submit",
      additionalTrackingParams: navigationTrackingParams
    });
  };
  const handleNextClick = async (updatedForms) => {
    const currentForms = updatedForms ?? forms;
    if (isFormSummaryStep(activeForm)) {
      trackSubmitClick();
      onSubmit();
      return;
    }
    const isAsyncValidationValid = await triggerValidation?.(activeForm.formId) ?? true;
    if (!activeForm.isValid || !isAsyncValidationValid) {
      setShouldValidate(true);
      trackNavigation({
        userEvents,
        actionType: "next",
        label: "next",
        returnValue: "validation error",
        additionalTrackingParams: navigationTrackingParams
      });
      return;
    }
    if (isFinalStep) {
      trackSubmitClick();
      onSubmit();
      return;
    }
    setShouldValidate(false);
    const toFormIndex = currentStep + 1;
    gotoFormByFormIndex(toFormIndex, currentForms);
    trackNavigation({
      userEvents,
      actionType: "next",
      toForm: currentForms[toFormIndex]?.formName,
      label: "next",
      returnValue: "success",
      additionalTrackingParams: navigationTrackingParams
    });
  };
  const handleBackClick = () => {
    if (currentStep > 0) {
      const toForm = forms[currentStep - 1];
      setActiveForm(toForm);
      trackNavigation({
        userEvents,
        actionType: "back",
        toForm: toForm?.formName,
        label: "back",
        additionalTrackingParams: navigationTrackingParams
      });
    }
  };
  const backClickHandler = isFirstStep ? externalBackClick : handleBackClick;
  return {
    handleBackClick: backClickHandler,
    handleNextClick,
    gotoFormByFormIndex,
    activeForm,
    shouldValidate,
    setShouldValidate,
    steps: { current: currentStep, total: totalSteps }
  };
};
const logger = createLogger();
function FormRouterContextProvider({ children, forms, setFormIndex }) {
  const contextValue = useMemo(
    () => ({
      setFormIndex,
      goToFormByFieldName: (fieldName) => {
        if (fieldName === "idDocument") {
          fieldName = "idVerificationMethod";
        }
        const formIndex = forms.findIndex(
          (form) => form?.fields?.some((field) => field === fieldName)
        );
        if (formIndex > -1) {
          setFormIndex(formIndex);
        } else {
          logger.error("No form was found to have that field so form navigation failed.");
        }
      }
    }),
    [forms, setFormIndex]
  );
  return /* @__PURE__ */ jsx(FormRouterContext.Provider, { value: contextValue, children });
}
const getRequiredForms = (forms, requiredFields, optionalFields, skipSummary) => {
  const reasons = [];
  const requiredForms = Object.values(forms).filter(({ formId }) => {
    if (requiredFields || optionalFields) {
      const hasRequired = Boolean(requiredFields?.[formId]?.length);
      const hasOptional = Boolean(optionalFields?.[formId]?.length);
      const isIncluded = hasRequired || hasOptional;
      const inclusionReasons = [];
      if (hasRequired) {
        inclusionReasons.push("has required fields");
      }
      if (hasOptional) {
        inclusionReasons.push("has optional fields");
      }
      if (isIncluded) {
        reasons.push(`Form '${formId}': INCLUDED (${inclusionReasons.join(" & ")})`);
      } else {
        reasons.push(`Form '${formId}': EXCLUDED (no required or optional fields)`);
      }
      return isIncluded;
    }
    reasons.push(`Form '${formId}': INCLUDED (no required/optional fields check)`);
    return true;
  });
  formDebugInfo.value = {
    ...formDebugInfo.value,
    __FORMS__: {
      status: "INFO",
      reasons
    }
  };
  if (skipSummary) {
    return requiredForms;
  }
  return [...requiredForms, summaryStep];
};
const addValidityToForms = (forms, formValidity, problems) => forms.map(({ formId, formName, fields }) => ({
  formId,
  formName,
  fields,
  isValid: formValidity?.[formId] ?? false,
  hasServerValidationErrors: Boolean(problems?.validationErrors?.[formId])
}));
export {
  FormRouterContextProvider as F,
  addValidityToForms as a,
  getRequiredForms as g,
  useFormComposer as u
};
