import React, { useMemo } from "react";
import { locales } from "@pisell/utils";
import "./PhoneInput.less";
//#region src/pro/Login2.0/components/PhoneInput.tsx
/** 默认国家/地区列表 */
const DEFAULT_COUNTRIES = [
	{
		name: "United States",
		code: "US",
		calling_code: "1",
		currency_code: "USD"
	},
	{
		name: "China",
		code: "CN",
		calling_code: "86",
		currency_code: "CNY"
	},
	{
		name: "United Kingdom",
		code: "GB",
		calling_code: "44",
		currency_code: "GBP"
	},
	{
		name: "Australia",
		code: "AU",
		calling_code: "61",
		currency_code: "AUD"
	},
	{
		name: "Canada",
		code: "CA",
		calling_code: "1",
		currency_code: "CAD"
	},
	{
		name: "Japan",
		code: "JP",
		calling_code: "81",
		currency_code: "JPY"
	},
	{
		name: "South Korea",
		code: "KR",
		calling_code: "82",
		currency_code: "KRW"
	},
	{
		name: "Singapore",
		code: "SG",
		calling_code: "65",
		currency_code: "SGD"
	},
	{
		name: "Hong Kong",
		code: "HK",
		calling_code: "852",
		currency_code: "HKD"
	},
	{
		name: "Taiwan",
		code: "TW",
		calling_code: "886",
		currency_code: "TWD"
	},
	{
		name: "Malaysia",
		code: "MY",
		calling_code: "60",
		currency_code: "MYR"
	},
	{
		name: "Thailand",
		code: "TH",
		calling_code: "66",
		currency_code: "THB"
	},
	{
		name: "Vietnam",
		code: "VN",
		calling_code: "84",
		currency_code: "VND"
	},
	{
		name: "Philippines",
		code: "PH",
		calling_code: "63",
		currency_code: "PHP"
	},
	{
		name: "Indonesia",
		code: "ID",
		calling_code: "62",
		currency_code: "IDR"
	},
	{
		name: "India",
		code: "IN",
		calling_code: "91",
		currency_code: "INR"
	},
	{
		name: "Germany",
		code: "DE",
		calling_code: "49",
		currency_code: "EUR"
	},
	{
		name: "France",
		code: "FR",
		calling_code: "33",
		currency_code: "EUR"
	},
	{
		name: "Italy",
		code: "IT",
		calling_code: "39",
		currency_code: "EUR"
	},
	{
		name: "Spain",
		code: "ES",
		calling_code: "34",
		currency_code: "EUR"
	}
];
/**
* 从浏览器检测用户的国家/地区
* 优先级：
* 1. Intl.DateTimeFormat 的 resolvedOptions
* 2. navigator.language 的地区后缀
* 3. 返回 null（使用默认值）
*/
function detectUserCountry() {
	try {
		if (typeof Intl !== "undefined" && Intl.DateTimeFormat) {
			const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
			const timeZoneMap = {
				"America/New_York": "US",
				"America/Los_Angeles": "US",
				"America/Chicago": "US",
				"America/Denver": "US",
				"America/Toronto": "CA",
				"America/Vancouver": "CA",
				"Europe/London": "GB",
				"Europe/Paris": "FR",
				"Europe/Berlin": "DE",
				"Europe/Rome": "IT",
				"Europe/Madrid": "ES",
				"Asia/Shanghai": "CN",
				"Asia/Hong_Kong": "HK",
				"Asia/Taipei": "TW",
				"Asia/Tokyo": "JP",
				"Asia/Seoul": "KR",
				"Asia/Singapore": "SG",
				"Asia/Bangkok": "TH",
				"Asia/Kuala_Lumpur": "MY",
				"Asia/Jakarta": "ID",
				"Asia/Manila": "PH",
				"Asia/Ho_Chi_Minh": "VN",
				"Asia/Kolkata": "IN",
				"Australia/Sydney": "AU",
				"Australia/Melbourne": "AU"
			};
			if (timeZone && timeZoneMap[timeZone]) return timeZoneMap[timeZone];
		}
		if (typeof navigator !== "undefined" && navigator.language) {
			const parts = navigator.language.split("-");
			if (parts.length > 1) return parts[1].toUpperCase();
			const langMap = {
				"zh": "CN",
				"en": "US",
				"ja": "JP",
				"ko": "KR",
				"de": "DE",
				"fr": "FR",
				"es": "ES",
				"it": "IT",
				"th": "TH",
				"vi": "VN",
				"id": "ID",
				"ms": "MY"
			};
			if (langMap[parts[0]]) return langMap[parts[0]];
		}
	} catch (error) {
		console.warn("Failed to detect user country:", error);
	}
	return null;
}
/**
* 手机号输入组件
* 
* 支持国际区号选择和手机号输入
* 值格式：+区号+手机号，例如：+8613800138000 或 +15551234567
*/
function PhoneInput({ value, onChange, placeholder, onKeyDown, size = "large", disabled = false, className = "", countries = DEFAULT_COUNTRIES, defaultCountry, valueFormat = "string" }) {
	const effectivePlaceholder = placeholder || locales.getText("pisell-phone-input-placeholder");
	const normalizedValue = useMemo(() => {
		if (!value) return "";
		console.log("value", value);
		if (typeof value === "object" && "phone" in value) {
			const { phone, country_calling_code } = value;
			return `+${country_calling_code}${phone}`;
		}
		return value;
	}, [value]);
	const effectiveDefaultCountry = useMemo(() => {
		var _countries$;
		const detectedCountry = detectUserCountry();
		if (detectedCountry && countries.some((c) => c.code === detectedCountry)) {
			console.log("PhoneInput: Auto-detected country:", detectedCountry);
			return detectedCountry;
		}
		if (defaultCountry && countries.some((c) => c.code === defaultCountry)) return defaultCountry;
		return (countries === null || countries === void 0 || (_countries$ = countries[0]) === null || _countries$ === void 0 ? void 0 : _countries$.code) || "AU";
	}, [countries, defaultCountry]);
	const { dialCode: currentDialCode, phoneNumber: currentPhoneNumber } = useMemo(() => {
		if (!(countries === null || countries === void 0 ? void 0 : countries.length)) return {
			dialCode: "",
			phoneNumber: ""
		};
		if (!normalizedValue || !normalizedValue.startsWith("+")) {
			const defaultCountryOption = countries.find((c) => c.code === effectiveDefaultCountry) || (countries === null || countries === void 0 ? void 0 : countries[0]);
			return {
				dialCode: `+${defaultCountryOption === null || defaultCountryOption === void 0 ? void 0 : defaultCountryOption.calling_code}`,
				phoneNumber: ""
			};
		}
		for (const country of countries) {
			const countryDialCode = `+${country.calling_code}`;
			if (normalizedValue.startsWith(countryDialCode)) return {
				dialCode: countryDialCode,
				phoneNumber: normalizedValue.slice(countryDialCode.length)
			};
		}
		return {
			dialCode: `+${(countries.find((c) => c.code === effectiveDefaultCountry) || countries[0]).calling_code}`,
			phoneNumber: normalizedValue.startsWith("+") ? normalizedValue.slice(1) : normalizedValue
		};
	}, [
		normalizedValue,
		countries,
		effectiveDefaultCountry
	]);
	const currentCountry = useMemo(() => {
		return countries.find((c) => `+${c.calling_code}` === currentDialCode) || countries[0];
	}, [currentDialCode, countries]);
	const formatOutputValue = (dialCode, phoneNumber) => {
		const fullString = `${dialCode}${phoneNumber}`;
		if (valueFormat === "object") return {
			phone: String(phoneNumber || ""),
			country_calling_code: String(dialCode.replace("+", "") || "")
		};
		return fullString;
	};
	const handleDialCodeChange = (e) => {
		const newDialCode = e.target.value;
		const newValue = formatOutputValue(newDialCode, currentPhoneNumber);
		onChange === null || onChange === void 0 || onChange(newValue);
	};
	const handlePhoneNumberChange = (e) => {
		let inputValue = e.target.value;
		const dialCodeWithoutPlus = currentDialCode.replace("+", "");
		if (inputValue.startsWith("+")) {
			if (inputValue.startsWith(currentDialCode)) inputValue = inputValue.slice(currentDialCode.length);
		} else if (inputValue.startsWith(dialCodeWithoutPlus)) inputValue = inputValue.slice(dialCodeWithoutPlus.length);
		const newValue = formatOutputValue(currentDialCode, inputValue.replace(/[^\d]/g, ""));
		onChange === null || onChange === void 0 || onChange(newValue);
	};
	return /* @__PURE__ */ React.createElement("div", { className: `phone-input-wrapper ${className}` }, /* @__PURE__ */ React.createElement("div", { className: "phone-input-container" }, /* @__PURE__ */ React.createElement("div", { className: "phone-input-prefix" }, /* @__PURE__ */ React.createElement("span", { className: "phone-input-country-display" }, currentCountry === null || currentCountry === void 0 ? void 0 : currentCountry.code, "(", currentDialCode, ")"), /* @__PURE__ */ React.createElement("select", {
		className: "phone-input-select",
		value: currentDialCode,
		onChange: handleDialCodeChange,
		disabled
	}, countries.map((country) => /* @__PURE__ */ React.createElement("option", {
		key: country.code,
		value: `+${country.calling_code}`
	}, country.code, " +", country.calling_code))), /* @__PURE__ */ React.createElement("svg", {
		className: "phone-input-arrow",
		width: "12",
		height: "12",
		viewBox: "0 0 12 12",
		fill: "none",
		xmlns: "http://www.w3.org/2000/svg"
	}, /* @__PURE__ */ React.createElement("path", {
		d: "M3 4.5L6 7.5L9 4.5",
		stroke: "currentColor",
		strokeWidth: "1.5",
		strokeLinecap: "round",
		strokeLinejoin: "round"
	}))), /* @__PURE__ */ React.createElement("div", { className: "phone-input-divider" }), /* @__PURE__ */ React.createElement("input", {
		type: "tel",
		className: `phone-input-field phone-input-field-${size}`,
		value: currentPhoneNumber,
		onChange: handlePhoneNumberChange,
		onKeyDown,
		placeholder: effectivePlaceholder,
		disabled,
		autoComplete: "tel"
	})));
}
//#endregion
export { PhoneInput as default };
