// Functions: Unit Convert

@use 'sass:math';
@use 'sass:meta';
@use 'gesso' as *;
@use 'numbers' as *;

/// Convert unitless number to unit value
// @param {Number} $value - unitless number
// @return {String} - unit type
@function convert($value, $unit: px) {
  @if math.is-unitless($value) {
    @if $unit == px {
      @return $value * 1px;
    }
    @if $unit == em {
      @return $value * 1em;
    }
  } @else {
    @return $value;
  }
}

/// Convert values to px.
// @param {Number} $value - Value to convert. Can be px, em, or rem.
//   If unitless, pixels are assumed.
// @param {Number} $base - Base font size in pixels.
// @return {Number} - Value in pixels.
@function px($value, $base: gesso-get-map(typography, base-font-size)) {
  @if math.is-unitless($value) {
    @return convert($value, px);
  }
  @if (meta.type-of($base) != 'number' or math.unit($base) != 'px') {
    @error 'Base font size must be in pixels.';
  }
  @if (math.unit($value) != 'px') {
    @return strip-unit($value) * $base;
  } @else {
    @return $value;
  }
}

/// Convert values to em.
// @param {Number} $value - Value to convert. Can be px, em, or rem.
//   If unitless, pixels are assumed.
// @param {Number} $base - Base font size in pixels.
// @return {Number} - Value in ems.
@function em($value, $base: gesso-get-map(typography, base-font-size)) {
  @if (meta.type-of($base) != 'number' or math.unit($base) != 'px') {
    @error 'Base font size must be in pixels.';
  }
  @if (meta.type-of($value) == 'number' and math.unit($value) != 'em') {
    @if (math.unit($value) != 'px') {
      $value: px($value, $base);
    }
    @return (math.div($value, $base)) * 1em;
  }
  @return $value;
}

/// Convert values to rem.
// @param {Number} $value - Value to convert. Can be px, em, or rem.
//   If unitless, pixels are assumed. If ems, size will be converted using
//   the same base (so 0.5em is equal to 0.5rem). If you want to convert using
//   a different font size, do rem(px($emValue, $emBase), $remBase).
// @param {Number} $base - Base font size in pixels.
// @return {Number} - Value in rems.
@function rem($value, $base: gesso-get-map(typography, base-font-size)) {
  @if (meta.type-of($base) != 'number' or math.unit($base) != 'px') {
    @error 'Base font size must be in pixels.';
  }
  @if (meta.type-of($value) == 'number' and math.unit($value) != 'rem') {
    @if (math.unit($value) != 'px') {
      $value: px($value, $base);
    }
    @return (math.div($value, $base)) * 1rem;
  }
  @return $value;
}
