@use '../../00-settings/colors' as *;
@use '../../00-settings/themes' as *;

@use 'sass:map';
@use 'sass:string';
@use 'sass:list';

$theme-color: null !default;

/// Returns the resolved color from the `$colors` map using the `$default` key.
/// The `$exception` parameter is deprecated and ignored.
///
/// @param {map} $colors - Theme color map.
/// @param {string} $default - Utility string like 'color-primary'.
/// @param {string} $exception - Deprecated fallback (ignored).
/// @return {color} - The resolved color.
@function set-themified-property($colors, $default, $exception: null) {
  @if $exception != null and map.has-key($colors, $exception) {
    @return map.get($colors, $exception);
  }

  @if $default != null and map.has-key($colors, $default) {
    @return map.get($colors, $default);
  }

  @if $default != null {
    $parts: string.split($default, '--');
    @if list.length($parts) > 1 {
      $base: list.nth($parts, 1);
      @if map.has-key($colors, $base) {
        @return map.get($colors, $base);
      }
    }
  }

  @error "Unknown theme color: default=`#{$default}`, exception=`#{$exception}`. Check your _themes.scss/_colors.scss.";
}

/// Mixin to apply a themed CSS property inside a `.cs--<theme>` context.
///
/// @param {string} $property - CSS property name.
/// @param {string} $default - Utility string like 'color-primary'.
/// @param {string} $exception - Deprecated fallback (ignored).
@mixin theme($property: null, $default: null, $exception: null, $extra-values: null) {
  @each $theme, $colors in $themes {
    .cs--#{$theme} & {
      #{$property}: set-themified-property($colors, $default, $exception);
    }
  }
}

/// Same as `theme()` mixin, but applies the `.cs--<theme>` class to the root element of the selector.
///
/// Use when the base selector is on the root element (e.g. `<body>`).
///
/// @param {string} $property - CSS property name.
/// @param {string} $default - Utility string like 'color-primary'.
/// @param {string} $exception - Deprecated fallback (ignored).
@mixin theme-body($property: null, $default: null, $exception: null, $extra-values: null) {
  @each $theme, $colors in $themes {
    @at-root .cs--#{$theme}#{&} {
      #{$property}: set-themified-property($colors, $default, $exception);
    }
  }
}

/// Mixin that exposes `$theme-color` inside the `@content` block for custom styling.
/// Useful for things like borders or shadows where the value is not a simple property.
///
/// @param {string} $default - Utility string like 'color-primary'.
/// @param {string} $exception - Deprecated fallback (ignored).
@mixin theme-content($default: null, $exception: null) {
  @each $theme, $colors in $themes {
    $theme-color: set-themified-property($colors, $default, $exception) !global;

    .cs--#{$theme} & {
      @content;
    }
  }
}
