/// Conditional Styles with Sass. Dress you CSS appropriately.
/// Jacket is a Compass component that prints and hides styles based on
/// context variables you set in your stylesheet. Write and maintain a master
/// stylesheet, then output custom tailored stylesheets for modern and legacy
/// browsers, site and app builds, or any other context you can think of.
/// @link https://github.com/at-import/jacket
/// @group Jacket

@mixin jacket($contexts...) {

  $naked: false;
  $selectors: ();
  $filtered: ();
  $selector-string: '';

  // Set the global context variable.
  $jckt-context: $contexts !global;

  // If jacket is a single context and selector list, encapsulate.
  @if list-separator($jacket) == 'space' {
    $jacket: $jacket, null !global;
  }

  // Test if a jacket context and jacket value match.
  @each $item in $jacket {
    @each $context in $contexts {
      @if index($context, nth($item, 1)) {

        // Gather wrapping selectors.
        @if length($item) == 1 {
          $naked: true;
        }
        @if length($item) == 2 {
          $selectors: append($selectors, nth($item, 2) + ' &');
        }
      }
    }
  }

  // Filter out duplicate selectors.
  // If reject() is added to Sass we can remove the $filtered holder variable.
  @each $selector in $selectors {
    @if index($filtered, $selector) == false {
      $filtered: append($filtered, $selector);
    }
  }

  // Build the selector string.
  @each $selector in $filtered {
    @if $selector-string != '' {
      $selector-string: $selector-string + ', ';
    }
    $selector-string: $selector-string + $selector;
  }

  // If the weather is right, output that jacketed code!
  @if $naked {
    @content;
  }
  @if $selector-string != '' {
    #{$selector-string} {
      @content;
    }
  }
}

