@use 'sass:map';
@use '@swisspost/design-system-tokens/scheme';

@use '../mixins/supports';

/**
 * Fallback for browsers without `light-dark()` support, based on space toggles.
 *
 * Every scheme colour is recomputed from the `--post-fallback-prefers-light` toggle:
 * - empty value -> light
 * - `initial` -> dark
 *
 * For more information about space toggles, see:
 * - https://dev.to/janeori/css-lightdark-mode-implementation-without-duplicating-vars-22c9
 * - https://kizu.dev/cyclic-toggles/
 *
 * This placeholder is used to output the variables only once, shared by all selectors that use
 * `set()` and by the root scheme tokens (`_schemes.scss`). It can be removed once the
 * `light-dark()` function becomes available in across supported browsers.
 */
%color-scheme-fallback-variables {
  @include supports.light-dark(false) {
    @each $key, $light-value in scheme.$post-light {
      --#{$key}-light: var(--post-fallback-prefers-light) #{$light-value};
      --#{$key}: var(--#{$key}-light, #{map.get(scheme.$post-dark, $key)});
    }
  }
}

/**
 * Sets the colour scheme of an element, including the fallback for browsers without `light-dark()`
 * support.
 *
 * The input can be a literal value (`light` or `dark`) or a CSS variable that resolves to a core
 * colour scheme.
 */
@mixin set($color-scheme) {
  @include supports.light-dark(true) {
    color-scheme: #{$color-scheme};
  }

  @include supports.light-dark(false) {
    // Literals (`light`, `dark`) and the core tokens `var(--post-core-bg-scheme-…)` are not valid
    // space toggles and must be converted.
    @if $color-scheme == light or $color-scheme == var(--post-core-bg-scheme-light) {
      --post-fallback-prefers-light: ;
    } @else if $color-scheme == dark or $color-scheme == var(--post-core-bg-scheme-dark) {
      --post-fallback-prefers-light: initial;
    }
    // Other values are expected to already resolve to a space toggle.
    @else {
      --post-fallback-prefers-light: #{$color-scheme};
    }
  }

  // As `@extend` cannot reach selectors outside the current media query, it needs to be moved out
  // of it. This keeps `set()` usable within `@media`.
  @at-root (without: media) {
    @extend %color-scheme-fallback-variables;
  }
}
