/* global */
// Shared money formatter. Reads currency config from localStorage key 'vv-currency'
// (shape: { code:'USD'|'EUR'|'GBP'|..., symbol:'$', locale:'en-US' }) with a USD default.
(function(){
  const DEFAULT = { code:'USD', symbol:'$', locale:'en-US' };
  function getCfg(){
    try {
      const raw = localStorage.getItem('vv-currency');
      if (raw) return { ...DEFAULT, ...JSON.parse(raw) };
    } catch(e){}
    return DEFAULT;
  }
  function money(n, opts={}){
    const cfg = getCfg();
    const num = Number(n) || 0;
    const digits = opts.digits != null ? opts.digits : 2;
    // Prefer Intl if locale is real
    try {
      return new Intl.NumberFormat(cfg.locale, { style:'currency', currency: cfg.code, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(num);
    } catch(e){
      return `${cfg.symbol}${num.toFixed(digits)}`;
    }
  }
  function currencySymbol(){ return getCfg().symbol; }
  function setCurrency(cfg){
    try { localStorage.setItem('vv-currency', JSON.stringify({ ...DEFAULT, ...cfg })); } catch(e){}
    window.dispatchEvent(new CustomEvent('vv-currency-updated'));
  }
  window.vvFormat = { money, currencySymbol, setCurrency, getCurrency: getCfg };
})();
