import { n as useTranslation } from "../i18n-DoP1NB7u.js";
import { _ as y, 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 { t as Page } from "../page-DidH_RkX.js";
import { t as Spinner } from "../spinner-DqB4SGUV.js";
import { t as Button } from "../button-BMYTQ8fc.js";
import { t as registerIncodeModuleElement } from "../incodeModule-M8DszCee.js";
import { SCAN_NEW_DOCUMENT, createIdentityReuseManager } from "@incodetech/core/identity-reuse";
//#region src/modules/identity-reuse/identity-reuse.tsx
/**
* ISO 3166-1 alpha-3 → alpha-2 mapping for countries the SDK supports.
* The identity-reuse backend returns alpha-3 codes; flag rendering needs
* alpha-2. Extend as backend support expands; unmapped codes fall back to "".
*/
var ISO3_TO_ISO2 = {
	USA: "US",
	MEX: "MX",
	CAN: "CA",
	GBR: "GB",
	DEU: "DE",
	FRA: "FR",
	ESP: "ES",
	ITA: "IT",
	BRA: "BR",
	ARG: "AR",
	COL: "CO",
	CHL: "CL",
	PER: "PE",
	AUS: "AU",
	NZL: "NZ",
	JPN: "JP",
	KOR: "KR",
	CHN: "CN",
	IND: "IN",
	RUS: "RU",
	ZAF: "ZA",
	NGA: "NG",
	EGY: "EG",
	ARE: "AE",
	SAU: "SA",
	ISR: "IL",
	TUR: "TR",
	NLD: "NL",
	BEL: "BE",
	CHE: "CH",
	AUT: "AT",
	SWE: "SE",
	NOR: "NO",
	DNK: "DK",
	FIN: "FI",
	POL: "PL",
	PRT: "PT",
	IRL: "IE",
	GRC: "GR",
	CZE: "CZ",
	HUN: "HU",
	ROU: "RO",
	UKR: "UA",
	PHL: "PH",
	IDN: "ID",
	MYS: "MY",
	SGP: "SG",
	THA: "TH",
	VNM: "VN",
	PAK: "PK",
	BGD: "BD",
	HKG: "HK",
	TWN: "TW",
	VEN: "VE",
	ECU: "EC",
	GTM: "GT",
	CRI: "CR",
	PAN: "PA",
	DOM: "DO",
	PRI: "PR",
	CUB: "CU",
	JAM: "JM",
	HND: "HN",
	SLV: "SV",
	NIC: "NI",
	BOL: "BO",
	PRY: "PY",
	URY: "UY",
	KEN: "KE",
	GHA: "GH",
	MAR: "MA",
	TUN: "TN",
	KWT: "KW",
	QAT: "QA",
	BHR: "BH",
	OMN: "OM",
	JOR: "JO",
	LBN: "LB",
	SRB: "RS",
	HRV: "HR",
	SVK: "SK",
	SVN: "SI",
	BGR: "BG",
	LTU: "LT",
	LVA: "LV",
	EST: "EE",
	ISL: "IS",
	LUX: "LU",
	MLT: "MT",
	CYP: "CY"
};
/** Convert an ISO-2 or ISO-3 country code to a flag emoji. */
function countryCodeToFlag(countryCode) {
	if (!countryCode) return "";
	const upper = countryCode.toUpperCase();
	const iso2 = upper.length === 3 ? ISO3_TO_ISO2[upper] ?? "" : upper;
	if (iso2.length !== 2) return "";
	const A_OFFSET = 127462 - "A".charCodeAt(0);
	return String.fromCodePoint(iso2.charCodeAt(0) + A_OFFSET, iso2.charCodeAt(1) + A_OFFSET);
}
/**
* Format a backend verification timestamp as a locale-aware short date
* (e.g. "15 Apr 2023" in en-US). Auto-detects unit: values >= 1e12 are
* treated as milliseconds, smaller values as unix seconds (the documents
* API returns seconds, possibly with fractional millis). Returns null if
* the value can't be parsed so the caller can hide the row instead of
* rendering a half-empty "Verified" with no date.
*/
function formatVerifiedAt(timestamp, locale) {
	if (!Number.isFinite(timestamp) || timestamp <= 0) return null;
	const ms = timestamp >= 0xe8d4a51000 ? timestamp : timestamp * 1e3;
	const date = new Date(ms);
	if (Number.isNaN(date.getTime())) return null;
	return new Intl.DateTimeFormat(locale, {
		day: "2-digit",
		month: "short",
		year: "numeric"
	}).format(date);
}
var RadioDot = ({ checked }) => /* @__PURE__ */ u("span", {
	class: `IncodeIdentityReuseRadio ${checked ? "IncodeIdentityReuseRadioChecked" : ""}`,
	"aria-hidden": "true",
	children: checked ? /* @__PURE__ */ u("span", { class: "IncodeIdentityReuseRadioInner" }) : null
});
var DocumentCard = ({ document, selected, recommended, tabIndex, onSelect, locale }) => {
	const { t } = useTranslation();
	const typeLabel = t(`identityReuse.documentType.${document.documentType}`);
	const flag = countryCodeToFlag(document.countryCode);
	const verifiedDate = formatVerifiedAt(document.verifiedAt, locale);
	const verifiedWord = t("identityReuse.verified", { defaultValue: "Verified" });
	const verifiedLabel = verifiedDate ? `${verifiedWord} ${verifiedDate}` : null;
	return /* @__PURE__ */ u("button", {
		type: "button",
		class: `IncodeIdentityReuseCard ${selected ? "IncodeIdentityReuseCardSelected" : ""}`,
		role: "radio",
		"aria-checked": selected,
		tabIndex,
		onClick: onSelect,
		"data-testid": `identity-reuse-document-${document.id}`,
		children: /* @__PURE__ */ u("div", {
			class: "IncodeIdentityReuseCardBody",
			children: [
				/* @__PURE__ */ u("div", {
					class: "IncodeIdentityReuseCardHeader",
					children: [/* @__PURE__ */ u("div", {
						class: "IncodeIdentityReuseCardHeaderLeft",
						children: [/* @__PURE__ */ u("span", {
							class: "IncodeIdentityReuseCardTypeLabel",
							children: typeLabel
						}), recommended ? /* @__PURE__ */ u("span", {
							class: "IncodeIdentityReuseBadgeRecommended",
							children: t("identityReuse.badge.recommended")
						}) : null]
					}), /* @__PURE__ */ u(RadioDot, { checked: selected })]
				}),
				/* @__PURE__ */ u("p", {
					class: "IncodeIdentityReuseCardIdentifier",
					children: [flag ? /* @__PURE__ */ u("span", {
						"aria-hidden": "true",
						children: flag
					}) : null, /* @__PURE__ */ u("span", { children: document.maskedNumber })]
				}),
				verifiedLabel ? /* @__PURE__ */ u("p", {
					class: "IncodeIdentityReuseCardVerified",
					children: verifiedLabel
				}) : null
			]
		})
	});
};
var ScanNewRow = ({ selected, tabIndex, onSelect }) => {
	const { t } = useTranslation();
	return /* @__PURE__ */ u("button", {
		type: "button",
		class: `IncodeIdentityReuseCard IncodeIdentityReuseScanNewCard ${selected ? "IncodeIdentityReuseCardSelected" : ""}`,
		role: "radio",
		"aria-checked": selected,
		tabIndex,
		onClick: onSelect,
		"data-testid": "identity-reuse-scan-new",
		children: [/* @__PURE__ */ u("div", {
			class: "IncodeIdentityReuseScanNewBody",
			children: [/* @__PURE__ */ u("span", {
				class: "IncodeIdentityReuseCardTypeLabel",
				children: t("identityReuse.scanANewDocument")
			}), /* @__PURE__ */ u("span", {
				class: "IncodeIdentityReuseBadgeSlowest",
				children: t("identityReuse.badge.slowest")
			})]
		}), /* @__PURE__ */ u(RadioDot, { checked: selected })]
	});
};
var IdentityReuseContent = ({ config, manager: externalManager, onFinish, onError }) => {
	const { t, i18n } = useTranslation();
	const locale = i18n.language || "en";
	const [state, manager] = useManager(() => {
		if (externalManager) return externalManager;
		if (!config) throw new Error("IdentityReuse config is required when no manager is provided");
		return createIdentityReuseManager({ config });
	}, { manageLifecycle: !externalManager });
	useModuleTerminalCallbacks({
		status: state.status === "finished" ? "finished" : "loading",
		onFinish
	});
	const errorMessage = state.status === "error" ? state.error : void 0;
	y(() => {
		if (errorMessage) onError?.(errorMessage);
	}, [errorMessage, onError]);
	if (state.status === "idle" || state.status === "loading" || state.status === "submitting") return /* @__PURE__ */ u(Spinner, { title: t("identityReuse.loading") });
	if (state.status === "documentsFound") {
		const selectedId = state.selectedDocumentId;
		const optionIds = [...state.documents.map((d) => d.id), SCAN_NEW_DOCUMENT];
		const focusedIndex = selectedId === void 0 ? 0 : Math.max(0, optionIds.findIndex((id) => id === selectedId));
		const ctaLabel = selectedId === SCAN_NEW_DOCUMENT ? t("identityReuse.cta.scanNew") : t("identityReuse.cta.confirm");
		const handleRadiogroupKeyDown = (event) => {
			const container = event.currentTarget;
			if (!container) return;
			const buttons = container.querySelectorAll("[role=\"radio\"]");
			if (buttons.length === 0) return;
			const currentIndex = Array.from(buttons).findIndex((b) => b === document.activeElement);
			if (currentIndex === -1) return;
			let nextIndex = currentIndex;
			switch (event.key) {
				case "ArrowDown":
				case "ArrowRight":
					nextIndex = (currentIndex + 1) % buttons.length;
					break;
				case "ArrowUp":
				case "ArrowLeft":
					nextIndex = (currentIndex - 1 + buttons.length) % buttons.length;
					break;
				case "Home":
					nextIndex = 0;
					break;
				case "End":
					nextIndex = buttons.length - 1;
					break;
				default: return;
			}
			event.preventDefault();
			const next = buttons[nextIndex];
			if (next) {
				next.focus();
				next.click();
			}
		};
		return /* @__PURE__ */ u(Page, {
			className: "IncodeIdentityReusePage",
			title: t("identityReuse.title"),
			subtitle: t("identityReuse.subtitle"),
			children: /* @__PURE__ */ u("div", {
				class: "IncodeIdentityReuseBody",
				children: [/* @__PURE__ */ u("div", {
					class: "IncodeIdentityReuseList",
					role: "radiogroup",
					"aria-label": t("identityReuse.title"),
					onKeyDown: handleRadiogroupKeyDown,
					children: [state.documents.map((document, index) => /* @__PURE__ */ u(DocumentCard, {
						document,
						selected: selectedId === document.id,
						recommended: index === 0,
						tabIndex: index === focusedIndex ? 0 : -1,
						onSelect: () => manager.chooseDocument(document.id),
						locale
					}, document.id)), /* @__PURE__ */ u(ScanNewRow, {
						selected: selectedId === SCAN_NEW_DOCUMENT,
						tabIndex: focusedIndex === state.documents.length ? 0 : -1,
						onSelect: () => manager.chooseDocument(SCAN_NEW_DOCUMENT)
					})]
				}), /* @__PURE__ */ u("div", {
					class: "IncodeIdentityReuseActions",
					children: /* @__PURE__ */ u(Button, {
						onClick: () => manager.submit(),
						disabled: selectedId === void 0,
						"data-testid": "identity-reuse-confirm-button",
						children: ctaLabel
					})
				})]
			})
		});
	}
	if (state.status === "error") return /* @__PURE__ */ u(Page, {
		className: "IncodeIdentityReusePage",
		title: t("identityReuse.errorTitle"),
		subtitle: state.error,
		children: [/* @__PURE__ */ u("div", { class: "IncodeIdentityReuseContent" }), /* @__PURE__ */ u("div", {
			class: "IncodeIdentityReuseActions",
			children: [/* @__PURE__ */ u(Button, {
				onClick: () => manager.retry(),
				"data-testid": "identity-reuse-retry-button",
				children: t("identityReuse.cta.retry")
			}), /* @__PURE__ */ u(Button, {
				onClick: () => manager.skip(),
				variant: "link",
				"data-testid": "identity-reuse-skip-button",
				children: t("identityReuse.cta.skip")
			})]
		})]
	});
	if (state.status === "finished") return null;
	return null;
};
var IdentityReuse = ({ config, manager, onFinish, onError }) => /* @__PURE__ */ u(IncodeComponent, { children: config || manager ? /* @__PURE__ */ u(IdentityReuseContent, {
	config,
	manager,
	onFinish,
	onError
}) : null });
registerIncodeModuleElement(IdentityReuse, "incode-identity-reuse");
//#endregion
export { IdentityReuse };
