import { breakpointNames } from "../../../atoms/breakpoint/index.js";
import useBreakpointName from '../useBreakpointName';

/**
 * Resolve a responsive value map based on the current breakpoint measurement.
 * If the provided value is an object with at least one breakpoint name as
 * a key, then it's interpreted as a responsive value map; otherwise, if it's
 * either not an object, or none of its keys are breakpoint names, the value is
 * returned as-is. A responsive value map is an object that maps breakpoint
 * names onto specific values to use at those breakpoints. It doesn't have to
 * map _all_ breakpoint names. For example, the responsive value map:
 *
 * ```js
 * {
 *   xs: 'red',
 *   md: 'black',
 * }
 * ```
 *
 * will resolve to the value `'red'` at `xs` and `sm` breakpoints, and to the
 * value `'black'` at `md`, `lg`, and `xl` breakpoints.
 *
 * @param {Object|any} values
 *   Either a plain value to use as-is at all breakpoints or a responsive value
 *   map.
 */
const useResponsiveValues = function useResponsiveValues(values, key = 'window') {
  const currentBreakpoint = useBreakpointName(key);
  if (typeof values !== 'object') return values;
  if (breakpointNames.every(name => typeof values[name] === 'undefined')) {
    return values;
  }
  const normalizedValues = breakpointNames.reduce((breakpoints, name, i) => {
    const lastName = breakpointNames[i - 1];
    const value = typeof values[name] === 'undefined' ? breakpoints.get(lastName) : values[name];
    breakpoints.set(name, value);
    return breakpoints;
  }, new Map());
  return normalizedValues.get(currentBreakpoint || 'xs');
};
export default useResponsiveValues;