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

// Z-Index
// =======

// Z-Index
// -------
/// A list of named z-index layers, from lowest to highest index.
/// Nest lists (one level only) to establish a new z-index context:
/// The first item will be indexed based on top-level list position,
/// while additional values are indexed
/// by their position in the nested list.
///
/// @group layout-z-index
/// @example scss
///   $z-index: (
///     'main', // 1
///     'sidebar', // 2
///     'banner' 'active-nav' 'dropdown', // 3 1 2
///     'message', // 4
///     'modal', // 5
///   );
///
/// @type list
$z-index: () !default;

// Z-Index [function]
// ------------------
/// Return the numeric index of a named layer in your `$z-index` variable.
///
/// @since 1.0.0 -
/// No longer type-check output,
/// to allow CSS variables and other non-number values
///
/// @group layout-z-index
///
/// @param {string} $layer -
///   The name of a z-index layer in your configuration.
/// @require {variable} $z-index
/// @return {number} -
///   The z-index value associated with the given layer in your configuration.
@function z-index($layer) {
  $index: list.index($z-index, $layer);
  $nested: null;

  @if $index {
    @return $index;
  } @else {
    @for $i from 1 through list.length($z-index) {
      $stack: list.nth($z-index, $i);
      $index: $i;
      $nested: list.index($stack, $layer);

      @if meta.type-of($nested) == 'number' {
        @if $nested == 1 {
          @return $index;
        } @else if $nested > 1 {
          @return $nested - 1;
        }
      }
    }
  }

  @return $layer;
}

// Z-Index [mixin]
// ---------------
/// Output the `z-index` property and value of a given layer
/// in your `$z-index` configuration.
/// @group layout-z-index
/// @param {string} $layer -
///   The name of a z-index layer in your configuration.
/// @output -
///   The z-index property with a value based on your configuration.
@mixin z-index($layer) {
  z-index: z-index($layer);
}
