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

//
// Universal Responsive media query.
//
// IMPORTANT:
// When using LibSass for SCSS compiling (with Prepros it's called "Node Sass"),
// double check if media queries with multiple list parameters passed to this
// mixin were processed correctly. If not, try not to use LibSass.
//
// @example
//   @include media(
//     1600,                     // -> 'and (min-width: 1600px)'
//     1600px,                   // -> 'and (min-width: 1600px)'
//     ( 1600,   'min-height' ), // -> 'and (min-height: 1600px)'
//     ( 1600px, 'min-height' ), // -> 'and (min-height: 1600px)'
//     ( 1600,   'max-height' ), // -> 'and (max-height: 1599px)'
//     ( 1600px, 'max-height' ), // -> 'and (max-height: 1600px)'
//   ) {
//     $content;
//   }
//
// @since    1.0.0
// @version  2.0.0
//
// @param  lists $queries  Media query condition lists (arrays).
//
@mixin media( $queries... ) {

	$output : '';

	@each $query in $queries {

		@if (
			$query
			and (
				list == meta.type-of( $query )
				or number == meta.type-of( $query )
			)
		) {

			// Default query rule (the 2nd value in list) if not set otherwise

				@if ( 1 == list.length( $query ) ) {
					$query : list.append( $query, 'min-width' );
				}

			// Query value (the 1st value in list) in ems, or display it unchanged

				//
				// Query value must be set as SASS number, which can actually also contain a unit.
				// SASS string must be enclosed in parentheses, so never enclose the query value in those.
				//
				// @link  https://sass-lang.com/documentation/modules/math/#unit
				//
				$query_value : list.nth( $query, 1 );

				@if (
					number == meta.type-of( $query_value )
					and '' == math.unit( $query_value )
				) {

					// If the query is `max`, deduct a single pixel from unit-less query value.
					// (We do not do this if the query value contains a unit!)
					@if ( string.index( list.nth( $query, 2 ), 'max' ) ) {
						$query_value : $query_value - 1;
					}

					$query_value : $query_value + px;

					$query : list.set-nth( $query, 1, $query_value );
				}

			// Add to output

				@if ( 0 < string.length( $output ) ) {
					$output : $output + ' and ';
				}
				$output : $output + '(' + list.nth( $query, 2 ) + ': ' + list.nth( $query, 1 ) + ')';
		}
	}

	@if ( 0 < string.length( $output ) ) {
		@media #{ $output } {
			@content
		}

	} @else {
		@content

	}
}
