@use 'sass:list';
@use 'sass:map';
@use 'sass:meta';
@use 'sass:color';
@use 'sass:string';

@use '@haiilo/catalyst-tokens/dist/scss/variables' as *;
@forward '@haiilo/catalyst-tokens/dist/scss/variables' show $tokens;

// -----
// -- Split a string using the given separator.
// -----
@function -cat-split($string, $separator: ' ') {
  $result: ();
  $index: string.index($string, $separator);
  @while $index != null {
    $item: string.slice($string, 1, $index - 1);
    $result: list.append($result, $item);
    $string: string.slice($string, $index + string.length($separator));
    $index: string.index($string, $separator);
  }
  $result: list.append($result, $string);
  @return $result;
}

// -----
// -- Join strings using the given separator.
// -----
@function -cat-join($strings, $separator: ' ') {
  $result: '';
  @each $string in $strings {
    $result: $result + $separator + $string;
  }
  @return string.slice($result, string.length($separator) + 1);
}

// -----
// -- Deep map.get using a dot-separated key.
// -----
@function -cat-get($map, $key) {
  $keys: -cat-split('' + $key, '.');
  @each $key in $keys {
    @if $map {
      $map: map.get($map, $key);
    }
  }
  @return $map;
}

@function cat-token-wrap($value, $alpha: 1) {
  @if meta.type-of($value) == 'string' {
    @if meta.type-of($alpha) != 'number' or $alpha < 1 {
      @return rgba($value, $alpha);
    } @else {
      @return rgb($value);
    }
  } @else if meta.type-of($value) == 'list' {
    @return color.adjust(
      #00000000,
      $red: list.nth($value, 1),
      $green: list.nth($value, 2),
      $blue: list.nth($value, 3),
      $alpha: $alpha
    );
  } @else {
    @return $value;
  }
}

// -----
// -- Accessor for $tokens using a dot-separated key.
// -- Automatically wraps RGB partials into an rgb() expression and
// -- optionally adds an RGB alpha value.
// -----
@function cat-token($key, $alpha: 1, $wrap: true) {
  $value: -cat-get($tokens, $key);
  @if not $value {
    @error 'Unknown token "#{-cat-join($key, '.')}".';
  }
  @if string.index($key, 'color.') == 1 {
    @if $wrap {
      @return cat-token-wrap($value, $alpha);
    } @else if meta.type-of($alpha) != 'number' or $alpha < 1 {
      @return $value, $alpha;
    }
  }
  @return $value;
}
