import type { SharedData } from '@/types';
import { usePage } from '@inertiajs/react';

type CurrencyDisplay = 'symbol' | 'code';

export function useCurrency() {
  const { branding, locale } = usePage<SharedData>().props;

  const defaultCurrency = branding?.branding?.site_currency ?? 'USD';
  const resolvedLocale = locale ?? 'en-US';

  const format = (
    amount: number | string,
    display: CurrencyDisplay = 'symbol',
    currencyOverride?: string,
  ): string => {
    const numericAmount = Number(amount);
    const currency = (currencyOverride ?? defaultCurrency).toUpperCase();

    if (Number.isNaN(numericAmount)) return '0.00';

    try {
      if (display === 'symbol') {
        return new Intl.NumberFormat(resolvedLocale, {
          style: 'currency',
          currency,
        }).format(numericAmount);
      }

      const numberOnly = new Intl.NumberFormat(resolvedLocale, {
        style: 'decimal',
      }).format(numericAmount);

      return `${numberOnly} ${currency}`;
    } catch {
      const formatted = numericAmount.toLocaleString(resolvedLocale);
      return display === 'code' ? `${formatted} ${currency}` : formatted;
    }
  };

  return {
    currency: defaultCurrency,
    locale: resolvedLocale,
    format,
  };
}
