// .selector {
//   @include sprite(1 2, 32px 30px) {
//     background-image: theme('sprite-image.svg');
//     @include sprite-modifier('open', 1 1);
//     @include sprite-modifier('close', 1 2);
//   }
// }

$-sprite-width: false;
$-sprite-height: false;
$-sprite-whole-map: false;

@mixin -sprite-check-globals($mixin) {
  $text: 'Use the mixin #{$mixin} inside sprite() mixin';
  @if $-sprite-width == false {
    @error $text;
  }
  @if $-sprite-height == false {
    @error $text;
  }
  @if $-sprite-whole-map == false {
    @error $text;
  }
}

@mixin -sprite-position($sprite-map, $width, $height) {

  $x: nth($sprite-map, 1) - 1;
  $y: nth($sprite-map, 2) - 1;

  @if ($x < 0) {
    $x: 0;
  }
  @if ($y < 0) {
    $y: 0;
  }

  $x-position: $x * $width;
  $y-position: $y * $height;

  @if $x == 0 and $y != 0 {
    background-position: 0 (-#{$y-position});
  } @else {
    @if $y == 0 and $x != 0 {
      background-position:  (-#{$x-position}) 0;
    } @else {
      @if $x == 0 and $y == 0 {
        background-position: 0 0;
      } @else {
        background-position: (-#{$x-position}) (-#{$y-position});
      }
    }
  }
}

@mixin -sprite-scale($sprite-map: 1 1, $scale: 1) {
  @include -sprite-check-globals('sprite-scale');
  $width: $-sprite-width;
  $height: $-sprite-height;

  $background-width: (nth($sprite-map, 1) * $width);
  $background-height: (nth($sprite-map, 2) * $height);

  background-size: s($scale, $background-width) s($scale, $background-height);
  height: s($scale, $height);
  width: s($scale, $width);
}

@mixin sprite($whole-map: 1 1, $size-map: 0px 0px) {
  $width: nth($size-map, 1);
  $height: nth($size-map, 1);

  @if (length($size-map) == 2) {
    $height: nth($size-map, 2);
  }

  $-sprite-width: $width !global;
  $-sprite-height: $height !global;
  $-sprite-whole-map: $whole-map !global;

  background-repeat: no-repeat;
  background-size: (nth($whole-map, 1) * $width) (nth($whole-map, 2) * $height);
  height: $height;
  width: $width;
  @content;

  $-sprite-width: false !global;
  $-sprite-height: false !global;
  $-sprite-whole-map: false !global;
}

@mixin sprite-modifier($selector, $sprite-map: 1 1, $scale: 1) {
  @include -sprite-check-globals('sprite-modifier');
  $width: $-sprite-width;
  $height: $-sprite-height;
  $whole-map: $-sprite-whole-map;

  &#{$bem-modifier}#{$selector} {
    @content;
    @include -sprite-position($sprite-map, s($scale, $width), s($scale, $height));
    @if ($scale != 1) {
      @include -sprite-scale($whole-map, $scale);
    }
  }
}
