import { n as useTranslation } from "../i18n-DoP1NB7u.js";
import { h as q, v as u } from "../vendor-preact-DThS2ZQ_.js";
import { a as isTerminalModuleState, 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 OtpInput } from "../otpInput-DYJPGIzf.js";
import { t as Checkbox } from "../checkbox-1wUHSoaK.js";
import { t as PhoneInputComposed } from "../phoneInputComposed-BD2JzJM1.js";
import { t as registerIncodeModuleElement } from "../incodeModule-M8DszCee.js";
import { createPhoneManager } from "@incodetech/core/phone";
//#region src/modules/phone/phone.tsx
/**
* @module @incodetech/ui/phone
*
* Phone verification UI component for the Incode Web SDK.
* Provides a complete, ready-to-use phone verification experience
* with country code selection and OTP input.
*
* ## UI Usage
*
* The Phone component can be used as a React/Preact component or as a
* Web Component (`<incode-phone>`).
*
* @example React/Preact component usage
* ```tsx
* import { Phone } from '@incodetech/ui/phone';
* import { setup } from '@incodetech/core';
*
* // Configure the SDK first
* setup({ apiURL: 'https://api.example.com', token: 'your-token' });
*
* function App() {
*   const config = {
*     otpVerification: true,
*     otpExpirationInMinutes: 5,
*     prefill: false,
*   };
*
*   return (
*     <Phone
*       config={config}
*       onFinish={() => console.log('Phone verified!')}
*       onError={(error) => console.error('Error:', error)}
*     />
*   );
* }
* ```
*
* @example Web Component usage
* ```html
* <!-- Include the script -->
* <script type="module">
*   import '@incodetech/ui/phone';
*   import { setup } from '@incodetech/core';
*
*   setup({ apiURL: 'https://api.example.com', token: 'your-token' });
*
*   const phone = document.querySelector('incode-phone');
*   phone.config = {
*     otpVerification: true,
*     otpExpirationInMinutes: 5,
*     prefill: false,
*   };
*   phone.onFinish = () => console.log('Phone verified!');
*   phone.onError = (error) => console.error('Error:', error);
* <\/script>
*
* <incode-phone></incode-phone>
* ```
*
* ## Styling
*
* The component uses CSS custom properties (variables) for theming.
* Override these variables to customize the appearance:
*
* ```css
* :root {
*   --button-primary-surface-default: #0066cc;
*   --input-border-default: #cccccc;
*   --text-title: #333333;
* }
* ```
*
* ## Headless Alternative
*
* For complete control over the UI, use the headless `createPhoneManager`
* from `@incodetech/core/phone` instead. See the core module documentation.
*/
function getPhoneErrorTranslationKey(error) {
	if (error === "invalidPhone") return "phone.invalidPhone";
	if (error === "serverError") return "phone.serverError";
	return error;
}
function getOtpErrorTranslationKey(error) {
	if (error === "serverError") return "phone.serverError";
	return error;
}
var PhoneContent = ({ config, manager: externalManager, onFinish, onError }) => {
	const { t } = useTranslation();
	const [state, manager] = useManager(() => {
		if (externalManager) return externalManager;
		if (!config) throw new Error("Phone config is required");
		return createPhoneManager({ config });
	}, { manageLifecycle: !externalManager });
	const formatHintBuilder = q((example) => t("phone.formatHint", { example }), [t]);
	const countryAriaLabelBuilder = q(({ callingCode, countryName }) => t("phone.countryCodeAriaLabel", {
		callingCode,
		countryName
	}), [t]);
	useModuleTerminalCallbacks({
		status: state.status,
		onFinish,
		onError,
		error: state.status === "error" ? state.error : void 0
	});
	if (state.status === "idle" || state.status === "loadingPrefill" || state.status === "loadingStartInfo") return null;
	if (state.status === "inputting" || state.status === "submitting" || state.status === "sendingInitialOtp") {
		const isLoading = state.status === "submitting" || state.status === "sendingInitialOtp";
		const countryCode = state.status === "inputting" ? state.countryCode : "US";
		const prefilledPhone = state.status === "inputting" ? state.prefilledPhone : void 0;
		const serverPhoneError = state.status === "inputting" && state.phoneError ? t(getPhoneErrorTranslationKey(state.phoneError)) : void 0;
		const clientPhoneError = state.status === "inputting" && state.validationErrors?.phone ? t(getPhoneErrorTranslationKey(state.validationErrors.phone)) : void 0;
		const phoneError = serverPhoneError ?? clientPhoneError;
		const showFormatHintInError = !serverPhoneError && !!clientPhoneError;
		const isValid = state.status === "inputting" ? state.isValid : true;
		const optinEnabled = state.status === "inputting" ? state.optinEnabled ?? false : false;
		return /* @__PURE__ */ u(Page, {
			className: "IncodePhonePage",
			title: t("phone.verify"),
			subtitle: t("email.willSendCode"),
			children: [
				/* @__PURE__ */ u("div", {
					class: "IncodePhoneInputContainer",
					children: [
						/* @__PURE__ */ u(PhoneInputComposed, {
							id: "phone",
							countryCode,
							value: prefilledPhone,
							error: phoneError,
							showFormatHintInError,
							disabled: isLoading,
							onChange: (phone, isValid) => {
								manager.setPhoneNumber(phone, isValid);
							},
							onBlur: () => {
								manager.validatePhone();
							},
							formatHintBuilder,
							countryAriaLabelBuilder,
							"data-testid": "phone-input",
							showErrorIcon: true
						}),
						/* @__PURE__ */ u(Spacer, { size: 16 }),
						optinEnabled && /* @__PURE__ */ u(Checkbox, {
							id: "phone-optin",
							label: t("phone.optIn"),
							size: "s",
							onChange: (e) => manager.setOptInGranted(e.target.checked)
						})
					]
				}),
				/* @__PURE__ */ u(Spacer, {}),
				/* @__PURE__ */ u(Button, {
					onClick: () => manager.submit(),
					disabled: !isValid,
					isLoading,
					"data-testid": "phone-submit",
					children: t("common.continue")
				})
			]
		}, "phone-input");
	}
	if (state.status === "awaitingOtp" || state.status === "verifyingOtp" || state.status === "otpError" || state.status === "resendingOtp") {
		const isVerifying = state.status === "verifyingOtp";
		const hasOtpError = state.status === "otpError";
		const isAwaitingOtp = state.status === "awaitingOtp";
		const isResending = state.status === "resendingOtp";
		const showResendCooldown = isAwaitingOtp || hasOtpError || isVerifying;
		const otpError = hasOtpError ? t(getOtpErrorTranslationKey(state.otpError)) : void 0;
		const otpValidationError = "otpValidationErrors" in state && state.otpValidationErrors?.otp ? t("otp.incompleteCode", { length: state.otpLength }) : void 0;
		const isOtpValid = "isOtpValid" in state ? state.isOtpValid : true;
		return /* @__PURE__ */ u(Page, {
			className: "IncodePhonePage",
			title: t("otp.enterCodeSMS"),
			children: /* @__PURE__ */ u(OtpInput, {
				value: state.otpCode,
				otpLength: state.otpLength,
				resendTimer: showResendCooldown ? state.resendTimer : 0,
				canResend: showResendCooldown ? state.canResend : false,
				isLoading: isVerifying,
				disabled: isResending || isVerifying,
				error: otpError,
				validationError: otpValidationError,
				isValid: isOtpValid,
				onSubmit: (code) => manager.submitOtp(code),
				onChange: (code) => manager.setOtpCode(code),
				onValidate: () => manager.validateOtp(),
				onResend: () => manager.resendOtp(),
				onBack: () => manager.back()
			})
		}, "phone-otp");
	}
	if (isTerminalModuleState(state)) return null;
	return null;
};
/**
* Phone verification UI component.
*
* Provides a complete phone verification experience including:
* - Country code selector with flag emojis
* - Phone number input with validation
* - OTP code entry with resend functionality
* - Loading states and error handling
*
* @example Basic usage
* ```tsx
* <Phone
*   config={{
*     otpVerification: true,
*     otpExpirationInMinutes: 5,
*     prefill: false,
*   }}
*   onFinish={() => router.push('/next-step')}
*   onError={(err) => toast.error(err)}
* />
* ```
*
* @see {@link createPhoneManager} for headless usage
*/
var Phone = ({ config, manager, onFinish, onError }) => {
	return /* @__PURE__ */ u(IncodeComponent, { children: config || manager ? /* @__PURE__ */ u(PhoneContent, {
		config,
		manager,
		onFinish,
		onError
	}) : null });
};
registerIncodeModuleElement(Phone, "incode-phone");
//#endregion
export { Phone };
