@use 'sass:meta';
@use 'sass:math';
@use 'is-number' as *;
@use '../variables/misc' as *;

/// Converts a pixel value into `em` units (based on the root font-size).
/// Unitless values are assumed to be in pixels.
///
/// @param {Number} $pixels - A value to convert to em units.
/// @param {Number} $base [null] - The contextual base font-size.
///
/// @return {Number} The value in `em` units.
///
/// @access public
/// @group Utilities
/// @require {function} is-number
/// @require {variable} $base-font-size
///
/// @throw Invalid data type or units for $pixels
@function conv-to-em($pixels, $base: null) {
  @if not is-number($pixels) or (
    not math.is-unitless($pixels) and math.unit($pixels) != 'px'
  ) {
    @error 'Invalid value of [ #{meta.inspect($pixels)} ] passed to the ' +
        '[ conv-to-em() ] function. Value of $pixels must be number in px units.';
  }

  // If no base font-size is passsed to the function as $base,
  // use 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 multiply it by 16px
  // This is because 100% font size = 16px by default
  @if math.unit($base) == '%' {
    $base: math.div($base, 100%) * 16px;
  }

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

  @if math.is-unitless($base) {
    $base: $base * 1px;
  }

  @if math.is-unitless($pixels) {
    $pixels: $pixels * 1px;
  }

  @return math.div($pixels, $base) * 1em;
}
