import { n as useTranslation } from "./i18n-DoP1NB7u.js";
import { d as T, m as g, v as u } from "./vendor-preact-DThS2ZQ_.js";
import { c as useManager, o as useModuleTerminalCallbacks } from "./hooks-Da_yP_Dr.js";
import { t as IncodeComponent } from "./incodeComponent-CCP7GTMj.js";
import { r as Spacer } from "./loadingIcon-B0ysgiNq.js";
import { t as Page } from "./page-DidH_RkX.js";
import { t as Button } from "./button-BMYTQ8fc.js";
import { t as VerificationResult } from "./verificationResult-Brj8WSyW.js";
import { t as InputComposed } from "./inputComposed-C1R2LAa3.js";
import { n as countries, t as PhoneInputComposed } from "./phoneInputComposed-BD2JzJM1.js";
import { t as DropdownComposed } from "./dropdownComposed-ZdNkbyDs.js";
import { t as DateInputComposed } from "./dateInputComposed-DuaofcBl.js";
import { t as registerIncodeModuleElement } from "./incodeModule-M8DszCee.js";
import { n as getRequiredHintMode, t as getFieldHint } from "./requiredLabelHint-DX3oVNtu.js";
import { t as EmailInput } from "./emailInput-BymMe0f7.js";
import { formatCPF, isValidCPF } from "@incodetech/core/cpf-ocr";
import { createDynamicFormsManager } from "@incodetech/core/dynamic-forms";
//#region src/modules/dynamic-forms/dynamicForms.tsx
function getEffectiveType(question) {
	return question.inputType ?? question.overrides ?? "TEXT";
}
function getAutocompleteToken(type) {
	switch (type) {
		case "NAME": return "name";
		case "PHONE": return "tel";
		case "DATE": return "bday";
		default: return;
	}
}
var QuestionInput = ({ question, value, disabled = false, error, labelHint, onChange, onFormatValidityChange, onBlur }) => {
	const { t } = useTranslation();
	const effectiveType = getEffectiveType(question);
	const id = `dynamic-form-${question.questionId}`;
	const label = question.question;
	const isRequired = !question.isOptional;
	const autocomplete = getAutocompleteToken(effectiveType);
	const isCountryField = effectiveType === "COUNTRY" || effectiveType === "NATIONALITY";
	const countryOptions = T(() => isCountryField ? countries.map((c) => ({
		value: c.code,
		label: `${c.emoji} ${c.name}`,
		ariaLabel: c.name
	})) : [], [isCountryField]);
	if (effectiveType === "YESNO") {
		const yesNoOptions = [{
			value: "YES",
			label: t("common.yes")
		}, {
			value: "NO",
			label: t("common.no")
		}];
		return /* @__PURE__ */ u("div", {
			class: "IncodeDynamicFormsField",
			children: /* @__PURE__ */ u(DropdownComposed, {
				id,
				name: question.questionId,
				label,
				labelHint,
				value,
				options: yesNoOptions,
				required: isRequired,
				error,
				disabled,
				onChange: (val) => onChange(question.questionId, val),
				onBlur: () => onBlur?.(question.questionId)
			})
		});
	}
	if (effectiveType === "DATE") return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		children: /* @__PURE__ */ u(DateInputComposed, {
			id,
			name: question.questionId,
			label,
			labelHint,
			value,
			required: isRequired,
			autocomplete,
			error,
			showErrorIcon: !!error,
			disabled,
			onInput: (e) => onChange(question.questionId, e.target.value),
			onBlur: () => onBlur?.(question.questionId)
		})
	});
	if (effectiveType === "PHONE") return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		onFocusOut: () => onBlur?.(question.questionId),
		children: /* @__PURE__ */ u(PhoneInputComposed, {
			id,
			label,
			labelHint,
			value,
			required: isRequired,
			autocomplete,
			error,
			showErrorIcon: !!error,
			disabled,
			onChange: (fullNumber, isValid) => {
				onChange(question.questionId, fullNumber);
				onFormatValidityChange?.(question.questionId, isValid);
			}
		})
	});
	if (effectiveType === "COUNTRY" || effectiveType === "NATIONALITY") return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		children: /* @__PURE__ */ u(DropdownComposed, {
			id,
			label,
			labelHint,
			value,
			options: countryOptions,
			searchable: true,
			required: isRequired,
			error,
			disabled,
			onChange: (val) => onChange(question.questionId, val),
			onBlur: () => onBlur?.(question.questionId)
		})
	});
	if (effectiveType === "SELECT" || effectiveType === "MULTISELECT") {
		const selectOptions = (question.options ?? []).map((o) => ({
			value: o,
			label: o
		}));
		return /* @__PURE__ */ u("div", {
			class: "IncodeDynamicFormsField",
			children: /* @__PURE__ */ u(DropdownComposed, {
				id,
				label,
				labelHint,
				value,
				options: selectOptions,
				searchable: selectOptions.length > 5,
				required: isRequired,
				error,
				disabled,
				onChange: (val) => onChange(question.questionId, val),
				onBlur: () => onBlur?.(question.questionId)
			})
		});
	}
	if (effectiveType === "EMAIL") return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		children: /* @__PURE__ */ u(EmailInput, {
			value,
			emailError: error,
			label,
			labelHint,
			required: isRequired,
			disabled,
			onEmailChange: (email, isValid) => {
				onChange(question.questionId, email);
				onFormatValidityChange?.(question.questionId, isValid);
			},
			onBlur: () => onBlur?.(question.questionId)
		})
	});
	if (effectiveType === "CPF") return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		children: /* @__PURE__ */ u(InputComposed, {
			id,
			name: question.questionId,
			label,
			labelHint,
			inputMode: "numeric",
			maxLength: 14,
			value,
			required: isRequired,
			error,
			showErrorIcon: !!error,
			disabled,
			onInput: (e) => {
				const formatted = formatCPF(e.target.value);
				e.target.value = formatted;
				onChange(question.questionId, formatted);
				onFormatValidityChange?.(question.questionId, isValidCPF(formatted));
			},
			onBlur: () => onBlur?.(question.questionId)
		})
	});
	if (effectiveType === "NUMBER") return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		children: /* @__PURE__ */ u(InputComposed, {
			id,
			name: question.questionId,
			label,
			labelHint,
			type: "number",
			inputMode: "numeric",
			value,
			required: isRequired,
			error,
			showErrorIcon: !!error,
			disabled,
			onInput: (e) => {
				const numeric = e.target.value.replace(/[^0-9]/g, "");
				onChange(question.questionId, numeric);
			},
			onBlur: () => onBlur?.(question.questionId)
		})
	});
	return /* @__PURE__ */ u("div", {
		class: "IncodeDynamicFormsField",
		children: /* @__PURE__ */ u(InputComposed, {
			id,
			name: question.questionId,
			label,
			labelHint,
			type: "text",
			value,
			required: isRequired,
			autocomplete,
			error,
			showErrorIcon: !!error,
			disabled,
			onInput: (e) => onChange(question.questionId, e.target.value),
			onBlur: () => onBlur?.(question.questionId)
		})
	});
};
var ScreenForm = ({ screen, answers, validationErrors, canSubmit, isSubmitting = false, onAnswerChange, onAnswerValidityChange, onValidateField, onSubmit }) => {
	const { t } = useTranslation();
	const title = screen.hideTitle ? void 0 : screen.title || t("dynamicForms.title");
	const titleId = g();
	const fallbackFormLabel = screen.title || t("dynamicForms.title");
	const hintMode = T(() => getRequiredHintMode(screen.questions.map((q) => !q.isOptional)), [screen]);
	return /* @__PURE__ */ u(Page, {
		className: "IncodeDynamicFormsPage",
		title,
		titleId: title ? titleId : void 0,
		hideFooterBranding: true,
		children: [
			/* @__PURE__ */ u(Spacer, { size: 32 }),
			isSubmitting && /* @__PURE__ */ u("div", {
				role: "status",
				"aria-live": "polite",
				class: "IncodeSrOnly",
				children: t("common.processing")
			}),
			/* @__PURE__ */ u("form", {
				class: "IncodeDynamicFormsForm",
				onSubmit: (e) => {
					e.preventDefault();
					onSubmit();
				},
				"aria-labelledby": title ? titleId : void 0,
				"aria-label": title ? void 0 : fallbackFormLabel,
				"aria-busy": isSubmitting || void 0,
				children: [screen.questions.map((question) => {
					const errorKey = validationErrors?.[question.questionId];
					const hint = getFieldHint(hintMode, !question.isOptional);
					const labelHint = hint ? t(`forms.label.${hint}`) ?? void 0 : void 0;
					return /* @__PURE__ */ u(QuestionInput, {
						question,
						value: answers[question.questionId] ?? "",
						disabled: isSubmitting,
						error: errorKey ? t(errorKey) : void 0,
						labelHint,
						onChange: onAnswerChange,
						onFormatValidityChange: onAnswerValidityChange,
						onBlur: onValidateField
					}, question.questionId);
				}), /* @__PURE__ */ u(Button, {
					type: "submit",
					disabled: !canSubmit,
					isLoading: isSubmitting,
					children: t("common.continue")
				})]
			})
		]
	});
};
var DynamicFormsContent = ({ config, manager: externalManager, onFinish }) => {
	const { t } = useTranslation();
	const [state, manager] = useManager(() => {
		if (externalManager) return externalManager;
		if (!config) throw new Error("DynamicForms config is required");
		return createDynamicFormsManager({ config });
	}, {
		manageLifecycle: !externalManager,
		autoLoad: true
	});
	useModuleTerminalCallbacks({
		status: state.status === "closed" ? "finished" : state.status,
		onFinish
	});
	if (state.status === "idle" || state.status === "loadingScreens") return /* @__PURE__ */ u(VerificationResult, {
		status: "submitting",
		submittingTitle: t("common.loading")
	});
	if (state.status === "inputting" || state.status === "submitting") {
		const isSubmitting = state.status === "submitting";
		const canSubmit = state.status === "inputting" ? state.canSubmit : false;
		return /* @__PURE__ */ u(ScreenForm, {
			screen: state.currentScreen,
			answers: state.answers,
			validationErrors: state.validationErrors,
			canSubmit,
			isSubmitting,
			onAnswerChange: (questionId, value) => manager.setAnswer(questionId, value),
			onAnswerValidityChange: (questionId, isValid) => manager.setAnswerValidity(questionId, isValid),
			onValidateField: (questionId) => manager.validateField(questionId),
			onSubmit: () => manager.submit()
		}, state.screenIndex);
	}
	if (state.status === "success") return /* @__PURE__ */ u(VerificationResult, {
		status: "success",
		successTitle: t("dynamicForms.success")
	});
	if (state.status === "misconfigured") return /* @__PURE__ */ u(VerificationResult, {
		status: "failure",
		failureTitle: t("dynamicForms.misconfigured"),
		onSkip: () => manager.close(),
		skipLabel: t("common.close")
	});
	if (state.status === "finished" || state.status === "closed") return null;
};
/**
* Dynamic Forms UI component.
*
* Renders multi-screen forms driven by backend configuration.
* Supports all field types: TEXT, NAME, NUMBER, DATE, EMAIL, PHONE, CPF, COUNTRY, NATIONALITY, YESNO, SELECT, MULTISELECT.
*
* @example Basic usage with flowId
* ```tsx
* <DynamicForms
*   config={{ flowId: 'your-flow-id' }}
*   onFinish={() => router.push('/next-step')}
*   onError={(err) => toast.error(err)}
* />
* ```
*
* @example Pre-loaded screens
* ```tsx
* <DynamicForms
*   config={{ screens: [...] }}
*   onFinish={() => router.push('/next-step')}
* />
* ```
*
* @see {@link createDynamicFormsManager} for headless usage
*/
var DynamicForms = ({ config, manager, onFinish }) => {
	return /* @__PURE__ */ u(IncodeComponent, { children: config || manager ? /* @__PURE__ */ u(DynamicFormsContent, {
		config,
		manager,
		onFinish
	}) : null });
};
registerIncodeModuleElement(DynamicForms, "incode-dynamic-forms");
//#endregion
export { DynamicForms };
