/**
 * Strips formatting characters from a phone input, preserving digits and leading +.
 */
export function normalisePhoneInput(value: string): string {
	return value.replace(/[^\d+]/g, '').replace(/(?!^)\+/g, '');
}

/**
 * Validates a UK phone number.
 * Accepts: +44XXXXXXXXXX or 0XXXXXXXXXX (10–11 digits after prefix).
 * Returns true if valid.
 */
export function isValidUKPhone(phone: string): boolean {
	const clean = normalisePhoneInput(phone);
	return /^(\+44[1-9]\d{9,10}|0[1-9]\d{9,10})$/.test(clean);
}

/**
 * Formats a phone string as the user types — inserts spaces for readability.
 * e.g. 07700900000 → 07700 900000, +447700900000 → +44 7700 900000
 */
export function formatPhoneDisplay(value: string): string {
	const clean = normalisePhoneInput(value);
	if (clean.startsWith('+44')) {
		const digits = clean.slice(3).slice(0, 10); // max 10 digits after +44
		if (digits.length <= 4) return '+44 ' + digits;
		if (digits.length <= 8) return '+44 ' + digits.slice(0, 4) + ' ' + digits.slice(4);
		return '+44 ' + digits.slice(0, 4) + ' ' + digits.slice(4, 10);
	}
	if (clean.startsWith('0')) {
		const digits = clean.slice(1).slice(0, 10); // max 10 digits after 0
		if (digits.length <= 4) return '0' + digits;
		if (digits.length <= 7) return '0' + digits.slice(0, 4) + ' ' + digits.slice(4);
		return '0' + digits.slice(0, 4) + ' ' + digits.slice(4, 10);
	}
	return clean.slice(0, 15); // fallback limit
}

/**
 * Returns an E.164-normalised phone string ready to send to the backend,
 * or null if the input is not a valid UK number.
 */
export function toE164UK(phone: string): string | null {
	const clean = normalisePhoneInput(phone);
	if (!isValidUKPhone(clean)) return null;
	if (clean.startsWith('0')) return '+44' + clean.slice(1);
	return clean;
}
