@use "sass:color";
@use "sass:list";
@use "sass:map";
@use "sass:math";
@use "sass:meta";
@use "sass:string";

/// Casts a string into a number
/// https://hugogiraudel.com/2014/01/15/sass-string-to-number/
/// @author Hugo Giraudel
/// @param {String | Number} $value - Value to be parsed
/// @return {Number} - $value converted to a number
@function to-number($value) {
    @if meta.type-of($value) == "number" {
        @return $value;
    } @else if meta.type-of($value) != "string" {
        @warn "Value for `to-number` should be a number or a string.";
    }

    $result: 0;
    $digits: 0;
    $minus: string.slice($value, 1, 1) == "-";
    $numbers: (
        "0": 0,
        "1": 1,
        "2": 2,
        "3": 3,
        "4": 4,
        "5": 5,
        "6": 6,
        "7": 7,
        "8": 8,
        "9": 9,
    );

    $start: 1;
    @if $minus {
        $start: 2;
    }

    @for $i from $start through string.length($value) {
        $character: string.slice($value, $i, $i);

        @if not(list.index(map.keys($numbers), $character) or $character == ".")
        {
            $signed-result: $result;
            @if $minus {
                $signed-result: -$result;
            }
            @return to-length($signed-result, string.slice($value, $i));
        }

        @if $character == "." {
            $digits: 1;
        } @else if $digits == 0 {
            $result: $result * 10 + map.get($numbers, $character);
        } @else {
            $digits: $digits * 10;
            $result: $result + math.div(map.get($numbers, $character), $digits);
        }
    }

    @if $minus {
        @return -$result;
    }
    @return $result;
}

/// Add `$unit` to `$value`
/// @param {Number} $value - Value to add unit to
/// @param {String} $unit - String representation of the unit
/// @return {Number} - `$value` expressed in `$unit`
@function to-length($value, $unit) {
    $units: (
        "px": 1px,
        "cm": 1cm,
        "mm": 1mm,
        "%": 1%,
        "ch": 1ch,
        "pc": 1pc,
        "in": 1in,
        "em": 1em,
        "rem": 1rem,
        "pt": 1pt,
        "ex": 1ex,
        "vw": 1vw,
        "vh": 1vh,
        "vmin": 1vmin,
        "vmax": 1vmax,
    );

    @if not list.index(map.keys($units), $unit) {
        @warn "Invalid unit `#{$unit}`.";
    }

    @return $value * map.get($units, $unit);
}

/// Gjør en fargeverdi URL-safe, for eksempel til bruk i inline SVG
/// @param {Color} $color - Sass fargetype. Kan være HEX, hsl, hsla, rgb eller rgba.
/// @return {String} - input konvertert til en URL-safe HEX-verdi
@function urlencodecolor($color) {
    @if meta.type-of($color) == "color" and string.index(#{$color}, "#") == 1 {
        $hex: string.slice(color.ie-hex-str($color), 4);
        $converted-color: string.unquote("#{$hex}");

        @return "%23" + $converted-color;
    }

    @return $color;
}
