@use 'sass:map';
@use 'sass:meta';
@use 'sass:math';
@use 'sass:list';
@use 'sass:color';
@use 'sass:string';
@use 'charts';
@use 'config';
@use 'generator';
@use 'multipliers';
@use 'types';
@use 'contrast' as *;
@use '../utils/math' as *;
@forward 'contrast';

////
/// @package theming
////

$_enhanced-accessibility: false;

// Flags used to print each deprecation warning only once per compilation.
$_text-contrast-warned: false;
$_to-opaque-warned: false;
$_to-hsl-warned: false;

/// Configures the color module.
/// @access public
/// @group color
/// @param {Boolean} $enhanced-accessibility [null] - Enables features like color blind brushes for chart themes.
/// @example scss
///   .enhanced-accessibility {
///      @include configure-colors(true);
///    }
/// @see $brushes-color-blind
@mixin configure-colors($enhanced-accessibility: null) {
    @if $enhanced-accessibility {
        $_enhanced-accessibility: $enhanced-accessibility !global;
    }
}

/// Generates a color palette.
/// @access public
/// @group Palettes
/// @param {Color} $primary - The primary color used to generate the primary color palette (required).
/// @param {Color} $secondary - The secondary color used to generate the secondary color palette (required).
/// @param {Color} $surface - The color used as a background in components (required).
/// @param {Color} $gray [null] - The color used for generating the grayscale palette (optional).
/// @param {Color} $info [#1377d5] - The information color used throughout the application (optional).
/// @param {Color} $success [#4eb862] - The success color used throughout the application (optional).
/// @param {Color} $warn [#faa419] - The warning color used throughout the application (optional).
/// @param {Color} $error [#ff134a] - The error color used throughout the application (optional).
/// @param {String} $variant [null] - Used internally (optional).
/// @param {String} $generator [$shade-generator] - Either `fitted` or `legacy` (optional).
/// @param {String | Map | List} $scales [null] - One scale for every family, or a map keyed by family name (optional).
/// @requires {function} shades
/// @returns {Map} A map consisting of color shades for the passed base colors (primary, secondary, gray, etc).
/// @example scss
///   // Pass the required colors
///   $my-palette: palette(
///     $primary: rebeccapurple,
///     $secondary: orange,
///     $surface: white,
///   );
///
///   // Include the generated palette colors as CSS variables.
///   @include palette($my-palette);
/// @example scss - Keep the original multiplier-based shades
///   $my-palette: palette(rebeccapurple, orange, white, $generator: 'legacy');
/// @example scss - Give the grayscale a different rhythm
///   $my-palette: palette(rebeccapurple, orange, white, $scales: ('gray': 'carbon'));
/// @see $shade-generator
/// @see $scales
@function palette(
    $primary,
    $secondary,
    $surface,
    $gray: null,
    $info: #1377d5,
    $success: #4eb862,
    $warn: #faa419,
    $error: #ff134a,
    $variant: null,
    $generator: config.$shade-generator,
    $scales: null
) {
    @if $generator == 'legacy' and $scales {
        @warn '$scales is ignored. The legacy generator does not use scales.';

        $scales: null;
    }

    $color-shades: types.$IColorShades;
    $gray-shades: types.$IGrayShades;
    $primary-palette: shades(
        'primary',
        $primary,
        $color-shades,
        $generator: $generator,
        $scale: _scale-for('primary', $scales)
    );
    $secondary-palette: shades(
        'secondary',
        $secondary,
        $color-shades,
        $generator: $generator,
        $scale: _scale-for('secondary', $scales)
    );
    $surface-palette: shades(
        'surface',
        $surface,
        types.$ISurfaceShades,
        $generator: $generator,
        $scale: _scale-for('surface', $scales)
    );
    $grayscale-palette: shades('gray', $gray, $gray-shades, $surface, $generator, _scale-for('gray', $scales));
    $info-palette: if(
        $info,
        shades('info', $info, $color-shades, $generator: $generator, $scale: _scale-for('info', $scales)),
        ()
    );
    $success-palette: if(
        $success,
        shades('success', $success, $color-shades, $generator: $generator, $scale: _scale-for('success', $scales)),
        ()
    );
    $warn-palette: if(
        $warn,
        shades('warn', $warn, $color-shades, $generator: $generator, $scale: _scale-for('warn', $scales)),
        ()
    );
    $error-palette: if(
        $error,
        shades('error', $error, $color-shades, $generator: $generator, $scale: _scale-for('error', $scales)),
        ()
    );

    @return (
        'primary': $primary-palette,
        'secondary': $secondary-palette,
        'gray': $grayscale-palette,
        'surface': $surface-palette,
        'info': $info-palette,
        'success': $success-palette,
        'warn': $warn-palette,
        'error': $error-palette,
        '_meta': (
            'variant': $variant,
        )
    );
}

/// Picks one family's scale out of the `$scales` argument, which may be a single spec
/// for every family or a map keyed by family name.
/// @access private
/// @group Palettes
/// @param {String} $name - The family to look up.
/// @param {String | Map | List} $scales - The `palette()` argument, or null.
/// @returns {String | Map | List} That family's scale, or null to let the generator decide.
@function _scale-for($name, $scales) {
    @if not $scales {
        @return null;
    }

    @if meta.type-of($scales) == 'map' {
        // Mirrored by SCALED_COLOR_GROUPS in the MCP package.
        $families: ('primary', 'secondary', 'gray', 'info', 'success', 'warn', 'error');
        $is-spec: _is-scale-spec($scales);

        // Warn once per palette() call.
        @if $name == 'primary' {
            @each $key in map.keys($scales) {
                $k: '#{$key}';

                @if $is-spec and not list.index(('range', 'curve', 'anchor'), $k) {
                    @warn '$scales key "#{$k}" is ignored. A $scales map with range, curve or anchor is ' +
                        'one spec for every family; key every entry by family to scale them separately.';
                } @else if not $is-spec and $k == 'surface' {
                    @warn '$scales key "surface" is ignored. A surface is built from its roles and takes no scale.';
                } @else if not $is-spec and not list.index($families, $k) {
                    @warn 'Unknown $scales key "#{$k}" is ignored. Key $scales by palette family ' +
                        '(#{$families}), or pass a single (range:, curve:, anchor:) spec for all of them.';
                }
            }
        }

        @if not $is-spec {
            @return map.get($scales, $name);
        }
    }

    @return $scales;
}

/// Whether a `$scales` map is a single spec rather than a map keyed by family.
/// @access private
/// @group Palettes
/// @param {Map} $scales - The `palette()` argument.
/// @returns {Boolean}
@function _is-scale-spec($scales) {
    @return map.has-key($scales, range) or map.has-key($scales, curve) or map.has-key($scales, anchor);
}

/// Generates color shades for a given color.
/// @access public
/// @group Palettes
/// @param {String} $name - The name of the color.
/// @param {Color} $color - The base color used to generate the shades.
/// @param {List} $shades - The list of shade variants.
/// @param {Color} $surface [null] - The surface color. Useful if generating shades of gray (optional).
/// @param {String} $generator [$shade-generator] - Either `fitted` or `legacy` (optional).
/// @param {String | Map | List} $scale [null] - A preset name, a `(range:, curve:)` map, or a curve (optional).
/// @requires {function} adaptive-contrast
/// @returns {Map} A map consisting of color shades and their respective contrast colors.
///
/// @example scss
///   $color-name: 'accent';
///
///   // Include the generated palette colors as CSS variables.
///   @include palette(
///     (
///       #{$color-name}: shades($color-name, #a57865, $IColorShades),
///     )
///   );
/// @example scss - Pick a scale for this scale
///   $shades: shades('accent', #a57865, $IColorShades, $scale: 'carbon');
/// @see $IColorShades
/// @see $scales
@function shades($name, $color, $shades, $surface: null, $generator: config.$shade-generator, $scale: null) {
    $entries: if(
        $generator == 'legacy',
        _legacy-entries($name, $color, $shades, $surface),
        generator.family($name, $color, $shades, $surface, $scale)
    );
    $result: ();

    @if '#{$name}' == 'surface' {
        $entries: map.merge(_surface-numbers($color, $shades, $generator), $entries);

        // A legacy surface holds its seed on 500, so base follows it at runtime. A fitted
        // surface points 500 at base instead; aliasing it this way too would be a cycle.
        @if $generator == 'legacy' and map.has-key($entries, '500') {
            $entries: map.set($entries, 'base', 'css', #{var(--ig-surface-500)});
        }
    }

    @each $variant, $shade in $entries {
        $result: map.set($result, $variant, map.get($shade, 'css'));
        $result: map.set($result, '#{$variant}-contrast', adaptive-contrast(_contrast-source($name, $variant, $shade)));
        $result: map.set($result, '#{$variant}-raw', map.get($shade, 'raw'));
    }

    @return $result;
}

/// The color a shade's contrast color is measured against. A translucent shade is seen over its
/// backdrop, so it is measured as the two composited; measuring the translucent color alone would
/// ignore its alpha and read a faint black layer as solid black. Both stay CSS variables, so the
/// contrast follows either one at runtime.
/// @access private
/// @group Palettes
/// @param {String} $name - The family name.
/// @param {String} $variant - The shade variant.
/// @param {Map} $shade - The shade entry, `(css:, raw:)`, with an optional `backdrop` variant.
/// @returns {String} A CSS color to measure.
@function _contrast-source($name, $variant, $shade) {
    $self: var(--ig-#{$name}-#{$variant});
    $backdrop: map.get($shade, 'backdrop');

    @if not $backdrop {
        @return #{$self};
    }

    $alpha: math.percentage(color.alpha(map.get($shade, 'raw')));

    @return string.unquote('color-mix(in srgb, rgb(from #{$self} r g b) #{$alpha}, var(--ig-#{$name}-#{$backdrop}))');
}

/// Builds the multiplier-based shades or — for a surface — the same layer roles the
/// `fitted` generator emits. The roles are contrast steps off the background rather than
/// points on a multiplier ramp, so they mean the same thing under either generator, and
/// having them everywhere is what lets a schema say `('surface', 'base')` unconditionally.
/// @access private
/// @group Palettes
/// @param {String} $name - The name of the color.
/// @param {Color} $color - The base color used to generate the shades.
/// @param {List} $shades - The list of shade variants.
/// @param {Color} $surface [null] - The surface color, for the grayscale.
/// @requires {function} shade
/// @returns {Map} Each variant mapped to `(css:, raw:)`.
@function _legacy-entries($name, $color, $shades, $surface: null) {
    @if '#{$name}' == 'surface' {
        @return generator.family('surface', $color, types.$ISurfaceRoles);
    }

    $entries: ();

    @each $variant in $shades {
        $shade: shade($name, $color, $variant, $surface);
        $entries: map.set(
            $entries,
            $variant,
            (
                css: map.get($shade, 'hsl'),
                raw: map.get($shade, 'raw'),
            )
        );
    }

    @return $entries;
}

/// Builds the numeric shades of a surface from its `500` with the legacy multipliers. A legacy
/// surface holds its seed on `500`. A fitted surface points `500` at `base`, so its numeric
/// shades follow the background, including when `base` changes at runtime.
/// @access private
/// @group Palettes
/// @param {Color} $color - The surface color.
/// @param {List} $shades - The requested variants; only those in `$ISurfaceNumericShades` are built.
/// @param {String} $generator - Either `fitted` or `legacy`.
/// @requires {function} shade
/// @returns {Map} Each numeric variant mapped to `(css:, raw:)`.
@function _surface-numbers($color, $shades, $generator) {
    $entries: ();

    @each $variant in $shades {
        @if list.index(types.$ISurfaceNumericShades, '#{$variant}') {
            $shade: shade('surface', $color, $variant);
            $css: map.get($shade, 'hsl');

            @if $generator != 'legacy' and '#{$variant}' == '500' {
                $css: #{var(--ig-surface-base)};
            }

            $entries: map.set(
                $entries,
                $variant,
                (
                    css: $css,
                    raw: map.get($shade, 'raw'),
                )
            );
        }
    }

    @return $entries;
}

/// Generates a color shade for a given base colors.
/// @access private
/// @group Palettes
/// @param {String} $name - The base color name (primary, secondary, etc.) to be used to generate a color variant.
/// @param {Color} $color - The color value to be used to generate a color shade.
/// @param {String | Number} $shade - The color shade variant.
/// @param {Color} $surface [null] - The surface color. Useful when generating a shade of gray (optional).
/// @require {function} luminance
/// @require {function} to-fixed
/// @returns {Map} A map containing a list of HSL values and a raw color value.
@function shade($name, $color, $shade, $surface: null) {
    $h: var(--ig-#{$name}-h);
    $s: var(--ig-#{$name}-s);
    $l: var(--ig-#{$name}-l);

    @if #{$name} == 'gray' {
        $lum: luminance($surface);
        $color: if($color, $color, if($lum > 0.5, #000, #fff));

        @if #{$shade} == 'seed' {
            @return (raw: $color, hsl: $color);
        }

        $lmap: map.get(multipliers.$grayscale, 'l');
        $len: list.length($lmap);
        $i: list.index(map.keys($lmap), #{$shade});
        $l: list.nth(map.values($lmap), if($lum > 0.5, $len - $i + 1, $i));
        $raw: hsl(
            to-fixed(color.channel($color, 'hue', $space: hsl)),
            to-fixed(color.channel($color, 'saturation', $space: hsl)),
            $l
        );
        $hsl: #{hsl(from var(--ig-#{$name}-500) h s $l)};

        @if #{$shade} == '500' {
            $hsl: $raw;
        }

        @return (raw: $raw, hsl: $hsl);
    } @else {
        $hsl: null;
        $raw: null;

        @if #{$shade} == '500' or #{$shade} == 'seed' {
            $hsl: $color;
            $raw: $color;
        } @else {
            $sx: map.get(multipliers.$color, 's', #{$shade});
            $lx: map.get(multipliers.$color, 'l', #{$shade});
            $raw: hsl(
                to-fixed(color.channel($color, 'hue', $space: hsl)),
                to-fixed(color.channel($color, 'saturation', $space: hsl) * $sx),
                to-fixed(color.channel($color, 'lightness', $space: hsl) * $lx)
            );
            $hsl: #{hsl(from var(--ig-#{$name}-500) h calc(s * $sx) calc(l * $lx))};
        }

        @return (raw: $raw, hsl: $hsl);
    }
}

/// Calculates a dynamic shade of a color by adjusting its lightness in LCH color space.
/// @access public
/// @param {Color} $color - The base color to shade.
/// @param {Number} $lightness [50] - The target lightness value to move toward.
/// @param {Number} $percentage [0.1] - The percentage to move toward the target lightness.
/// @param {Number} $offset [10] - The offset added or subtracted based on direction.
/// @returns {Color} The dynamically shaded color in LCH color space
@function dynamic-shade($color, $lightness: 50, $factor: 0.1, $offset: 5) {
    @return lch(from $color calc(l + ($lightness - l) * $factor + sign($lightness - l) * $offset) c h);
}

/// Normalizes a color value to ensure consistent format output.
/// This fixes issues with newer Sass versions that return RGB format with floating point precision.
/// @access private
/// @group Color
/// @param {Color} $color - The color to normalize.
/// @returns {Color} The normalized color in hex format.
@function _normalize-color($color) {
    @if meta.type-of($color) == 'color' {
        // Round RGB channels to integers to maintain backward compatibility with older Sass behavior
        $r: math.round(color.channel($color, 'red', $space: rgb));
        $g: math.round(color.channel($color, 'green', $space: rgb));
        $b: math.round(color.channel($color, 'blue', $space: rgb));

        @return rgb($r, $g, $b);
    }

    @return $color;
}

/// Retrieves a color from a color palette.
/// @access public
/// @group Palettes
/// @param {Map} $palette [null] - The source palette map (optional).
/// @param {String} $color [primary] - The target color from the color palette.
/// @param {Number | String} $variant [500] - The target color shade from the color palette.
/// @param {Number} $opacity [null] - Optional opacity to apply to the color shade.
/// @returns {Color | String} The raw color shade or CSS variable reference from the palette.
///
/// @example scss - Getting a color from the palette
///   // Without providing a palette
///   .my-component-1 {
///      background: color($color: primary, $variant: 200); // var(--ig-primary-200)
///    }
///
///    // With a specific palette
///   .my-component-2 {
///      background: color($my-palette, primary, 200); // #88c0e5
///    }
///
/// @example scss - Getting a color with opacity
///   .my-component-1 {
///      background: color($color: primary, $variant: 200, $opacity: 0.5); // hsl(from var(--ig-primary-200) h s l/0.5)
///    }
///
///    // With a specific palette
///   .my-component-2 {
///      background: color($my-palette, primary, 200, $opacity: 0.5); // rgba(136, 192, 229, 0.5)
///    }
@function color($palette: null, $color: primary, $variant: null, $opacity: null) {
    $variant: if($variant, $variant, if('#{$color}' == 'surface', 'base', 500));
    $s: #{var(--ig-#{$color}-#{$variant})};
    $contrast: if(meta.type-of($variant) == string, string.index($variant, 'contrast'), false);
    $_alpha: if($opacity, $opacity, 1);
    $_relative-color: if($opacity, hsl(from $s h s l / $opacity), $s);

    @if $palette {
        $s: map.get($palette, #{$color});
        $base: map.get($s, #{$variant});
        $raw: map.get($s, #{$variant}-raw);

        @return if(
            $contrast,
            $_relative-color,
            if($raw, if($opacity, rgba($raw, $opacity), $raw), _normalize-color($base))
        );
    }

    @return $_relative-color;
}

/// Retrieves a contrast color for a given color variant from a color palette. Works similarly to the color function.
/// @access public
/// @group Palettes
/// @param {Map} $palette [null] - The source palette map (optional).
/// @param {String} $color [primary] - The target color from the color palette.
/// @param {Number | String} $variant [500] - The target color shade from the color palette.
/// @param {Number} $opacity [null] - Optional opacity to apply to the color shade.
/// @requires {function} color
/// @returns {Color | String} The raw contrast color shade or CSS variable from the palette.
///
/// @example scss - without passing a palette
///   .my-component {
///      background: color($color: 'primary', $variant: 200);
///      color: contrast-color($color: 'primary', $variant: 200);
///    }
@function contrast-color($palette: null, $color: primary, $variant: null, $opacity: null) {
    $variant: if($variant, $variant, if('#{$color}' == 'surface', 'base', 500));

    @return color($palette, $color, #{$variant}-contrast, $opacity);
}

/// Returns a CSS runtime calculated relative color(black or white) for a given color.
/// @access public
/// @group Color
/// @param {Color} $color - The base color used in the calculation.
///
/// @example scss
///   .my-component {
///      --bg: #09f;
///      background: var(--bg);
///      color: adaptive-contrast(var(--bg)); // hsl(from color(from var(--bg) var(--y-contrast)) h 0 l)
///    }
/// @returns {string} Returns a relative HSL color where the lightness is adjusted
@function adaptive-contrast($color) {
    $fn: meta.get-function('color', $css: true);

    @return hsla(from meta.call($fn, from $color var(--y-contrast)) h 0 l / 1);
}

/// Returns a contrast color for a passed color.
/// @deprecated Use adaptive-contrast instead.
/// @access public
/// @group Color
/// @param {Color} $background - The background color used to return a contrast/forground color for.
/// @param {Color | List } $foreground [#fff] - A list of foreground colors that can be used with the provided background.
/// @param {String} $contrast [AAA] - The contrast level according to WCAG 2.0 standards.
/// @example scss
///   .my-component {
///      background: #09f;
///      color: text-contrast(#09f);
///    }
///
/// @require {function} contrast
/// @see {function} adaptive-contrast
/// @returns {Color} Returns either white, black, or the provided foreground color if it meets the required contrast level.
/// @link https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html WCAG 2.0 Contrast
@function text-contrast($background, $foreground: white, $contrast: 'AAA') {
    @if not $_text-contrast-warned {
        @warn 'text-contrast() is deprecated. Use adaptive-contrast() instead.';

        $_text-contrast-warned: true !global;
    }

    @if meta.type-of($foreground) != 'list' and meta.type-of($background) != 'color' {
        @return $background;
    }

    $level: map.get(
        (
            'a': 3,
            'aa': 4.5,
            'aaa': 7,
        ),
        string.to-lower-case($contrast)
    );

    @if not($level) {
        @error '$contrast must be \'A\', \'AA\', or \'AAA\'';
    }

    $candidates: ();

    @each $color in $foreground {
        @if meta.type-of($color) != 'color' {
            @return $background;
        }

        $candidates: list.append($candidates, contrast($background, $color));
    }

    $foreground: list.nth($foreground, list.index($candidates, math.max($candidates...)));

    @if contrast($background, $foreground) >= $level {
        @return $foreground;
    } @else {
        $lightContrast: contrast($background, white);
        $darkContrast: contrast($background, black);

        @if $lightContrast > $darkContrast {
            @return white;
        } @else {
            @return black;
        }
    }
}

/// Mixes two colors to produce an opaque color.
/// @deprecated Switch to CSS color-mix.
/// @access private
/// @group Color
/// @param {Color} $color-1 - The first color, usually transparent.
/// @param {Color} $color-2 [#fff] - The second color, usually opaque.
/// @return {Color} The color representation of the rgba value.
@function to-opaque($color-1, $color-2: #fff) {
    @if not $_to-opaque-warned {
        @warn 'to-opaque() is deprecated. Use the CSS color-mix() function instead.';

        $_to-opaque-warned: true !global;
    }

    @if meta.type-of($color-1) == color and meta.type-of($color-2) == color {
        $red: color.channel($color-1, 'red', $space: rgb);
        $green: color.channel($color-1, 'green', $space: rgb);
        $blue: color.channel($color-1, 'blue', $space: rgb);
        $a: color.channel($color-1, 'alpha');
        $r: math.floor($a * $red + (1 - $a) * color.channel($color-2, 'red', $space: rgb));
        $g: math.floor($a * $green + (1 - $a) * color.channel($color-2, 'green', $space: rgb));
        $b: math.floor($a * $blue + (1 - $a) * color.channel($color-2, 'blue', $space: rgb));

        @return rgb($r, $g, $b);
    }

    @return $color-1;
}

/// Retruns a comma separated list of hue, saturation, and lightness values for a given color.
/// @deprecated Not needed anymore and will be removed in the future.
/// @access public
/// @group Color
/// @param {Color} $color - The color to be converted to an HSL list of values.
/// @example scss - Turn #000 into an HSL list of values
///   $hsl-list: to-hsl(#000); // (0deg, 0%, 0%);
/// @return {List} This list of HSL values.
@function to-hsl($color) {
    @if not $_to-hsl-warned {
        @warn 'to-hsl() is deprecated and will be removed in a future release. It is no longer needed.';

        $_to-hsl-warned: true !global;
    }

    @return (
        math.round(color.channel($color, 'hue', $space: hsl)),
        math.round(color.channel($color, 'saturation', $space: hsl)),
        math.round(color.channel($color, 'lightness', $space: hsl))
    );
}

/// Returns a list of colors to be used as chart brushes. The return value depends on the value of enhanced-accessibility.
/// @access public
/// @group Palettes
/// @returns { List } A list of colors to be used as chart brushes.
/// @see {mixin} configure-colors
/// @see $brushes-regular
/// @see $brushes-color-blind
@function chart-brushes() {
    @return if($_enhanced-accessibility, charts.$brushes-color-blind, charts.$brushes-regular);
}
