////
/// @group Main
////
@use "sass:list";
@use "sass:map";
@use 'sass:math';

/// Generate `clamp()` to smoothly scale a value between two breakpoints
/// @param {Map} $map - Map of breakpoints and values
/// @param {String} $units [vw] - Optionally specify container query units
/// @return {String} - Custom `clamp()` formula
/// @link https://chrisburnell.com/clamp-calculator/
/// @link https://www.smashingmagazine.com/2023/11/addressing-accessibility-concerns-fluid-type/
///
/// @example scss
///   p {
///     font-size: scale-clamp((375px: 16px, 960px: 20px));
///   }
///
@function scale-clamp($map, $units: vw) {
  // Formulas:
  //
  //   Change = (sizeMax - sizeMin) / (viewportMax - viewportMin);
  //   A = 100vw * Change;
  //   B = sizeMax - viewportMax * Change;
  //   Result = clamp(sizeMin, A + B, sizeMax);
  //
  $breakpoints: map.keys($map);
  $values: map.values($map);
  $min-width: list.nth($breakpoints, 1);
  $max-width: list.nth($breakpoints, 2);
  $start: list.nth($values, 1);
  $end: list.nth($values, 2);
  $change: math.div($end - $start, $max-width - $min-width);
  $b: $end - ($max-width * $change);

  // Add support for container query units
  // https://caniuse.com/css-container-query-units
  $width: 100vw;
  @if $units == 'cqw' {
    $width: 100cqw;
  } @else if $units == 'cqh' {
    $width: 100cqh;
  } @else if $units == 'cqi' {
    $width: 100cqi;
  } @else if $units == 'cqb' {
    $width: 100cqb;
  }

  $a: $width * $change;

  // Round to 3 decimal places
  // Note: Additional decimal places won’t have any effect on the computed
  //       value and makes it harder to read in the dev tools.
  $a: math.div(math.round($a * 1000), 1000);
  $b: math.div(math.round($b * 1000), 1000);

  // This will reduce the value as the viewport width increases
  @if $start > $end {
    @return clamp(#{$end}, #{$a} + #{$b}, #{$start});
  }

  @return clamp(#{$start}, #{$a} + #{$b}, #{$end});
}
