import { parsePhoneNumberFromString } from 'libphonenumber-js/min';

// We use JSDelivr (proxy by static.descope.com) in order to fetch the images as image file from this library (svg-country-flags)
// This reduces our bundle size, and we use it as a static remote resource.
export const getCountryFlag = (code) =>
  `https://static.descope.com/npm/svg-country-flags@1.2.10/svg/${code.toLowerCase()}.svg`;

export const comboBoxItem = ({ code, dialCode, name: country }) => `
	<div
		data-id="${dialCode}"
		data-name="${code} ${dialCode} ${country}"
		data-country-code="${code}"
	>
		<div>
			<span>
				<img src="${getCountryFlag(code)}" width="20"/>
			</span>
			<span>${country}</span>
		</div>
		<div>
			<span>${code}</span>
			<span>${dialCode}</span>
		</div>
	</div>
`;

export const parsePhoneNumber = (val) => {
  const value = val || '';
  let countryCode = '';
  let phoneNumber = '';

  // Attempt to parse the value using libphonenumber-js
  const parsed = parsePhoneNumberFromString(value);

  if (parsed) {
    if (parsed.countryCallingCode) {
      countryCode = `+${parsed.countryCallingCode}`;
    }

    if (parsed.nationalNumber) {
      phoneNumber = parsed.nationalNumber;
    }
  } else {
    // Fallback: assume a dash separates country code and phone number
    const [country, phone] = value.split('-');
    countryCode = country || '';
    phoneNumber = phone || '';
  }

  return [countryCode, phoneNumber];
};
