@use 'strip-units';
@use '../../settings/variables' as v;

// ==========================================================================
// _units.scss
//
// Contains all functions relating to units
// ==========================================================================

// @include line-height
//
// Given a font-size and a line-height (in pixels)
// Returns a unitless line-height value
@use 'sass:math';
@use 'sass:map';

@function decimal-round($number, $digits: 0, $mode: round) {
    $n: 1;

    // $number must be a number
    @if type-of($number) != number {
        @warn '#{ $number } is not a number.';
        @return $number;
    }

    // $digits must be a unitless number
    @if type-of($digits) != number {
        @warn '#{ $digits } is not a number.';
        @return $number;
    } @else if not unitless($digits) {
        @warn '#{ $digits } has a unit.';
        @return $number;
    }

    @if $digits > 0 {
        @for $i from 1 through $digits {
            $n: $n * 10;
        }
    }

    @if $mode == round {
        @return math.div(round($number * $n), $n);
    } @else if $mode == ceil {
        @return math.div(ceil($number * $n), $n);
    } @else if $mode == floor {
        @return math.div(floor($number * $n), $n);
    } @else {
        @warn '#{ $mode } is undefined keyword.';
        @return $number;
    }
}

@function line-height($font-size: 'body-s', $line-height: '20', $scale: 'default') {
    @if type-of($font-size) == 'number' {
        @return decimal-round(math.div($line-height, $font-size), 2);
    } @else if map-has-key(v.$type, $font-size) { // else try and find the value in our type map
        $key-map: map-get(v.$type, $font-size);
        $font-list: map-get($key-map, $scale);

        @if type-of($font-list) == 'list' {
            @return line-height(nth($font-list, 1), nth($font-list, 2));
        } @else {
            @warn 'No line-height found as part of the $type map for #{ $font-size }';
        }
    }
}

$line-height-base : line-height(); // Lifted out of the variables file to fix circular reference issues

@function em-to-px($emVal, $base: v.$font-size-base) {
    @return ($emVal * $base) * 1px;
}

@function map-to-px($breakpoints, $base: v.$font-size-base) {
    $newBreakpoints: ();

    @each $name, $emValue in $breakpoints {
        $pxValue: em-to-px(strip-units.strip-units($emValue), $base);
        $newBreakpoints: map-merge($newBreakpoints, ($name: $pxValue));
    }

    @return $newBreakpoints;
}
