import { Meta, Source } from '@storybook/addon-docs/blocks';

<Meta title="Dark Mode" />

# Dark Mode

A concise guide explaining **how dark mode works** with your CSS variables and **how to use it** in Storybook.

---

## What dark mode is (high‑level)

Dark mode is implemented with **two sets of CSS variables** (tokens):

- **Light** values live under `:root`.
- **Dark** values override under `:root[data-theme="dark"]`.

Components only reference tokens with `var(--token-name)` — switching theme is just toggling the `data-theme` attribute (no component code changes).

---

## Token structure (SCSS → CSS)

Your presets export SCSS like this:

<Source 
  language="scss" 
  dark 
  code={`
  $root-selector: ':root' !default;
$dark-selector: '[data-theme="dark"]' !default;

#{$root-selector} {
/_ Light tokens _/
--color-background-primary: #ffffff;
--color-text-primary: #000000;
/_ … all your light variables … _/
}

#{$root-selector}#{$dark-selector} {
/_ Dark tokens _/
--color-background-primary: #191919;
--color-text-primary: #d9d9d9;
/_ … all your dark variables … _/
}
`}
/>

After compilation, this becomes standard CSS:

<Source
  language="css"
  dark
  code={`
    :root {
      /* light tokens */
    }
    :root[data-theme='dark'] {
      /* dark tokens */
    }
  `}
/>

> If you can’t (or don’t want to) target `:root`, you can pass a different `$root-selector` when building your theme and apply `data-theme="dark"` on that container instead.

---

## Using tokens inside components

To enable the dark mode you have to ensure to:

- Add the `data-theme` attribute in your root element with the value `dark`,
- Use variables — never hard‑code colors or sizes

```html
<div class="root" data-theme="dark">…</div>
```

<Source 
  language="sass" 
  dark 
  code={`
    @use "@mozaic-ds/tokens" as *;

    .mc-component: {
      background-color: $--color-background-primary;
    }

`}
/>

When the theme changes, these values update automatically via CSS.

---

## Accessibility & good practices

- Aim for **WCAG AA** contrast at minimum; verify text vs. background pairs.
- Prefer **semantic tokens** (`--button-color-…`, `--color-text-…`) over raw color hexes.
- Keep all component styles expressed in tokens so the **theme switch has zero component logic**.

---

## Troubleshooting

- **Dark toggle does nothing** → Ensure the tokens were imported **before** component styles and that `data-theme="dark"` is set on the same selector the tokens target (usually `:root`).
- **Weird colors** → Search for hard‑coded values and replace them with tokens.
- **Variables undefined** → Check your build order and that the SCSS was compiled to CSS and loaded by Storybook.

---

## Summary

- Light tokens on `:root`, dark overrides on `:root[data-theme="dark"]`.
- Components read tokens with `var(--$token-name)` — no runtime branching required.
