import { n as useTranslation } from "./i18n-DoP1NB7u.js";
import { _ as y, d as T, l as A, v as u, x as k } from "./vendor-preact-DThS2ZQ_.js";
import { c as useManager, i as useFormScrollable, 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 "./extensibility-DesSYynI.js";
import { t as Spinner } from "./spinner-DqB4SGUV.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 { i as translateError, r as FormField } from "./radioGroupComposed-TuAWUAFK.js";
import { t as DropdownComposed } from "./dropdownComposed-ZdNkbyDs.js";
import { t as registerIncodeModuleElement } from "./incodeModule-M8DszCee.js";
import { n as getRequiredHintMode, t as getFieldHint } from "./requiredLabelHint-DX3oVNtu.js";
import { n as AddressAutocomplete, t as getAccessibleOptionLabel } from "./optionAccessibleLabel-_nvVCTSL.js";
import { t as CountrySelector$1 } from "./countrySelector-HaBPZOXx.js";
import { DEV_ONLY_COUNTRIES, SUPPORTED_COUNTRIES, createEkybManager } from "@incodetech/core/ekyb";
//#region src/modules/ekyb/countrySelector.tsx
var CountrySelector = ({ value, onChange }) => {
	const { t } = useTranslation();
	return /* @__PURE__ */ u(CountrySelector$1, {
		id: "ekyb-country",
		label: t("ekyb.country"),
		value,
		onChange,
		countryCodes: SUPPORTED_COUNTRIES,
		devOnlyCountryCodes: DEV_ONLY_COUNTRIES,
		"data-testid": "ekyb-country-selector"
	});
};
//#endregion
//#region src/modules/ekyb/fieldInput.tsx
var FieldInput = ({ field, value, error, errorParams, country: _country, labelHint, onChange, onBlur }) => {
	const { t } = useTranslation();
	if (field.type === "dropdown") return /* @__PURE__ */ u(DropdownComposed, {
		id: `ekyb-${field.name}`,
		label: t(field.label),
		labelHint,
		placeholder: field.placeholder ? t(field.placeholder) : void 0,
		value,
		options: (field.options ?? []).map((o) => {
			const translatedOptionLabel = t(o.label);
			return {
				...o,
				label: translatedOptionLabel,
				ariaLabel: getAccessibleOptionLabel(translatedOptionLabel)
			};
		}),
		error: translateError(t, error, errorParams),
		required: field.required,
		searchable: true,
		onChange: (val) => onChange(field.name, val),
		onBlur: onBlur ? () => onBlur(field.name) : void 0,
		"data-testid": `ekyb-field-${field.name}`
	});
	return /* @__PURE__ */ u(FormField, {
		name: field.name,
		label: field.label,
		displayLabel: field.displayLabel,
		value,
		error,
		errorParams,
		required: field.required,
		labelHint,
		onChange,
		onBlur
	});
};
//#endregion
//#region src/modules/ekyb/uboInputs.tsx
var UboInputs = ({ ubos, validationErrors, canAddUbo, labelHint, onSetField, onBlur, onAdd, onRemove }) => {
	const { t } = useTranslation();
	const translateError$2 = (err) => translateError(t, err?.key, err?.params);
	if (ubos.length === 0) return null;
	return /* @__PURE__ */ u("div", {
		className: "IncodeEkybUbos",
		children: [ubos.map((ubo, index) => {
			const nameLabel = index === 0 ? t("ekyb.uboName") : t("ekyb.uboNameWithNumber", { number: index + 1 });
			const surnameLabel = index === 0 ? t("ekyb.uboSurname") : t("ekyb.uboSurnameWithNumber", { number: index + 1 });
			const isFirst = index === 0;
			return /* @__PURE__ */ u("div", {
				className: "IncodeEkybUboEntry",
				role: "group",
				"aria-label": `UBO ${index + 1}`,
				children: [
					/* @__PURE__ */ u(InputComposed, {
						id: `ubo-${index}-name`,
						label: nameLabel,
						labelHint,
						name: `ubo-${index}-name`,
						value: ubo.name,
						error: translateError$2(validationErrors?.[`ubo-${index}-name`]),
						required: true,
						onInput: (e) => onSetField(index, "name", e.target.value),
						onBlur: onBlur ? () => onBlur(`ubo-${index}-name`) : void 0,
						"data-testid": `ekyb-ubo-${index}-name`
					}),
					/* @__PURE__ */ u(InputComposed, {
						id: `ubo-${index}-surname`,
						label: surnameLabel,
						labelHint,
						name: `ubo-${index}-surname`,
						value: ubo.surname,
						error: translateError$2(validationErrors?.[`ubo-${index}-surname`]),
						required: true,
						onInput: (e) => onSetField(index, "surname", e.target.value),
						onBlur: onBlur ? () => onBlur(`ubo-${index}-surname`) : void 0,
						"data-testid": `ekyb-ubo-${index}-surname`
					}),
					!isFirst && /* @__PURE__ */ u("button", {
						className: "IncodeEkybRemoveUbo",
						onClick: () => onRemove(index),
						type: "button",
						"aria-label": `${t("common.remove")} UBO ${index + 1}`,
						children: t("common.remove")
					})
				]
			}, ubo.id);
		}), canAddUbo && /* @__PURE__ */ u("button", {
			className: "IncodeEkybAddUbo",
			onClick: onAdd,
			type: "button",
			"data-testid": "ekyb-add-ubo",
			children: t("ekyb.addAnotherUbo")
		})]
	});
};
//#endregion
//#region src/modules/ekyb/ekybModule.tsx
var EkybContent = ({ config, onFinish }) => {
	const { t } = useTranslation();
	const [state, manager] = useManager(() => createEkybManager({ config }));
	useModuleTerminalCallbacks({
		status: state.status === "closed" ? "finished" : state.status,
		onFinish
	});
	if (state.status === "finished" || state.status === "closed") return null;
	if (state.status === "loading") return /* @__PURE__ */ u(VerificationResult, {
		status: "submitting",
		submittingTitle: t("common.loading")
	});
	if (state.status === "submitting") return /* @__PURE__ */ u(Page, {
		className: "IncodeEkybPage",
		children: /* @__PURE__ */ u(Spinner, {
			fullScreen: false,
			title: t("common.processing"),
			className: "IncodeEkybSpinner"
		})
	});
	if (state.status === "success") return /* @__PURE__ */ u(VerificationResult, { status: "success" });
	if (state.status === "error") return /* @__PURE__ */ u(VerificationResult, {
		status: "failure",
		onRetry: () => manager.retry()
	});
	if (state.status === "form") return /* @__PURE__ */ u(EkybForm, {
		state,
		manager
	});
	return null;
};
var ADDRESS_FIELD_NAMES = new Set([
	"street",
	"houseNo",
	"addressLine2",
	"city",
	"state",
	"postalCode"
]);
var EkybForm = ({ state, manager }) => {
	const { country, fields, values, validationErrors, isValid, ubos, canAddUbo, addressSuggestions } = state;
	const { t } = useTranslation();
	const formRef = A(null);
	const postalCodeFieldRef = A(null);
	const previousPostalCodeErrorRef = A(void 0);
	const isScrollable = useFormScrollable(formRef, fields.length);
	const translateError$1 = (err) => translateError(t, err?.key, err?.params);
	const postalCodeErrorKey = validationErrors?.postalCode?.key;
	y(() => {
		const previous = previousPostalCodeErrorRef.current;
		previousPostalCodeErrorRef.current = postalCodeErrorKey;
		if (!postalCodeErrorKey || previous === postalCodeErrorKey) return;
		const rafId = requestAnimationFrame(() => {
			const postalField = postalCodeFieldRef.current;
			if (!postalField) return;
			(postalField.querySelector("#postalCode-error") ?? postalField).scrollIntoView({
				behavior: "smooth",
				block: "nearest"
			});
		});
		return () => cancelAnimationFrame(rafId);
	}, [postalCodeErrorKey]);
	const businessFields = fields.filter((f) => !ADDRESS_FIELD_NAMES.has(f.name));
	const addressFields = fields.filter((f) => ADDRESS_FIELD_NAMES.has(f.name));
	const mode = T(() => getRequiredHintMode(fields.map((f) => f.required)), [fields]);
	const labelHintFor = (required) => {
		const hint = getFieldHint(mode, required);
		return hint ? t(`forms.label.${hint}`) : void 0;
	};
	return /* @__PURE__ */ u(Page, {
		className: `IncodeEkybPage${isScrollable ? " IncodeEkybPageScrollable" : ""}`,
		title: t("ekyb.title"),
		children: [/* @__PURE__ */ u("div", {
			ref: formRef,
			className: "IncodeEkybForm",
			children: [
				/* @__PURE__ */ u(CountrySelector, {
					value: country,
					onChange: (c) => manager.setCountry(c)
				}),
				businessFields.map((field) => /* @__PURE__ */ u(FieldInput, {
					field,
					value: values[field.name] ?? "",
					error: translateError$1(validationErrors?.[field.name]),
					country,
					labelHint: labelHintFor(field.required),
					onChange: (name, value) => manager.setField(name, value),
					onBlur: (name) => manager.validateField(name)
				}, field.name)),
				/* @__PURE__ */ u(UboInputs, {
					ubos,
					validationErrors,
					canAddUbo,
					labelHint: labelHintFor(true),
					onSetField: (index, field, value) => manager.setUboField(index, field, value),
					onBlur: (fieldKey) => manager.validateField(fieldKey),
					onAdd: () => manager.addUbo(),
					onRemove: (index) => manager.removeUbo(index)
				}),
				addressFields.length > 0 && /* @__PURE__ */ u(k, { children: [/* @__PURE__ */ u("h3", {
					className: "IncodeEkybSectionHeader",
					children: t("ekyb.addressDetails")
				}), addressFields.map((field) => {
					if (field.name === "street") return /* @__PURE__ */ u(AddressAutocomplete, {
						label: field.label,
						labelHint: labelHintFor(field.required),
						value: values.street ?? "",
						error: translateError$1(validationErrors?.street),
						suggestions: addressSuggestions,
						required: field.required,
						onChange: (value) => manager.setField("street", value),
						onSearch: (query) => manager.searchAddress(query),
						onSelect: (suggestion) => manager.selectAddress(suggestion),
						onBlur: () => manager.validateField("street")
					}, field.name);
					return /* @__PURE__ */ u("div", {
						ref: field.name === "postalCode" ? postalCodeFieldRef : void 0,
						children: /* @__PURE__ */ u(FieldInput, {
							field,
							value: values[field.name] ?? "",
							error: translateError$1(validationErrors?.[field.name]),
							country,
							labelHint: labelHintFor(field.required),
							onChange: (name, value) => manager.setField(name, value),
							onBlur: (name) => manager.validateField(name)
						})
					}, field.name);
				})] })
			]
		}), /* @__PURE__ */ u("div", {
			className: "IncodeEkybFooter",
			children: [/* @__PURE__ */ u(Button, {
				onClick: () => manager.submit(),
				disabled: !isValid,
				"data-testid": "ekyb-submit",
				children: t("ekyb.continue")
			}), /* @__PURE__ */ u(Spacer, { size: 16 })]
		})]
	});
};
var EkybModule = ({ config, onFinish }) => {
	return /* @__PURE__ */ u(IncodeComponent, { children: config ? /* @__PURE__ */ u(EkybContent, {
		config,
		onFinish
	}) : null });
};
registerIncodeModuleElement(EkybModule, "incode-ekyb");
//#endregion
export { EkybModule as t };
