@use "sass:color";
@use "sass:math";
@use "sass:string";
@use "./variables" as *;

// Functions

// Replace `$search` with `$replace` in `$string`
// Used on our SVG icon backgrounds for custom forms.
// @author Hugo Giraudel
// @param {String} $string - Initial string
// @param {String} $search - Substring to replace
// @param {String} $replace ('') - New value
// @return {String} - Updated string

@function str-replace($string, $search, $replace: "") {
  $index: string.index($string, $search);

  @if $index {
    $new: str-replace(string.slice($string, $index + string.length($search)), $search, $replace);

    @return (string.slice($string, 1, $index - 1) + $replace + $new);
  }

  @return $string;
}

// See https://codepen.io/kevinweber/pen/dXWoRw
// Requires the use of quotes around data URIs.

@function escape-svg($string) {
  @if string.index($string, "data:image/svg+xml") {
    @each $char, $encoded in $escaped-characters {
      // Do not escape the url brackets

      @if string.index($string, "url(") == 1 {
        $string: url("#{str-replace(string.slice($string, 6, -3), $char, $encoded)}");
      } @else {
        $string: str-replace($string, $char, $encoded);
      }
    }
  }

  @return $string;
}

@function color-flip($key, $value, $threshold: $color-flip-threshold, $lightness: $color-flip-l, $opacity: 100%) {
  $color-sum: math.max(color.channel($value, "lightness", $space: hsl), 0%);

  @if $color-sum > $threshold {
    @return hsl(from var(--html-color) h s l / $opacity);
  } @else {
    @return hsl(from var(--white) h s l / $opacity);
  }
}
