import { useCallback, useMemo } from "react";

export function unwrapFirstValue<T>(value: T | T[] | undefined): T | undefined {
  if (Array.isArray(value)) {
    return value[0];
  }
  return value;
}

export function wrapValue<T>(value: T | undefined): T[] | undefined {
  return value === undefined ? undefined : [value];
}

export function useUnwrappedHandler<T>(
  handler: ((value: T | undefined) => void) | undefined,
) {
  return useCallback(
    (value: T | T[]) => {
      handler?.(unwrapFirstValue(value));
    },
    [handler],
  );
}

export function useWrappedValue<T>(value: T | undefined): T[] | undefined {
  return useMemo(() => wrapValue(value), [value]);
}

export function numberFormatter(
  value: number | string | undefined,
  formatOptions?: Intl.NumberFormatOptions,
  locale = navigator.languages?.[0] || "en-GB",
): string {
  if (!formatOptions) {
    return value?.toString() || "";
  }

  return new Intl.NumberFormat(locale, formatOptions).format(+(value || 0));
}
