"use client";
import { useNumberInput } from "./useNumberInput.js";
import { bigIntToNumber } from "../../utils/bigIntToNumber.js";
import { formatBigInt } from "../../utils/formatBigInt.js";
import { numberToBigInt } from "../../utils/numberToBigInt.js";
const normalizeCurrency = (currency) => {
  if (typeof currency === "string") {
    return { code: currency, format: {} };
  }
  return currency;
};
function useCurrencyInput({
  useBigInt = false,
  precision = 18n,
  min = null,
  max = null,
  currency: passedCurrency = "GRT",
  convertedCurrency: passedConvertedCurrency = {
    code: "USD",
    format: { minimumFractionDigits: 2, maximumFractionDigits: 2 }
  },
  conversionRate,
  ...options
} = {}) {
  const currency = normalizeCurrency(passedCurrency);
  const convertedCurrency = normalizeCurrency(passedConvertedCurrency);
  const numberInput = useNumberInput({
    useBigInt,
    precision,
    min: min ?? (useBigInt ? 0n : 0),
    max,
    format: currency.format,
    ...options
  });
  let convertedAmount = void 0;
  let convertedValue = null;
  if (conversionRate !== void 0) {
    let convert;
    if (typeof conversionRate === "number" || typeof conversionRate === "bigint") {
      convert = (value) => {
        if (typeof value === "bigint") {
          const precisionFactor = 10n ** precision;
          return value * conversionRate / precisionFactor;
        } else {
          return value * conversionRate;
        }
      };
    } else {
      convert = conversionRate;
    }
    const valueToConvert = useBigInt ? numberInput.nonValidatedValue : bigIntToNumber(numberInput.nonValidatedValue, precision);
    const nonValidatedConvertedValue = convert(valueToConvert);
    convertedAmount = formatBigInt(
      typeof nonValidatedConvertedValue === "number" ? numberToBigInt(nonValidatedConvertedValue, precision) : nonValidatedConvertedValue,
      precision,
      convertedCurrency.format
    );
    if (numberInput.value !== null) {
      convertedValue = nonValidatedConvertedValue;
    }
  }
  const onMaxClicked = max !== null ? () => numberInput.setValue(max) : void 0;
  return {
    ...numberInput,
    convertedValue,
    props: {
      ...numberInput.props,
      currency: currency.code,
      convertedCurrency: convertedCurrency.code,
      convertedAmount,
      onMaxClicked
    }
  };
}
export {
  useCurrencyInput
};
