> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# Control Flow & Maps

SCSS có cấu trúc điều kiện và vòng lặp để sinh CSS động. Kết hợp với maps và lists để tạo style hàng loạt từ dữ liệu.

## Lists

List là dãy giá trị, ngăn cách bằng dấu cách hoặc phẩy.

```scss
$sizes: 4px, 8px, 16px, 32px;
```

| Function              | Tác dụng                      |
| --------------------- | ----------------------------- |
| `nth($list, $n)`      | Lấy phần tử thứ n (1-indexed) |
| `length($list)`       | Số phần tử                    |
| `append($list, $val)` | Thêm phần tử                  |
| `index($list, $val)`  | Vị trí của giá trị            |

## Maps

Map là cặp key-value, dùng cho config có cấu trúc (màu theme, breakpoint).

```scss
$colors: (
  'primary': #2e8555,
  'danger': #d9534f,
  'muted': #6c757d
);

.alert {
  color: map-get($colors, 'danger');
}
```

| Function                  | Tác dụng             |
| ------------------------- | -------------------- |
| `map-get($map, $key)`     | Lấy value theo key   |
| `map-has-key($map, $key)` | Kiểm tra tồn tại key |
| `map-keys($map)`          | List các key         |
| `map-values($map)`        | List các value       |

## @if / @else

```scss
@mixin theme($mode) {
  @if $mode == 'dark' {
    background: #1a1a1a;
    color: #fff;
  } @else if $mode == 'light' {
    background: #fff;
    color: #1a1a1a;
  } @else {
    background: gray;
  }
}

.panel {
  @include theme('dark');
}
```

## @each

Lặp qua list hoặc map. Hữu ích nhất khi sinh nhiều class theo cùng pattern.

```scss
// lặp map: sinh class màu
@each $name, $color in $colors {
  .text-#{$name} {
    color: $color;
  }
}
```

Compile ra:

```css
.text-primary { color: #2e8555; }
.text-danger { color: #d9534f; }
.text-muted { color: #6c757d; }
```

```scss
// lặp list
@each $size in $sizes {
  .p-#{$size} {
    padding: $size;
  }
}
```

## @for

Lặp theo số, dùng cho grid, spacing scale.

```scss
// through: bao gồm cả 12; to: không bao gồm
@for $i from 1 through 12 {
  .col-#{$i} {
    width: percentage($i / 12);
  }
}
```

## @while

Lặp theo điều kiện. Ít dùng, phần lớn trường hợp `@for`/`@each` đủ.

```scss
$i: 1;
@while $i <= 3 {
  .m-#{$i} { margin: #{$i * 4}px; }
  $i: $i + 1;
}
```

## Interpolation trong control flow

`#{}` để chèn biến vào tên selector hoặc property. Bắt buộc khi tạo tên class động.

```scss
@each $name, $value in $breakpoints {
  .hide-#{$name} {
    display: none;
  }
}
```

## Tips cho AEM

Dùng map cho design tokens (màu, spacing, breakpoint) đặt trong `abstracts/`, rồi `@each` sinh utility class hoặc CSS custom property. Cách này giữ một nguồn dữ liệu duy nhất, đổi token là toàn bộ style cập nhật, hợp với việc duy trì brand đồng nhất qua nhiều AEM component.

```scss
:root {
  @each $name, $color in $colors {
    --color-#{$name}: #{$color};
  }
}
```
