// Global functions.
@use 'sass:math';

// Pixels to ems.
@function pxEm($px) {
  @return math.div($px, $base-font-size) * 1em;
}

// Pixels to rems.
@function pxRem($px) {
  @return math.div($px, $base-font-size) * 1rem;
}

/*
  @desc  Cast a value to a rem or em if necessary.

  @param {length | number} $length - A px length or unitless number.
  @param {boolean} $rem (optional) - Cast the provided px length or unitless number to a rem. When false, casts to em instead.
*/
@function pxCast($length, $rem: true) {
  @if unitless($length) and $length != 0 {
    @error 'pxCast: $length is unitless and non-zero.';
  }
  $casted: if(unitless($length), $length * 1px, $length);
  @return if($rem, pxRem($casted), pxEm($casted));
}

//  @desc Scale a value from one screen width to another based on the difference between the minimum
//    and maximum values. Requires clamp() support.
//  @param {length()} $widths - List of lengths, in px, representing the range to scale between the min and max values.
//  @param {length()} $values - List of lengths, in px, representing the min and max values to scale between.
//  @param {boolean} $rem (optional) - output units in rems. When false, outputs units in ems.
//  @example <caption>Between screen sizes of 744px and 1140px, linearly scale the padding from 20px to 40px.</caption>
//  .selector {
//    padding: generateScaling((744px 1140px), (20px 40px));
//  }
//  @returns clamp($min-value, <responsive-value>, $max-value)
@function generateScaling($widths, $values, $rem: true) {
  $params: (
    'min-width': pxCast(nth($widths, 1), $rem),
    'max-width': pxCast(nth($widths, 2), $rem),
    'min-value': pxCast(nth($values, 1), $rem),
    'max-value': pxCast(nth($values, 2), $rem),
  );

  $min-width: map-get($params, 'min-width');
  $max-width: map-get($params, 'max-width');
  $min-value: map-get($params, 'min-value');
  $max-value: map-get($params, 'max-value');

  $width-difference: math.div(1, $max-width - $min-width);
  $value-difference: $max-value - $min-value;
  $rate: $width-difference * $value-difference;

  $responsive-value: unquote(
    '#{$min-value - ($min-width * $rate)} + #{100vw * $rate}'
  );
  @return clamp(
    if($min-value < $max-value, $min-value, $max-value),
    $responsive-value,
    if($max-value > $min-value, $max-value, $min-value)
  );
}

// Creates an alpha value for a color.
// @param {color} $color - The color to apply the alpha to.
// @param {number} $alpha - The alpha value to apply to the color, ether a percentage of transparency or a decimal value.
@function color-alpha($color, $alpha) {
  @if (unit($alpha) != '%') {
    $alpha: (1 - $alpha) * 100%;
  }
  @return color-mix(in srgb, $color, transparent $alpha);
}
