'use client';

/**
 * Hook that returns a currency formatting function based on the
 * currently selected currency in the currency store.
 *
 * Usage:
 *   const fmtCurrency = useCurrencyFormatter();
 *   fmtCurrency(1234.5) → "$1,234.50" (or equivalent in selected currency)
 */

import { useMemo, useCallback } from 'react';
import { useCurrencyStore } from '@/lib/stores/currency-store';

export function useCurrencyFormatter() {
  const { currency } = useCurrencyStore();

  const formatter = useMemo(
    () =>
      new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: currency.code,
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
    [currency.code]
  );

  return (n: number): string => formatter.format(n);
}

/**
 * Hook that returns a compact currency formatter for chart Y axis ticks.
 * Produces short labels like "$35K", "€1.2M", "£500" using the active currency symbol.
 *
 * Usage:
 *   const fmtAxis = useCurrencyAxisFormatter();
 *   <LineChartWidget yAxisFormatter={fmtAxis} ... />
 */
export function useCurrencyAxisFormatter() {
  const { currency } = useCurrencyStore();

  return useCallback(
    (value: number): string => {
      const abs = Math.abs(value);
      const sign = value < 0 ? '-' : '';
      const sym = currency.symbol;

      if (abs >= 1_000_000_000) {
        return `${sign}${sym}${(abs / 1_000_000_000).toFixed(1)}B`;
      }
      if (abs >= 1_000_000) {
        return `${sign}${sym}${(abs / 1_000_000).toFixed(1)}M`;
      }
      if (abs >= 1_000) {
        return `${sign}${sym}${(abs / 1_000).toFixed(0)}K`;
      }
      return `${sign}${sym}${abs}`;
    },
    [currency.symbol]
  );
}

/**
 * Hook that returns a compact currency formatter for displaying values in cards/lists.
 * Produces labels like "$4.8 M", "€120.0 K", "£500" using the active currency symbol.
 * Similar to formatCLP but uses the configured currency.
 *
 * Usage:
 *   const fmtMoney = useCompactCurrencyFormatter();
 *   fmtMoney(4760000) → "$4.8 M"
 */
export function useCompactCurrencyFormatter() {
  const { currency } = useCurrencyStore();

  return useCallback(
    (n: number): string => {
      const abs = Math.abs(n);
      const sign = n < 0 ? '-' : '';
      const sym = currency.symbol;

      if (abs >= 1_000_000) {
        return `${sign}${sym} ${(abs / 1_000_000).toFixed(1)} M`;
      }
      if (abs >= 1_000) {
        return `${sign}${sym} ${(abs / 1_000).toFixed(1)} K`;
      }
      return `${sign}${sym} ${Math.round(abs)}`;
    },
    [currency.symbol]
  );
}
