/**
 * EverQuest Currency Conversion
 * 1 sat = 1 copper
 * 100 copper = 1 silver
 * 100 silver = 1 gold  
 * 100 gold = 1 platinum
 */

export interface EverQuestCurrency {
  platinum: number
  gold: number
  silver: number
  copper: number
}

export function satoshisToEverQuest(satoshis: number): EverQuestCurrency {
  // Convert satoshis to copper (1 sat = 1 copper)
  let copper = satoshis
  
  // Convert to higher denominations
  const platinum = Math.floor(copper / 1000000) // 100 gold = 1 platinum
  copper %= 1000000
  
  const gold = Math.floor(copper / 10000) // 100 silver = 1 gold
  copper %= 10000
  
  const silver = Math.floor(copper / 100) // 100 copper = 1 silver
  copper %= 100
  
  return {
    platinum,
    gold,
    silver,
    copper
  }
}

export function formatEverQuestCurrency(currency: EverQuestCurrency): string {
  const parts: string[] = []
  
  if (currency.platinum > 0) {
    parts.push(`${currency.platinum}p`)
  }
  
  if (currency.gold > 0) {
    parts.push(`${currency.gold.toString().padStart(2, '0')}g`)
  }
  
  if (currency.silver > 0) {
    parts.push(`${currency.silver.toString().padStart(2, '0')}s`)
  }
  
  if (currency.copper > 0) {
    parts.push(`${currency.copper.toString().padStart(2, '0')}c`)
  }
  
  // If no currency, show 0c
  if (parts.length === 0) {
    return '00c'
  }
  
  return parts.join(' ')
}

export function formatWalletBalance(balanceMsat: number): string {
  // Convert msat to satoshis (1 sat = 1000 msat)
  const satoshis = Math.floor(balanceMsat / 1000)
  const currency = satoshisToEverQuest(satoshis)
  return formatEverQuestCurrency(currency)
}

// Test examples:
// 100 sat = 1s (1 silver)
// 10000 sat = 1g (1 gold) 
// 1000000 sat = 1p (1 platinum)
// 1234567 sat = 1p 2g 3s 4c 