/**
 * Format phone number: +998 00 111-22-33 yoki +888 00 111-22-33
 */
const formatPhone = (value: string) => {
  // faqat raqamlarni olish
  const digits = value.replace(/\D/g, "");

  // agar hech narsa yo'q bo'lsa — input bo'sh bo'lib tursin
  if (digits.length === 0) return "";

  // prefiksni aniqlash (faqat agar 998 yoki 888 bilan boshlangan bo'lsa)
  let prefix = "";
  if (digits.startsWith("998")) prefix = "+998 ";
  else if (digits.startsWith("888")) prefix = "+888 ";

  // agar 998 ham 888 ham emas bo‘lsa — foydalanuvchi hali prefiks kiritmagan, hech narsa qaytarmaymiz
  if (!prefix) return "+" + digits;

  // prefiksni olib tashlab, asosiy raqam qismini olish
  const core = digits.replace(/^998|^888/, "");

  let formattedNumber = prefix;

  if (core.length > 0) formattedNumber += core.slice(0, 2);
  if (core.length > 2) formattedNumber += " " + core.slice(2, 5);
  if (core.length > 5) formattedNumber += "-" + core.slice(5, 7);
  if (core.length > 7) formattedNumber += "-" + core.slice(7, 9);

  return formattedNumber.trim();
};

export default formatPhone;
