// ==========================================================================
// ## TOOLS: FUNCTIONS
// ==========================================================================

@use 'sass:math';

/// @content Function that converts the given pixel value to its EM quivalent.
///
/// @param {Number} $size
///   The pixel value to convert.
///
/// @return {Number}
///   Scalable pixel value in EMs.
///
/// @access public
///
@function em($size) {
  @if (type-of($size) == number) {
    @if (unit($size) != 'px') {
      @error "`#{$size}` needs to be a pixel value.";
    }
  } @else {
    @error "`#{$size}` needs to be a number.";
  }

  @return math.div($size, $font-base-size) * 1em;
}

/// @content Function that converts the given pixel value to its REM quivalent.
///
/// @param {Number} $size
///   The pixel value to convert.
///
/// @return {Number}
///   Scalable pixel value in REMs.
///
/// @access public
///
@function rem($size) {
  @if (type-of($size) == number) {
    @if (unit($size) != 'px') {
      @error "`#{$size}` needs to be a pixel value.";
    }
  } @else {
    @error "`#{$size}` needs to be a number.";
  }

  @return math.div($size, $font-base-size) * 1rem;
}

// Breakpoint viewport sizes and media queries.
//
// Breakpoints are defined as a map of (name: minimum width), order from small to large:
// (xs: 576px, sm: 768px, md: 992px)
// The map defined in the `$breakpoints` global variable is used as the `$breakpoints` argument by default.
// Name of the next breakpoint, or null for the last breakpoint.
// >> breakpoint-next(sm) -> md
// >> breakpoint-next(sm, $breakpoints: (xs: 576px, sm: 768px, md: 992px)) -> md
// >> breakpoint-next(sm, $breakpoint-names: (xs sm md)) -> md
@function breakpoint-next(
  $name,
  $breakpoints: $breakpoints,
  $breakpoint-names: map-keys($breakpoints)
) {
  $n: index($breakpoint-names, $name);
  @return if(
    $n < length($breakpoint-names),
    nth($breakpoint-names, $n + 1),
    null
  );
}

// Minimum breakpoint width. Null for the smallest (first) breakpoint.
// >> breakpoint-min(sm, (xs: 576px, sm: 768px, md: 992px)) -> 768px
@function breakpoint-min($name, $breakpoints: $breakpoints) {
  $min: map-get($breakpoints, $name);
  @return if($min !=0, $min, null);
}

// Maximum breakpoint width. Null for the largest (last) breakpoint.
// The maximum value is calculated as the minimum of the next one less 0.1.
// >> breakpoint-max(sm, (xs: 576px, sm: 768px, md: 992px)) -> 991px
@function breakpoint-max($name, $breakpoints: $breakpoints) {
  $next: breakpoint-next($name, $breakpoints);
  @return if($next, breakpoint-min($next, $breakpoints) - 1, null);
}
