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

//
// Get unit from length.
//
// Inspired by https://stackoverflow.com/a/58630116.
//
// @param {length} $length — Original length.
// @returns {string} — Detected unit.

@function _get($length) {
    @return string.slice($length * 0 + '', 2, -1);
}

//
// Re-calculate `px` to `em`.
//
// @param {length} $length — Original length in `px`.
// @param {length} $current-font-size — Font size of current context in `em`. Necessary when != 1em.
// @returns {length} — New length in `em`, relative to the font size of current context.

@function _px2em($length, $current-font-size: 1em) {
    $_original-font-size: 16px;

    @return math.div($length, $_original-font-size) * math.div(1em, $current-font-size) * 1em;
}

//
// Re-calculate `rem` to `em`.
//
// @param {length} $length — Original length in `rem`.
// @param {length} $current-font-size — Font size of current context in `em`. Necessary when != 1em.
// @returns {length} — New length in `em`, relative to the font size of current context.

@function _rem2em($length, $current-font-size: 1em) {
    @return math.div($length, 1rem) * math.div(1em, $current-font-size) * 1em;
}

//
// Automatically convert input length to `em` for convertible units. Otherwise return the input.
//
// We cannot rely on `rem` as it can vary from project to project. Also, we prefer proportional
// scaling even for pixel-based values. Re-calculation to `em` is therefore needed for all `rem` and
// `px`-based design tokens. Output value is then relative to `--lmcccm-base-font-size` (see
// `src/scss/theme/_default.scss`).
//
// @param {length} $input — Original length in any unit.
// @param {length} $current-font-size — Font size of current context in `em`. Necessary when != 1em.
// @returns {length} — New length in `em`, relative to the font size of current context.

@function convert2em($input, $current-font-size: 1em) {
    $_input-unit: _get($input);

    @if $_input-unit == 'px' {
        @return _px2em($input, $current-font-size);
    } @else if $_input-unit == 'rem' {
        @return _rem2em($input, $current-font-size);
    } @else {
        @return $input;
    }
}
