import { CURRENCIES, type AppCurrency, type AppLocale } from "./types";

/** 方案等金額以 TWD 為基準單位（整數） */
export function convertFromTwd(amountTwd: number, currency: AppCurrency): number {
  const meta = CURRENCIES.find((c) => c.id === currency) || CURRENCIES[0]!;
  return amountTwd * meta.fromTwd;
}

export function formatMoney(
  amountTwd: number,
  currency: AppCurrency,
  locale: AppLocale,
): string {
  const meta = CURRENCIES.find((c) => c.id === currency) || CURRENCIES[0]!;
  const value = convertFromTwd(amountTwd, currency);
  const localeTag = locale === "en" ? "en-US" : "zh-TW";

  // JPY 無小數
  const fraction = currency === "JPY" ? 0 : currency === "TWD" ? 0 : 2;
  try {
    return new Intl.NumberFormat(localeTag, {
      style: "currency",
      currency,
      currencyDisplay: "symbol",
      minimumFractionDigits: fraction,
      maximumFractionDigits: fraction,
    }).format(value);
  } catch {
    const rounded =
      fraction === 0 ? Math.round(value) : Math.round(value * 100) / 100;
    return `${meta.symbol}${rounded.toLocaleString(localeTag)}`;
  }
}

/**
 * 方案月費金額（僅幣值，不含「／月」）。
 * 週期請在 UI 旁標一次，例如 `NT$590` + `／月`，避免疊成「／月／月」。
 */
export function formatPlanPrice(
  amountTwd: number,
  currency: AppCurrency,
  locale: AppLocale,
): string {
  return formatMoney(amountTwd, currency, locale);
}
