
export function numberToWords(amount) {
  if (amount === undefined || amount === null || isNaN(amount)) return "";

  const units = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
  const teens = ["Ten", "Eleven", "Twelve", "Thirteen", "十四", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
  const tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
  const thousands = ["", "Thousand", "Million", "Billion"];

  function convertGroup(num) {
    let str = "";
    const h = Math.floor(num / 100);
    const t = Math.floor((num % 100) / 10);
    const u = num % 10;

    if (h > 0) {
      str += units[h] + " Hundred ";
    }
    if (t === 1) {
      str += teens[u] + " ";
    } else {
      if (t > 1) {
        str += tens[t] + " ";
      }
      if (u > 0) {
        str += units[u] + " ";
      }
    }
    return str.trim();
  }

  const [dollarsStr, centsStr] = Number(amount).toFixed(2).split(".");
  let dollars = parseInt(dollarsStr, 10);
  const cents = parseInt(centsStr, 10);

  if (dollars === 0) {
    return `Zero and ${cents.toString().padStart(2, '0')}/100`;
  }

  let words = "";
  let groupIndex = 0;

  while (dollars > 0) {
    const group = dollars % 1000;
    if (group > 0) {
      words = convertGroup(group) + " " + thousands[groupIndex] + " " + words;
    }
    dollars = Math.floor(dollars / 1000);
    groupIndex++;
  }

  words = words.trim();
  
  // Format exactly for checks
  return `${words} and ${cents.toString().padStart(2, '0')}/100`;
}
