@use "sass:map";
@use "sass:math";
@use "sass:meta";
@use "sass:string";

@function pow($number, $exp) {
  $return: 1;

  @if $exp > 0 {
    // If the exponent is positive then multiply it
    @for $i from 1 through $exp {
      $return: $return * $number;
    }
  }
  @else if $exp < 0 {
    // If the number is 0 or negative then divide it
    @for $i from 1 through -$exp {
      $return: math.div($return, $number);
    }
  }

  @return $return;
}

@function modular-scale($exp, $size: $font-size-base, $type-scale: $type-scale) {
  @return pow($type-scale, $exp) * $size;
}

@function strip-unit($number) {
  @return math.div($number, $number * 0 + 1);
}

@function to-rem($value, $base: 16px) {
  @if (math.unit($value) == 'em') {
    $value: strip-unit($value) * 1rem;
  }

  @if (math.unit($value) != 'rem') {
    $value: math.div(strip-unit($value), strip-unit($base)) * 1rem;
  }

  @if (strip-unit($value) == 0) {
    $value: 0;
  }

  @return $value;
}

@function str-replace($string, $search, $replace: '') {
  $index: string.index($string, $search);

  @if $index {
    @return string.slice($string, 1, $index - 1) + $replace + str-replace(string.slice($string, $index + string.length($search)), $search, $replace);
  }

  @return $string;
}

// Usage example:
//
// .icon {
//   background-image: url(get-icon('radio', #fff));
// }
@function get-icon($icon, $color: $icon-color) {
  $color: meta.inspect($color);

  @if (string.index($color, '#') != null) {
    @if map.has-key($icons, $icon) {
      $icon: 'data:image/svg+xml;charset=utf8,' + map.get($icons, $icon);
      $icon: str-replace($icon, meta.inspect($icon-color), $color);

      @each $char, $encoded in ( ('<', '%3C'), ('>', '%3E'), ('#', '%23'), ('"', "'") ) {
        $icon: str-replace($icon, $char, $encoded);
      }
    }
    @else {
      @error "Please make sure '#{$icon}' is defined in the $icons map.";
    }
  }
  @else {
    @error "Please make sure '#{$color}' is a HEX value.";
  }

  @return $icon;
}
