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

/* stylelint-disable max-nesting-depth */
@mixin generate-utility($utility, $infix: '') {
  $values: map.get($utility, values);

  // If the values are a list or string, convert it into a map
  @if meta.type-of($values) == 'string' or meta.type-of(list.nth($values, 1)) != 'list' {
    $values: list.zip($values, $values);
  }

  @each $key, $value in $values {
    $properties: map.get($utility, property);

    // Multiple properties are possible, for example with vertical or horizontal margins or paddings
    @if meta.type-of($properties) == 'string' {
      $properties: list.append((), $properties);
    }

    // Check if the class value is a list (multiple classes)
    $class-list: list.nth($properties, 1);
    @if map.has-key($utility, class) {
      $class-list: map.get($utility, class);
    }

    @if meta.type-of($class-list) != 'list' {
      $class-list: ($class-list);
    }

    // Use custom CSS variable name if present, otherwise default to `class`
    $css-variable-name: map.get($utility, class);
    @if map.has-key($utility, css-variable-name) {
      $css-variable-name: map.get($utility, css-variable-name);
    }

    // State params to generate pseudo-classes
    $state: ();
    @if map.has-key($utility, state) {
      $state: map.get($utility, state);
    }

    @if $class-list == null and string.slice($infix, 1, 1) == '-' {
      $infix: string.slice($infix, 2);
    }

    // Don't prefix if value key is null (e.g. with shadow class)
    $property-class-modifier: '';
    @if $key {
      $property-class-modifier: $key;
      @if $class-list != null or $infix != '' {
        $property-class-modifier: '-#{$key}';
      }
    }

    $is-css-var: map.get($utility, css-var);
    $is-local-vars: map.get($utility, local-vars);

    @if $value != null {
      $class-selectors: ();

      @each $class in $class-list {
        $class-selectors: list.append(
          $class-selectors,
          '.#{$class + $infix + $property-class-modifier}',
          comma
        );
      }

      $class-selectors: list.join($class-selectors, ', ');

      @if $is-css-var {
        #{$class-selectors} {
          --post-#{$css-variable-name}: #{$value};
        }
      } @else {
        #{$class-selectors} {
          @each $property in $properties {
            @if $is-local-vars {
              @each $local-var, $variable in $is-local-vars {
                --post-#{$local-var}: #{$variable};
              }
            }
            #{$property}: $value !important;
          }
        }
      }
    }
  }
}
/* stylelint-enable max-nesting-depth */
