import { resolveLocaleForElement } from '../shared/locale';

function formatRawValue(raw: string, formatter: Intl.NumberFormat): string | null {
  const numeric = Number.parseFloat(raw);
  if (!Number.isFinite(numeric)) {
    return null;
  }

  return formatter.format(numeric);
}

export function initExchangeRatesFormatting(): void {
  const widgets = document.querySelectorAll<HTMLElement>('.crtoday-widget.crtoday-exchange-rates');

  widgets.forEach((widget) => {
    const decimals = Number.parseInt(widget.dataset.crtodayDecimals || '2', 10);
    const locale = resolveLocaleForElement(widget);

    const formatter = new Intl.NumberFormat(locale, {
      minimumFractionDigits: Number.isFinite(decimals) ? decimals : 2,
      maximumFractionDigits: Number.isFinite(decimals) ? decimals : 2,
      useGrouping: true,
    });

    widget.querySelectorAll<HTMLElement>('.crtoday-rate-value[data-crtoday-raw]').forEach((valueEl) => {
      const raw = valueEl.dataset.crtodayRaw;
      if (!raw) {
        return;
      }

      const formatted = formatRawValue(raw, formatter);
      if (formatted !== null) {
        valueEl.textContent = formatted;
      }
    });
  });
}
