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

// Design system spacing map
$dsSpacings: (
  0: 0,
  4xs: var(--ds-spacing-4xSmall, 0.125rem),
  3xs: var(--ds-spacing-3xSmall, 0.25rem),
  2xs: var(--ds-spacing-2xSmall, 0.5rem),
  xs: var(--ds-spacing-xSmall, 0.75rem),
  sm: var(--ds-spacing-small, 1rem),
  md: var(--ds-spacing-medium, 1.5rem),
  lg: var(--ds-spacing-large, 2rem),
  xl: var(--ds-spacing-xLarge, 2.5rem),
  2xl: var(--ds-spacing-2xLarge, 3rem),
  3xl: var(--ds-spacing-3xLarge, 3.5rem),
  4xl: var(--ds-spacing-4xLarge, 4rem),
  5xl: var(--ds-spacing-5xLarge, 4.5rem),
);
$types: ('m', 'p'); // margin or padding
$directions: ('', 't', 'r', 'b', 'l', 'x', 'y'); // top/right/bottom/left/horizontal/vertical

// Function to get spacing value from map
@function dsSpacing($key) {
  @if map.has-key($dsSpacings, $key) {
    @return map.get($dsSpacings, $key);
  } @else {
    @warn "Unknown spacing key `#{$key}`.";
    @return null;
  }
}

// Mixin to apply spacing based on type and direction
@mixin dsSpace($type, $dir, $value) {
  @if $dir == 'x' {
    #{$type}-left: $value;
    #{$type}-right: $value;
  } @else if $dir == 'y' {
    #{$type}-top: $value;
    #{$type}-bottom: $value;
  } @else if $dir == 't' {
    #{$type}-top: $value;
  } @else if $dir == 'r' {
    #{$type}-right: $value;
  } @else if $dir == 'b' {
    #{$type}-bottom: $value;
  } @else if $dir == 'l' {
    #{$type}-left: $value;
  } @else {
    #{$type}: $value;
  }
}

// Generator mixin to create all utility classes
@mixin generateSpacingUtilities {
  @each $type in $types {
    $property: 'padding';

    @if $type == 'm' {
      $property: 'margin';
    }

    @each $dir in $directions {
      @each $key, $val in $dsSpacings {
        // Build the class name safely
        $dirPart: '';

        @if $dir != '' {
          $dirPart: '#{$dir}';
        }

        $className: '.ds-#{$type}#{$dirPart}-#{$key}';

        #{$className} {
          @include dsSpace($property, $dir, $val);
        }
      }
    }
  }
}
