@use '../config';
@use 'sass:list';
@use 'sass:map';
@use 'sass:math';
@use 'sass-mq' as mq;

/// Get the maximum layout offset (outer gutter, horizontal margin).
/// @return {number} -
///   maximum value from `$layout-offset`
/// @example scss
///   // Configuration
///   @use '@pixelherz/sassbox' with (
///     $layout-offset: (
///       default: 20px,
///       mouse: 40px,
///       rabbit: 80px,
///     ),
///     $layout-max-width: 1360px,
///   );
///
///   // Usage
///   .page {
///     // get-layout-max-offset() will return `80px`
///     max-width: #{sassbox.$layout-max-width + (sassbox.get-layout-max-offset() * 2)}; // 1520px
///   }
/// @since 1.0.0
/// @group layout
/// @see layout-max-width

@function get-layout-max-offset() {
  // Collect all offsets (outer gutter) in a list.
  // We'll use this later to get the max offset.
  $layout-offsets: ();
  @each $bp in config.$layout-offset {
    $layout-offsets: append($layout-offsets, list.nth($bp, 2));
  }
  @return math.max(0, $layout-offsets...);
}

/// Apply horizontal offset
/// @output
///   Applies the left/right offset for all breakpoints defined in your
///   configuration (`$layout-offset`).
/// @param {string} $prop ['margin'] -
///   By default the properties `margin-left` and `margin-right` are used. Use
///   this parameter if you prefer another property (`padding` makes sense in
///   some cases).
/// @example scss
///   // Configuration
///   @use '@pixelherz/sassbox' with (
///     $layout-offset: (
///       default: 20px,
///       mouse: 40px,
///       rabbit: 80px,
///     ),
///   );
///
///   // Usage
///   .layout {
///     @include sassbox.use-layout-offset($prop: 'padding');
///   }
/// @since 1.0.0
/// @group layout

@mixin use-layout-offset($prop: 'margin') {
  @each $offset in config.$layout-offset {
    $bp-name: list.nth($offset, 1);
    $offset-val: list.nth($offset, 2);
    // Default (no breakpoint)
    @if $bp-name == 'default' {
      #{$prop}-right: $offset-val;
      #{$prop}-left: $offset-val;
    }
    // Breakpoint
    @else if map.has-key(mq.$breakpoints, $bp-name) {
      @include mq.mq($from: $bp-name) {
        #{$prop}-right: $offset-val;
        #{$prop}-left: $offset-val;
      }
    }
    // Breakpoint invalid
    @else {
      @warn "Breakpoint '#{$bp-name}' is not defined in $breakpoints. Check your configuration in $layout-offset, make sure $breakpoints is available or add the breakpoint to $breakpoints.";
    }
  }
}

// Legacy support for <1.0.0, can be dropped with >=2.0.0

@function grid-max-offset() {
  @warn "Function grid-max-offset() is deprecated and will be removed. Use get-layout-max-offset() instead.";
  @return get-layout-max-offset();
}

@mixin apply-grid-offset($prop: 'margin') {
  @warn "Mixin apply-grid-offset() is deprecated and will be removed. Use use-layout-offset() instead.";
  @include use-layout-offset($prop);
}
