@use 'sass:string';
@use 'sass:math';
@use 'sass:meta';
@use 'sass:list';
@use 'strip-unit' as *;
@use 'is-number' as *;
@use 'list-update' as *;
@use '../variables' as *;

/// Converts `rem` value(s) into pixel units. Can be a single value of a List of
/// values. Unitless values are assumed to be in `rem` units.
///
/// @param {List | Number} $rems - Values in `rem` units.
/// @param {Number} $base - The base font-size.
///
/// @return {List | Number} The value(s) in pixels `px`.
///
/// @access public
/// @group Utilities
@function conv-to-px($rems, $base: null) {
  $px-vals: ();

  @each $value in $rems {
    @if is-number($value) and math.is-unitless($value) {
      $rems: update-list($rems, $value, $value * 1rem);

      $value: $value * 1rem;
    }

    @if not is-number($value) or math.unit($value) != 'rem' {
      @error 'Invalid $rems value of [ #{meta.inspect($value)} ] passed to the ' +
          '[ conv-to-px() ] function. You must pass a valid length in rem ' +
          'units, or a List containing only such values.';
    }
  }

  // If no base is defined, defer to the $base-font-size variable. If that does
  // not exist, default to 16
  @if not $base {
    $base: if(
      meta.variable-exists('base-font-size') or
      meta.global-variable-exists('base-font-size'),
      $base-font-size,
      16
    );
  }

  // If the base font size is a %, then divide by 100% and multiply it by 16px
  // This is because 100% font size = 16px by default in browsers.
  @if math.unit($base) == '%' {
    $base: math.div($base, 100%) * 16;
  }

  @if math.unit($base) == 'rem' or math.unit($base) == 'em' {
    $base: strip-unit($base) * 16;
  }

  @if math.unit($base) == 'px' {
    $base: strip-unit($base);
  }

  @each $val in $rems {
    $val-in-pixels: strip-unit($val) * $base * 1px;
    $px-vals: list.append($px-vals, $val-in-pixels);
  }

  @if length($px-vals) == 1 {
    @return list.nth($px-vals, 1);
  } @else {
    @return $px-vals;
  }
}
