@use "sass:math";

$yiq-contrasted-threshold:  150 !default;

// Color contrast
@function color-yiq($color, $dark: $yiq-text-dark, $light: $yiq-text-light) {
    $r: red($color);
    $g: green($color);
    $b: blue($color);

    $yiq: math.div((($r * 299) + ($g * 587) + ($b * 114)), 1000);

    @if ($yiq >= $yiq-contrasted-threshold) {
        @return $dark;
    } @else {
        @return $light;
    }
}

@function theme-color($key: "primary") {
    @return map-get($theme-colors, $key);
}

// Return valid calc
@function add($value1, $value2, $return-calc: true) {
    @if $value1 == null {
        @return $value2;
    }

    @if $value2 == null {
        @return $value1;
    }

    @if type-of($value1) == number and type-of($value2) == number and comparable($value1, $value2) {
        @return $value1 + $value2;
    }

    @return if($return-calc == true, calc(#{$value1} + #{$value2}), $value1 + unquote(" + ") + $value2);
}

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

    @if $index {
        @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
    }

    @return $string;
}

@function escape-svg($string) {
    @if str-index($string, "data:image/svg+xml") {
        @each $char, $encoded in $escaped-characters {
            // Do not escape the url brackets
            @if str-index($string, "url(") == 1 {
                $string: url("#{str-replace(str-slice($string, 6, -3), $char, $encoded)}");
            } @else {
                $string: str-replace($string, $char, $encoded);
            }
        }
    }

    @return $string;
}

@function subtract($value1, $value2, $return-calc: true) {
    @if $value1 == null and $value2 == null {
        @return null;
    }

    @if $value1 == null {
        @return -$value2;
    }

    @if $value2 == null {
        @return $value1;
    }

    @if type-of($value1) == number and type-of($value2) == number and comparable($value1, $value2) {
        @return $value1 - $value2;
    }

    @return if($return-calc == true, calc(#{$value1} - #{$value2}), $value1 + unquote(" - ") + $value2);
}
