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

<Meta title="Utilities/Layer Manager/Overview" />

# Layer Manager Overview

The layer manager exists to keep every teleported component (dialogs, drawers, popovers, tooltips, toasts, etc.) in a predictable stacking order without sprinkling arbitrary `z-index: 9999` rules across the codebase. Instead of assigning fixed bands per component type, we keep a single global stack that increments as layers mount. [Reference](https://v1.chakra-ui.com/docs/components/recipes/z-index)

## Why avoid manual z-index values?

- **Unbounded numbers** – once one component uses `z-index: 9999`, the next overlay needs more. This escalates quickly and still breaks when stacking contexts change.
- **Stacking contexts** – `position`, `transform`, `opacity`, `filter`, and even flex or grid children can create new contexts that ignore global z-index rules. Portaled content plus a manager side-steps this entirely.
- **Shared ownership** – dialogs, drawers, dropdowns, and popovers often live in different packages. A single allocator means each feature does not need to know what values others are using.

## How it works here

1. **Single base (1000)** – all teleported layers share the same starting point, which keeps the implementation simple and predictable.
2. **Auto-increment** – every time a component mounts, it receives the next value in the global stack so the newest element always sits on top, regardless of type.
3. **Scoped offsets** – overlays that belong to the same surface (e.g., `DialogOverlay` vs. `DialogContent`) call `useLayerZIndex({ offset: -2 })` so the overlay sits just beneath the content that spawned it.

```
const modalZ = useLayerZIndex();
const overlayZ = useLayerZIndex({ offset: -2 });
```

## Benefits

- **Deterministic ordering** – the last overlay opened is always on top, no matter if it is a drawer, modal, popover, or toast.
- **Safer refactors** – no need to chase down hard-coded z-index constants across the codebase; everything flows through the same stack.

## When to override

In rare cases you might still need a custom `z-index`. Prefer to:

1. Add a dedicated offset (e.g., `useLayerZIndex({ offset: X })`) if the overlay needs to sit just above/below a sibling.
2. Only apply inline overrides for truly one-off cases, and document why the global manager does not work there.


Use the `Layer Manager` stories in Storybook to verify real interactions (dialog + tooltip/popover, drawer + dialog, nested dialogs, dialog + toast) whenever you add a new teleported component.

