@use "sass:color";
@use "sass:math";
@use "sass:meta";

/// Generates a triangle SVG element and applies it as a background image.
///
/// @author John Hildenbiddle (@jhildenbiddle)
///
/// @param  {up|down|left|right} $direction - Direction of triangle
/// @param  {Length} $width [16px]  - Width of triangle (px)
/// @param  {Length} $height [16px] - Height of triangle (px)
/// @param  {Color} $color [black]  - Color of triangle
/// @return {String}                - URL-encoded SVG data uri
///
/// @example scss
/// .myclass {
///   background-image: triangle-data-uri(right);
///   background-repeat: no-repeat;
///   background-position: left center;
/// }
///
/// .myclass {
///   background: triangle-data-uri(right) no-repeat left center;
/// }
@function triangle-data-uri($direction, $width: null, $height: null, $color: black) {
    // Default size
    @if $width == null and $height == null {
        $width : 16;
        $height: $width;
    }
    // Equal height/width when one dimension is specified
    @else {
        $width : if($width == null, $height, $width);
        $height: if($height == null, $width, $height);
    }

    // Strip units
    $width : math.div($width, $width * 0 + 1);
    $height: math.div($height, $height * 0 + 1);

    // Convert color to RGB
    @if meta.type-of($color) == color {
        $color: 'rgb%28#{color.red($color)}, #{color.green($color)}, #{color.blue($color)}%29';
    }

    // Polygon points
    $polygon-points: '';

    @if $direction == up {
        $polygon-points: '0,#{$height} #{$width},#{$height} #{$width * 0.5},0';
    }
    @else if $direction == down {
        $polygon-points: '0,0 #{$width},0 #{$width * 0.5},#{$height}';
    }
    @else if $direction == right {
        $polygon-points: '0,0 0,#{$height} #{$width},#{$height * 0.5}';
    }
    @else if $direction == left {
        $polygon-points: '#{$width},0 #{$width},#{$height} 0,#{$height * 0.5}';
    }

    @if $polygon-points == '' {
        @error "triangle-data-uri: #{$direction} is not a valid direction";
    }
    @else {
        // Unencoded SVG: <svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='#{$width}' height='#{$height}' viewBox='0 0 #{$width} #{$height}'><polygon points='#{$polygon-points}' style='fill: #{$color}'></polygon></svg>
        @return url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' width='#{$width}' height='#{$height}' viewBox='0 0 #{$width} #{$height}'%3E%3Cpolygon points='#{$polygon-points}' style='fill: #{$color}'%3E%3C/polygon%3E%3C/svg%3E");
    }
}
