> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Routing

Routes are file-based via [`expo-router`](https://docs.expo.dev/router/introduction/). All files live in `app/`. Each route file imports a screen from `@features/*/screens/` and re-exports it as the default export — no business logic in the routing layer.

Cross-group navigation (onboarding ↔ tutorial ↔ auth ↔ app) is **entirely declarative**: the root `app/_layout.tsx` wraps each group in `<Stack.Protected guard={...}>`.

## Route tree

```mermaid
flowchart TB
  rootLayout["app/_layout.tsx"] --> onbGroup["(onboarding)/"]
  rootLayout --> tutorialGroup["(tutorial)/"]
  rootLayout --> authGroup["(auth)/"]
  rootLayout --> appGroup["(app)/"]

  onbGroup --> onbLayout["_layout.tsx portrait"]
  onbLayout --> onbIndex[index.tsx]

  tutorialGroup --> tutorialLayout["_layout.tsx landscape"]
  tutorialLayout --> tutScreens["welcome · choose-song · play · song-result · reward"]

  authGroup --> authLayout["_layout.tsx"]
  authLayout --> signIn[sign-in.tsx]
  authLayout --> signUp[sign-up.tsx]

  appGroup --> appLayout["_layout.tsx landscape"]
  appLayout --> tabsGroup["(tabs)/"]
  appLayout --> playRoutes["play · play-result · learn · keyboard · dev/*"]

  tabsGroup --> tabsLayout["_layout.tsx<br/>SideTabBar (left)"]
  tabsLayout --> tabIndex["index.tsx → redirect songs"]
  tabsLayout --> tabSongs[songs.tsx]
  tabsLayout --> tabMission[mission.tsx]
  tabsLayout --> tabLeagues[leagues.tsx]
  tabsLayout --> tabProfile[profile.tsx]
```

## Route → screen mapping

| Route                     | File                             | Screen                                                                                                                                                                 |
| ------------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/(onboarding)`           | `app/(onboarding)/index.tsx`     | `OnboardingScreen`                                                                                                                                                     |
| `/(tutorial)`             | `app/(tutorial)/index.tsx`       | `TutorialWelcomeScreen`                                                                                                                                                |
| `/(tutorial)/choose-song` | `app/(tutorial)/choose-song.tsx` | `TutorialChooseSongScreen`                                                                                                                                             |
| `/(tutorial)/play`        | `app/(tutorial)/play.tsx`        | `TutorialGameplayScreen` — `?revealed=1` (from the choose screen's pick reveal) opens it with `animation: "none"` and its reveal settled (`tutorialPlayOpensRevealed`) |
| `/(tutorial)/song-result` | `app/(tutorial)/song-result.tsx` | `TutorialSongResultScreen`                                                                                                                                             |
| `/(tutorial)/reward`      | `app/(tutorial)/reward.tsx`      | `TutorialRewardScreen`                                                                                                                                                 |
| `/(auth)/sign-in`         | `app/(auth)/sign-in.tsx`         | `SignInScreen`                                                                                                                                                         |
| `/(auth)/sign-up`         | `app/(auth)/sign-up.tsx`         | `SignUpScreen`                                                                                                                                                         |
| `/(app)/(tabs)`           | `app/(app)/(tabs)/index.tsx`     | Redirect → `songs`                                                                                                                                                     |
| `/(app)/(tabs)/songs`     | `app/(app)/(tabs)/songs.tsx`     | `SongsScreen`                                                                                                                                                          |
| `/(app)/(tabs)/mission`   | `app/(app)/(tabs)/mission.tsx`   | `MissionScreen`                                                                                                                                                        |
| `/(app)/(tabs)/leagues`   | `app/(app)/(tabs)/leagues.tsx`   | `LeaguesScreen`                                                                                                                                                        |
| `/(app)/(tabs)/profile`   | `app/(app)/(tabs)/profile.tsx`   | `ProfileScreen`                                                                                                                                                        |

There is **no `app/index.tsx`** — the root layout's `<Stack.Protected>` blocks decide which group is mounted as the entry, so no manual boot redirect is needed.

**Tutorial → app hand-off.** When the tutorial completes, its guarded screen redirects to the
app. By default that is the app's home (`/` → tabs → `songs`). When the player left the tutorial
for a song (reward picker Claim, a gameplay suggestion), the tutorial store fixes
`exitHref` with `hasCompleted` and the root passes it as the tutorial group's
`<Stack.Protected redirectTo>`: the tutorial replaces itself with `/(app)/play` in one navigation,
and the `(app)` stack opens as `[play]` alone — the Song list is not mounted under that first
song, so nothing beneath the launch cover can take a tap. With an `exitHref` the root's `(app)`
screen swaps in with `animation: "none"`: the launch cover is the only transition, and the
group's default slide would still be running when the play screen (already loaded, so up at once)
paints its loading card and the cover lifts. Leaving gameplay or its result goes
through `leaveToSongList` (`src/features/piano/leave-to-song-list.ts`): pop when the Song list is
underneath, else replace onto it; Android's back does the same (`useHardwareBackToSongList`).

## Screen orientation

Orientation is **not** a global app setting — each route-group layout declares what it needs via `useOrientation` from [`@core/orientation`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/orientation/). A shared Zustand store resolves the winning request and calls `expo-screen-orientation`'s `lockAsync` exactly once per actual change, so surfaces never race each other into rotation flicker.

| Route group    | Layout file                    | Orientation | Notes                                                                                                                                   |
| -------------- | ------------------------------ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `(onboarding)` | `app/(onboarding)/_layout.tsx` | `portrait`  | One screen: film + Start                                                                                                                |
| `(tutorial)`   | `app/(tutorial)/_layout.tsx`   | `landscape` | First-run piano tutorial. Fades between screens over the root's dark `#04051A` (`contentStyle`), never react-navigation's default white |
| `(app)`        | `app/(app)/_layout.tsx`        | `landscape` | Main app shell (tabs, play, learn, keyboard; dev-only `lab-claim-reward`, the Component Labs clone of the tutorial reward picker)       |
| `(auth)`       | —                              | _(none)_    | Inherits the previous group's lock until auth mounts                                                                                    |

Landscape locks to a **concrete** `LANDSCAPE_RIGHT` (not the ambiguous `LANDSCAPE` mask). On iOS 16+, a mask can be a no-op when the system cannot infer which way to rotate away from portrait.

An **iPhone** always opens **portrait**, however it is held, so its splash is portrait only. An **iPad** opens the way it is held. Both come from Info.plist ([`app.config.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/app.config.ts)), which iOS reads to draw the launch image before any app code runs:

- **iPhone:** `UISupportedInterfaceOrientations` lists only `UIInterfaceOrientationPortrait` (`IPHONE_LAUNCH_ORIENTATIONS`). With all four orientations listed, a phone held sideways showed the whole splash landscape.
- **iPad:** `UISupportedInterfaceOrientations~ipad` lists all four (`IPAD_LAUNCH_ORIENTATIONS`).
- **No `initialOrientation`.** That option writes one starting mask for iPhone and iPad alike; without it expo-screen-orientation starts each device from its own list. `PORTRAIT_UP` would turn an iPad held sideways to portrait under the splash; `DEFAULT` let an iPhone's window follow a phone held sideways while the JS splash was up.
- **Landscape still works.** Info.plist only decides the launch; after that iOS asks the app delegate, and expo-screen-orientation's subscriber answers with the current lock ([`launch-orientation.test.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/config/__tests__/launch-orientation.test.ts)).
- **The lock stays while the app is in the background** (our patch, [`patches/expo-screen-orientation@58.0.3.patch`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/patches/expo-screen-orientation%4058.0.3.patch)). Upstream drops it on background, and the app then answers with its Info.plist default — portrait only on an iPhone. A full-screen ad that allows landscape only (AppLovin's video screen) is still up when a tap on its store button sends the player away, so iOS found no orientation the two shared and killed the app while snapshotting it (`UIApplicationInvalidInterfaceOrientation`). Coming back only re-applies the lock; the module is still registered.

On an upright iPad the first landscape screen switches the app to a letterbox (iPadOS 26). The patch [`patches/expo-screen-orientation@58.0.3.patch`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/patches/expo-screen-orientation%4058.0.3.patch) makes that switch a single turn:

- **Upright iPad:** the lock only announces the new mask (`setNeedsUpdateOfSupportedInterfaceOrientations`) and lets iPadOS letterbox the app.
  - With an explicit `requestGeometryUpdate`, iPadOS first turned the screen 90° and then folded it back into the letterbox, so the splash turned twice.
- **Any iPad on iOS 16+:** the lock skips the legacy `UIDevice` orientation write. It disagreed with the mask and showed up as extra jumps.

That turn happens **after** the splash, on a phone as on an iPad, never under it. Turned under the splash, the launch image swung round on its way out (into the letterbox on an iPad, sideways on a phone), and the logo flashed round:

- **The splash keeps the orientation it opened in** (always portrait on an iPhone). `(app)` and `(tutorial)` take landscape through [`useLandscapeAfterSplash`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/useLandscapeAfterSplash.ts). It asks for nothing until the splash has gone ([`splash-visibility-store`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/splash-visibility-store.ts)), and with no request in the store no lock goes out. Past onboarding the splash itself waits for no lock ([`expectedSplashOrientation`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/splash-handoff.pure.ts) is `null`).
- **The turn happens behind a dark cover.** [`LandscapeTurnCover`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/LandscapeTurnCover.tsx) is a plain screen in the splash's colour, over the navigator and the banner and under the modals.
  - It is up from the first frame, so it is in place when the splash goes, and the Song List is never seen portrait.
  - It fades out (250 ms) once the window is landscape; the open-app paywall then slides in landscape.
  - It covers only a launch into a landscape group, only until the first landscape window. It keeps song previews quiet while up. It gives up 1.5 s after the splash in case the lock is declined.
  - An iPhone always opens portrait, so its every launch into a landscape group turns once behind it. An iPad held landscape has no turn and never sees it.
- **No request keeps the last lock.** Under the splash an iPad's stack can be empty: the launch paywall's landscape overlay is the only request, and closing it before the splash goes used to fall back to portrait, so the window turned portrait and back. The store now skips the lock when nobody is asking ([`orientation-store.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/orientation/orientation-store.ts)).

Root-level modals that need a different orientation while visible (e.g. [`PaywallModal`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/paywall/components/PaywallModal.tsx)) pass `ORIENTATION_PRIORITY.overlay` so they win over the base layout. Pass `null` when hidden so the overlay request is cleared without unmounting the modal — route-group layouts do **not** release on unmount (that caused rotation flicker during group swaps; the incoming layout's request wins by recency instead):

```tsx
// app/(app)/_layout.tsx — landscape, once the splash has gone
useLandscapeAfterSplash();

// PaywallModal — portrait for post-onboarding offer, landscape for in-app upsell
useOrientation(visible ? presentation : null, ORIENTATION_PRIORITY.overlay);
```

The in-app paywall opens from the side tab already in landscape.

The open-app paywalls (session 2+ subscription, session 3 discount) are the one landscape offer that can open before the app is landscape. A phone with its rotation lock on launches the app portrait, and `(app)` issues its landscape lock in the same commit that mounts [`SessionPaywallHost`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/paywall/components/SessionPaywallHost.tsx). The host decides the launch as soon as purchases and Remote Config are in, but opens the offer only once the window is landscape.

The offer also waits for the launch's **App Open** step. From launch #2 on, a player past onboarding and the tutorial who has finished at least 4 songs (lifetime `song_end`) may get an AdMob App Open over the Song List ([`AppOpenHost`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/app-open/components/AppOpenHost.tsx), which reads the launch `SessionPaywallHost` records as `useSessionStore.currentLaunch`). The paywall opens only once `useAppOpenLaunchStore.phase` is `done` — the ad shown (and handed the screen back), skipped (not loaded within 5 s), blocked by its gates or failed; a launch that never tries one — App Open off, a subscriber, too few song starts — is `done` at once, and a step that has not started 15 s after the launch is known is marked `done` anyway. So the two never land on each other and a launch with no App Open waits for nothing.

The step can end wherever the player is, so the offer also waits for the Song List (`/songs`) with nothing covering it and no full-screen ad on it or still handing the screen back ([`launch-paywall.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/paywall/launch-paywall.pure.ts)). Until then it stays owed, and opens the next time all of that holds — back on the Song List after a song, say. The session-3 discount is marked shown only as it opens, so a player who quits before it never loses it. Rules: [ad-trigger-logic.md §6](/docs/ad-trigger-logic.md).

Landscape paywalls also size their root from the window ([`PaywallLandscapeSettle`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/paywall/components/PaywallLayoutBlock.tsx)), not from the `<Modal>`. A Modal first sizes its content from the **device** orientation, which a rotation lock holds at portrait. Left to the Modal, the offer showed as a narrow column until the Modal caught up.

Inside `(app)/(tabs)`, [`SideTabBar`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/components/navigation/SideTabBar/index.tsx) is a left-positioned tab rail (`tabBarPosition: "left"`) sized for landscape — `unstable_settings.anchor` is `songs`.

Active-tab motion ("Lit Dot", DEV 2026-11-23): the Skia flare springs to the new tab (`SIDE_TAB_SLIDE_SPRING`) and lands with a flash, where the inner-edge line grows from its middle and the flare blooms, driven by one 0 → 1 `arriveSv` clock (`SIDE_TAB_*_ARRIVE_*` in `side-tab-active.utils.ts`, rest values = the static Figma look). The newly focused icon or avatar pops 1 → 1.2 → 1 (`useSideTabIconPop`, not on first mount).

The rail announces every trip it starts to another feature — a tab, or the Keyboard launcher — through [`onSideTabNavigate`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/components/navigation/side-tab-navigation.ts). Shared UI cannot import a feature, so a feature that keeps state across those trips listens there; the song list clears its search on it ([songs.md](/docs/features/songs.md#lock-resolution)).

## Immersive piano routes — keep-awake + system gesture deferral (iOS)

Bottom-edge Home / app-switcher deferral is **app-wide** — [`AppProviders`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/providers/AppProviders.tsx) enables it at bootstrap via [`setGameplayGestureDeferralEnabled`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/system-gesture-defer.ts) and the local Expo module [`modules/screen-gesture-defer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/screen-gesture-defer/). It is **not** configured per `Stack.Screen` and **not** toggled from feature screens.

The `play`, `learn`, and `keyboard` stack screens additionally call [`useKeepGameplayAwake`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/hooks/useKeepGameplayAwake.ts) so the device does not auto-lock during an immersive session. `play-result` does not — the session is over and normal auto-lock is fine.

**Transitions.** `/(app)/play` and the entire `/(tutorial)` stack use `animation: "fade"` so the shared prepare loading card (`PrepareLoadingOverlay`) fades in/out rather than sliding over the previous screen. `play-result` and `keyboard` likewise fade. `learn` keeps the stack's own push, except a visit opened with `reveal=1` (`learnOpensWithReveal(route.params)`), which opens in place with `animation: "none"` — see below.

See [architecture.md § System gesture deferral](/docs/architecture.md#system-gesture-deferral-app-wide) for the deferral call chain and rebuild requirements.

## Launch splash — two screens

1. **Native launch image** — the piano keys alone (`assets/splash/splash-keys.png` through react-native-bootsplash, 192dp) on the starry `SplashBackground`. No wordmark, no tagline (`withSplashBottomImage` is no longer registered).
2. **JS launch splash** — [`AppLaunchSplash`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/components/AppLaunchSplash.tsx), mounted from the root layout's first render. Once its backdrop and key art have decoded and fonts are in, it hides the native splash and plays the "Key ripple" intro ([`splash-ripple.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/splash-ripple.pure.ts)) off one clock, starting on the native frame: the keys, big and centred where the native image drew them, dip and light up one by one left → right, then glide up and shrink into place; MAGIC PIANO pops in letter by letter (judgement font, black stroke, gradient-03 sliced per letter); then "Headphone Recommended … NN%". The keys are one Skia canvas ([`SplashRippleKeys`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/components/SplashRippleKeys.tsx)) cutting the glow-free art `assets/splash/splash-keys-clean.png` into five hand-traced key slices over the designer's vector glow; it is drawn under the native splash before the intro starts, so its image upload and shader compiles happen there. Reduced motion keeps the keys in place and only fades the text. The percentage is live, from the boot gates [`useHideSplash`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/useHideSplash.ts) already evaluates ([`splash-progress-store`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/splash-progress-store.ts)).

**Intro, essential loading, then deferred FTUE work.** The intro plays beside Remote Config's
fetch, cheap setup and the app-open chime. When it ends,
[`markSplashIntroDone`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/ui/launch-intro.ts) starts the guarded SDK loading stage in
[`start-app-bootstrap.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/bootstrap/start-app-bootstrap.ts), behind the still splash.
The lifecycle facade owns gameplay warmups, catalog sync and MIDI/version prefetch through
[`AppStartupPolicy`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/domain/policies/app-startup-policy.ts). If onboarding was incomplete
at launch, these tasks wait for both splash hidden and the first FTUE screen committed, then two
frame boundaries and idle. A returning launch starts them after the intro: its navigator waits
for RC and haptics (plus tracking/attribution behind a boot-time ATT prompt), and a completed
player's splash also waits for sampler/SFX launch warmups. RevenueCat and Crashlytics do not gate
navigation. Only the % moves while loading, drawn by Skia from shared values. The boot ceilings
(8 s services, 12 s hard) count from loading start. If the JS splash has not taken over within
`SPLASH_TAKEOVER_GRACE_MS` (2 s), loading starts behind the native splash and refuses a late
intro takeover. See [App startup and lifecycle](/docs/features/app-lifecycle.md) for lifecycle
transitions and restart behavior.

The [splash store](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/store.ts) still decides when the splash may go. The boot gates live in it rather than in React state, so a gate closing re-renders only what reads it: the root layout hears `selectAppReady`, and the % takes its share straight into a shared value. It asks the JS splash to leave, and the JS splash fades out, and only then do `releaseSplashCover`, `markSplashHidden` and `fn_after_splash_screen` run ([`launch-splash-handoff`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/splash/launch-splash-handoff.ts)). If the JS splash never took over, the native splash is hidden directly as before. The launch paywall waits for `useSplashHidden()`, because a native `<Modal>` would draw over the JS splash.

A dev build shows the native image twice: expo-dev-client puts it back up while it downloads the bundle. Release builds show it once.

## Learn Mode entry — lock, guard and reveal

Learn Mode opens after four finished songs (`song_end`; the rule is in [`@core/learn-access`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/learn-access/), the full contract in [songs.md](/docs/features/songs.md#learn-mode-opens-after-four-finished-songs)). Three routing facts follow from it:

- **`/learn` is guarded in the screen.** `LearnModeScreen` renders nothing for a locked player and, once, pops back (`router.back()`), or `router.replace("/songs")` when there is nothing under it. Not a `<Redirect>`: inside this pushed screen it REPLACES `learn` on the `(app)` stack with a fresh `(tabs)` route, leaving two live Song Lists. Every other lock (the Song List pill, the result's Learn tab) sits at a call site, so this one covers whatever reaches the route without passing one — a deep link, a stale path on the stack.
- **`/learn?reveal=1` plays the song reveal first.** The `reveal` param is only set by the "Learn Mode unlocked!" popup's Claim. That visit opens in place (`animation: "none"`), under the popup, which stays up until the path leaves `/songs` — so the popup hands straight to the reveal. `LearnModeScreen` shows the shared [`SongRevealShowcase`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/components/song-reveal/SongRevealShowcase.tsx) for `songRevealHandoffMs()`, then mounts Learn as usual (countdown, Stage 1); the body is told the screen has already arrived (`useScreenEntered({ alreadyEntered: true })`), so the countdown does not wait out the entrance backstop. It is decided once on mount; a visit without the param, or a song the catalog cannot show, goes straight in.
- **The popup is a root host.** [`LearnUnlockHost`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/learn/components/LearnUnlockHost.tsx) is mounted in `app/_layout.tsx` next to `TutorialExitHost`, so it outlives every screen. It opens only while the path is `/songs`, and Claim navigates to `/learn` for `twinkle-twinkle-little-star` with `reveal=1` and `songPlayType: "home"`.

## Root layout — the only place guards live

```tsx
// app/_layout.tsx
export default function RootLayout() {
  return (
    <AppProviders>
      <ProtectedRoutes />
    </AppProviders>
  );
}

function ProtectedRoutes() {
  const [fontsLoaded, fontsError] = useFonts(fontAssets);
  const isReady = fontsLoaded || fontsError !== null;

  useEffect(() => {
    if (!isReady) return;
    BootSplash.hide({ fade: true }).catch(() => undefined);
  }, [isReady]);

  const hasCompleted = useOnboardingStore((s) => s.hasCompleted);
  const hasCompletedTutorial = useTutorialStore((s) => s.hasCompleted);
  const needsTutorial = hasCompleted && !hasCompletedTutorial;

  return (
    <Stack screenOptions={{ headerShown: false }}>
      <Stack.Protected guard={!hasCompleted}>
        <Stack.Screen name="(onboarding)" />
      </Stack.Protected>

      <Stack.Protected guard={needsTutorial}>
        <Stack.Screen name="(tutorial)" />
      </Stack.Protected>

      <Stack.Protected guard={!session}>
        <Stack.Screen name="(auth)" />
      </Stack.Protected>

      <Stack.Protected guard={hasCompleted && !needsTutorial}>
        <Stack.Screen name="(app)" />
      </Stack.Protected>
    </Stack>
  );
}
```

Three things are co-located here on purpose:

1. **Font loading** + **splash dismissal** — they need to run before the user sees any UI.
2. **Zustand reads** for `hasCompleted` and `session` — selectors subscribe the root layout to those slices.
3. **`<Stack.Protected>` guards** — each block is mounted only when its guard is `true`. The router activates the first matching block, so order = priority.

## Guard / redirect flow

`<Stack.Protected>` does the work that per-group `<Redirect />` used to. When a guard flips from `false` to `true`, that block becomes the active stack and Expo Router transitions to its initial route automatically.

```mermaid
flowchart LR
  state[(Zustand)] --> onbSel{"!hasCompleted"}
  state --> authSel{"!session"}
  state --> appSel{"hasCompleted && !!session"}
  onbSel -->|true| onbStack["/(onboarding)"]
  authSel -->|true| authStack["/(auth)/sign-in"]
  appSel -->|true| appStack["/(app)/(tabs)"]
```

### Guard priority

| Order | Guard expression                        | Stack mounted  |
| ----- | --------------------------------------- | -------------- |
| 1     | `!hasCompleted`                         | `(onboarding)` |
| 2     | `hasCompleted && !hasCompletedTutorial` | `(tutorial)`   |
| 3     | `!session` (when auth enabled)          | `(auth)`       |
| 4     | `hasCompleted && !needsTutorial`        | `(app)`        |

The subscription paywall opens after **onboarding** (`finishWithPaywall()` → dismiss → `complete()`), then the tutorial runs. Completing the tutorial mounts `(app)`.

The guards are mutually exclusive by construction: if `!hasCompleted` is true the onboarding block wins; once onboarding and the paywall handoff finish, the tutorial guard takes over; then `(app)` mounts.

### Zustand-driven transitions (no router calls needed)

| Action                                                                                   | State change                                             | Result                                                                                                                                                                |
| ---------------------------------------------------------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Tap Start (`useOnboardingStore.complete()`)                                              | `hasCompleted: false → true`                             | onboarding guard flips off → router renders `(tutorial)`                                                                                                              |
| Complete tutorial (`useTutorialStore.complete()`)                                        | `hasCompleted: false → true`                             | tutorial guard flips off → router renders `(app)/(tabs)`                                                                                                              |
| Reach the tutorial's result (`useTutorialStore.markResultReached()`)                     | `reachedResult: false → true` (persisted)                | nothing this launch; the next cold start restores `hasCompleted: true` → `(app)/(tabs)`                                                                               |
| Reach a `pick_after_play` run's end before claiming (`markResultReached(pendingReward)`) | `reachedResult: true`, `pendingReward` saved (persisted) | nothing this launch; the next cold start keeps `hasCompleted: false` → `(tutorial)`, whose index (`TutorialEntryScreen`) opens the reward picker; **Claim** clears it |
| Pick a song on the choose screen (`useChooseSongStore.pick`)                             | `savedPick` saved (persisted)                            | a relaunch before the result walks the tutorial again, but its hand-off skips `/(tutorial)/choose-song` for `/(tutorial)/play` with that song; completion clears it   |
| Sign-in succeeds (`useAuthStore.setSession(s)`)                                          | `session: null → Session`                                | auth guard flips off, app guard flips on → router renders `(app)/(tabs)`                                                                                              |
| Sign-out (`useAuthStore.signOut()`)                                                      | `session: Session → null`                                | app guard flips off, auth guard flips on → router renders `(auth)/sign-in`                                                                                            |
| 401 from API (interceptor calls `signOut()`)                                             | same as sign-out                                         | same as sign-out                                                                                                                                                      |
| Reset onboarding flow from Profile                                                       | onboarding + tutorial reset, paywall closed, sign-out    | onboarding guard wins → router renders `(onboarding)`                                                                                                                 |

Screens just mutate Zustand and let the root layout react. The only legitimate uses of `router` are:

- **Intra-group navigation** (push/pop inside the same stack): e.g. `router.push('/(auth)/sign-up')` to swap between sign-in and sign-up.

```mermaid
sequenceDiagram
  participant U as User
  participant SI as SignInScreen
  participant Q as useSignInMutation
  participant S as useAuthStore
  participant L as app/_layout (ProtectedRoutes)
  participant R as expo-router

  U->>SI: tap Sign in
  SI->>Q: mutate(payload)
  Q-->>S: setSession(session)
  S-->>L: subscriber re-renders
  L-->>R: <Stack.Protected guard={true}> wraps (app)
  R-->>U: navigates to tabs
```

## Sign-in sequence (cross-layer)

```mermaid
sequenceDiagram
  participant U as User
  participant SI as SignInScreen
  participant Q as useSignInMutation
  participant API as features/auth/api.ts
  participant S as useAuthStore
  participant L as app/_layout (ProtectedRoutes)
  participant R as Expo Router

  U->>SI: Tap "Sign in"
  SI->>Q: mutate({ email, password })
  Q->>API: signInRequest(payload)
  API-->>Q: SessionDto
  Q->>Q: toSession(dto)
  Q->>S: setSession(session)
  S-->>S: persist to MMKV ("auth")
  S-->>L: zustand notifies subscribers
  L-->>R: re-renders Stack with app guard satisfied
  R-->>U: navigates to Home tab
```

## Sign-out sequence

```mermaid
sequenceDiagram
  participant U as User
  participant P as ProfileScreen
  participant Q as useSignOutMutation
  participant S as useAuthStore
  participant QC as queryClient
  participant L as app/_layout (ProtectedRoutes)
  participant R as Expo Router

  U->>P: Tap "Sign out"
  P->>Q: mutate()
  Q->>S: signOut()
  S-->>S: clear session in MMKV "auth"
  Q->>QC: queryClient.clear()
  S-->>L: zustand notifies subscribers
  L-->>R: re-renders Stack, auth guard now wins
  R-->>U: navigates to sign-in
```

## Adding a new route

1. Decide its location in the tree (auth-only? tab? modal?).

2. Add a file under `app/...` that does only:

   ```tsx
   import { MyScreen } from '@features/my-feature/screens/MyScreen';
   export default MyScreen;
   ```

3. If you need params, read them in the route file via `useLocalSearchParams` and pass them as props (see `app/(app)/play.tsx`).

4. If the route needs auth, place it under `(app)/`; the root layout's `<Stack.Protected guard={hasCompleted && !!session}>` already gates the entire group.

## Adding a new top-level group

If you ever need a fourth top-level group (e.g. an `(error)` recovery stack), add a `<Stack.Protected guard={...}>` block to `app/_layout.tsx` and an `app/(new-group)/_layout.tsx`. Keep guards mutually exclusive — pick a Zustand flag that's true in exactly one of the blocks at a time.

***

<small>Source: [`docs/routing.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/routing.md)</small>
