////
/// Core Function : Spacing space
/// @group core
////

@use 'sass:math';
@use 'sass:meta';
@use 'sass:string';
@use 'sass:list';
@use 'src/module/string' as str;

@function _join($value) {
  @if meta.type-of($value) != list {
    @return $value;
  }

  $separator: ' ';
  @if list.separator($value) == comma {
    $separator: ', ';
  }

  @return str.join($value, $separator);
}

/// Return space value from type map and convert to rem.
///
/// @param {Number} $value - valeur de l'espacement, permet de convertir cet espacement de v (4px) ou w (8px) en rem
///
/// @example scss - Set margin-bottom to 24px
///   .foo {
///     margin-bottom: space(6v);
///   }
@function space($value) {
  $type: meta.type-of($value);
  // @debug $type $value;
  @if $type == map {
    @error 'space function with map';
  }

  @if $type == arglist {
    @error 'space function with arglist';
  }

  @if $type == function {
    @error 'space function with function';
  }

  @if $type == color {
    @return $value;
  }

  @if $type == bool {
    @return $value;
  }

  @if $type == calculation {
    @return space('#{$value}');
  }

  @if $type == list {
    $list: ();
    $separator: list.separator($value);
    @each $v in $value {
      $list: append($list, space($v), $separator);
    }
    @return $list;
  }

  @if $type == number {
    $u: math.unit($value);

    @if $u == 'v' {
      @return math.div($value, 1v) * $V;
    }

    @if $u == 'w' {
      @return math.div($value, 1w) * $W;
    }

    @return $value;
  }

  @if $type == string {
    $c: string.index($value, '(');

    @if $c {
      $b: null;
      $n: 0;
      $i: $c + 1;
      $l: string.length($value);
      @while $b == null and $i <= $l {
        $char: string.slice($value, $i, $i);
        @if $char == '(' {
          $n: $n + 1;
        }
        @else if $char == ')' {
          @if $n > 0 {
            $n: $n - 1;
          }
          @else {
            $b: $i;
          }
        }
        $i: $i + 1;
      }

      $start: unquote('');
      $middle: space(string.slice($value, $c + 1, $b - 1));
      $end: unquote('');

      @if $c > 1 {
        $start: _join(space(string.slice($value, 1, $c - 1)));
      }

      $l: str-length($value);
      @if $b < $l {
        $end: _join(space(string.slice($value, $b + 1, $l)));
      }

      @return unquote('#{$start}(#{$middle})#{$end}');
    }

    @if string.index($value, ',') != null {
      @return space(str-split($value, ','));
    }

    @if string.index($value, ' ') != null {
      $list: str.split($value, ' ');
      $result: ();
      @each $item in $list {
        $result: append($result, space($item), space);
      }
      @return $result;
    }

    @if str.is-num($value) {
      @return space(str.to-num($value));
    }

    @return unquote($value);
  }

  @return $value;
}
