# Neo Region Store — Implementation Plan Status: ready to implement. Nothing in this plan has been applied yet. Scope: `apps/user-ui` (plus one `apps/web-ui` route). Old code is left in place and commented out at its mount point only. No deletions, no git operations, no migrations, no test runs. --- ## 1. Goal Replace the current region/location logic with a single new source of truth: - `neoRegionStore` — Zustand store holding the resolved region, bound, coords, selected address and the two flow flags. - `useRegionNeo` — the only hook any screen may use. It runs the chart's decision internally and returns the store's data. - `LocationWrapperNeo` — mounted where `LocationTestWrapper` is today; renders children only when the hook can return the required data. - `needsAddressFormFlow` — the whole address fallback (choose / add / login). - `needsAddressConfirmation` — map with a fixed pin, address dropdown, "keep this location", "add new address". Every current `useRegion` consumer is migrated to `useRegionNeo`. The old `useRegion`, `LocationTestWrapper`, `LocationFallbackFlow`, `regionStore`, `addressStore` and `region-switch.ts` stay in the repo, unused/commented at mount sites. --- ## 2. Settled decisions 1. **Saved address always wins** when the app has no cached region: if any saved address exists, its region/bound is used; the device fix only decides when the user has no address. 2. **Cached region + device in a different region:** - address exists in the new region → use that address; - guest, or no addresses at all → go ahead with the new region (no confirmation); - addresses exist but none in the new region → `needsAddressConfirmation`. 3. **No pending candidate, no hydration flag, no status enum.** The region returned by the hook is the region. A change is a change; a confirmation only offers a way back. 4. **Publish immediately:** a persisted region renders as soon as it is hydrated; the device decision may switch it later. 5. `selectedAddressId` **is** the active address, always. No read-time "default fallback". When it is non-null, region/bound/coords/name are derived from it. 6. `selectAddress(id)` performs the region switch itself (cart stash/clear/restore, cache invalidation) and then sets the selection. 7. `changeRegion(regionId, boundId?)` switches without an address and clears the selection. 8. `NeoAddressForm` is a thin adapter that renders the existing `AddressForm` component. 9. `AddressSwitcherSheet` mounts the new `NeoAddressFlow`. 10. The 3 s location poll is kept while `needsAddressFormFlow` is up. 11. The fixed-pin map is implemented as a `?fixed=1` mode on the existing `web-ui` `/location-selector` page. 12. Adding an address in a different region shows a warning and then follows the region-switch flow. Defaults accepted: - `fullAddress` = `addressLine1, addressLine2, city` (empties skipped). - Guest draft is auto-selected after login; first address is default (server-side). - Logout clears addresses + selection; region/bound/coords persist. - A persisted region missing from `listRegions` is treated as no cache. - 8 s resolve timeout, then decide without the fix. - Addresses with `regionId == null` are filtered out of the chooser. - The existing form validation and "Set as default" checkbox are kept. --- ## 3. Contracts ### 3.1 `useRegionNeo` return ```ts export type NeoCoords = { latitude: number; longitude: number } export interface NeoRegionData { regionId: number boundId: number regionName: string coords: NeoCoords selectedAddressId: number | null selectedAddress: NeoAddress | null // the full address object fullAddress: string | null // the formatted one-line string isCache: boolean changeRegion: (regionId: number, boundId?: number | null) => Promise selectAddress: (id: number) => Promise } export function useRegionNeo(): NeoRegionData // never null export function useNeoRegionBootstrap(): void // orchestration, mounted by the wrapper ``` - `useRegionNeo` may only be called by a component that `LocationWrapperNeo` renders. It returns the store's data directly and throws if the store has no complete region (a misuse, not a normal state). - The hook calls `getUserAddresses` as a `useQuery` at the top and derives `selectedAddress` / `fullAddress` from that data (falling back to the store while it loads). `selectAddress(id)` is the store action: async only because a cross-region switch awaits the cart stash, and it never calls the address API. A component that creates or edits an address must refresh the list itself (`utils.user.address.getUserAddresses.fetch(undefined)` then `setAddresses(...)`) before selecting. - `useNeoRegionBootstrap` runs the launch decision. The wrapper calls it and then reads the store itself. - Every field except `selectedAddressId` / `selectedAddress` / `fullAddress` is guaranteed present in the returned object (`selectedAddress` and `fullAddress` are null iff there is no address in the region). - `isCache === (origin === 'cache')`. ### 3.2 Store state `apps/user-ui/src/store/neoRegionStore.ts` ```ts type NeoOrigin = 'device' | 'cache' | 'address' | 'manual' interface NeoRegionState { regionId: number | null boundId: number | null regionName: string | null coords: NeoCoords | null origin: NeoOrigin | null addresses: NeoAddress[] selectedAddressId: number | null needsAddressFormFlow: boolean needsAddressConfirmation: boolean // single internal write path — used by the hook, never returned by useRegionNeo applyRegion: (data: { regionId: number boundId: number regionName: string coords: NeoCoords origin: NeoOrigin selectedAddressId: number | null }) => void // validates the selection against the region, persists, clears both flags // other internal actions setAddresses: (addresses: NeoAddress[]) => void // also clears an invalid selection openAddressFlow: () => void closeAddressFlow: () => void setNeedsConfirmation: (value: boolean) => void resetForLogout: () => void // public actions changeRegion: (regionId: number, boundId?: number | null) => Promise selectAddress: (id: number) => Promise } ``` `fullAddress` is derived in the hook from `addresses.find(a => a.id === selectedAddressId)`; it is not duplicated in the store. `applyRegion` is the only place that writes the five region fields plus the selection, so the invariant in §3.6 cannot be bypassed. The persisted snapshot is read by `readNeoRegionSnapshot()` (in `neo-region-cache.ts`), not by a store method — the hook reads it once and feeds it to `applyRegion` with `origin: 'cache'`. ### 3.3 `origin` / `isCache` | origin | meaning | |---|---| | `device` | region/bound taken from the live fix | | `cache` | no usable fix; persisted snapshot kept | | `address` | region/bound taken from a saved address | | `manual` | `changeRegion` without an address | `isCache` is `origin === 'cache'`. `NotifRegionSync` uses `origin === 'device'` for "record the tracked region". ### 3.4 Pure decision function `apps/user-ui/src/lib/neo-region-decision.ts` ```ts export interface NeoAddressSummary { id: number regionId: number | null boundId: number | null isDefault: boolean latitude: number | null longitude: number | null } export type NeoDecision = | { action: 'ready'; regionId: number; boundId: number; origin: NeoOrigin; selectedAddressId: number | null } | { action: 'needs-address-flow' } | { action: 'needs-confirmation'; regionId: number; boundId: number } export function decideNeoRegion(input: { cached: { regionId: number; boundId: number; regionName: string; coords: NeoCoords } | null fix: NeoCoords | null resolved: { regionId: number; boundId: number } | null // null = off / out of every bound isAuthenticated: boolean addresses: NeoAddressSummary[] }): NeoDecision ``` ### 3.5 Decision table `a(region)` = an address with `regionId === region`; `defaultAddr` = the address with `isDefault`. | # | cached | fix / resolved | auth + addresses | Decision | |---|---|---|---|---| | 1 | A | no fix or `resolved == null` | any | `ready(A, A.bound, 'cache', default in A ?? null)` | | 2 | none | no fix / `resolved == null` | default exists | `ready(default.region, default.bound, 'address', default.id)` | | 3 | none | no fix / `resolved == null` | guest / no address | `needs-address-flow` | | 4 | A | resolved B, B == A | any | `ready(A, B.bound, 'device', default in A ?? null)` | | 5 | A | resolved B, B ≠ A | address in B | `ready(B, a(B).bound, 'address', a(B).id)` | | 6 | A | resolved B, B ≠ A | authenticated, addresses exist, none in B | `needs-confirmation(B, B.bound)` | | 7 | A | resolved B, B ≠ A | guest or zero addresses | `ready(B, B.bound, 'device', null)` | | 8 | none | resolved B | guest / zero addresses | `ready(B, B.bound, 'device', null)` | | 9 | none | resolved B | any address | `ready(defaultAddr.region, defaultAddr.bound, 'address', defaultAddr.id)` (decision 2) | Notes: - Row 9 uses the default address; if none is flagged (data anomaly), the lowest id is used. - Rows 1 and 4 preserve an already-valid explicit selection if one exists; otherwise they select the default in that region. - `needs-confirmation` is reachable only from row 6. Its predicate also enforces: `origin === 'device'`, `resolved.regionId !== cached.regionId`, `addresses.length > 0`, no address in `resolved.regionId`. ### 3.6 Selection invariant > `selectedAddressId` is either `null`, or the id of an address whose `regionId === regionId` and `boundId === boundId`. Enforced only in the store: | Moment | Effect | |---|---| | Decision adopts an address | `selectedAddressId = that id` | | Decision adopts device/cache with no address in the region | `selectedAddressId = null` | | `changeRegion` | clears the selection | | `selectAddress(id)` | switches to the address's region/bound if needed, then selects | | `selectAddress` with an address outside the current region | allowed — it performs the switch | | `setAddresses` refetch no longer contains the id | clears the selection | | Logout | clears addresses + selection | | Address list contains `regionId == null` | filtered out before storing | --- ## 4. New files | File | Responsibility | |---|---| | `apps/user-ui/src/lib/neo-address.ts` | `NeoCoords` / `NeoAddress`, `toNeoAddress`, `addressCoords`, `formatNeoAddress`. | | `apps/user-ui/src/lib/neo-region-decision.ts` | Pure decision function (section 3.4/3.5). No React, no store, no network. | | `apps/user-ui/src/lib/neo-region-switch.ts` | Cart/cache side effects for a region change, lifted from `region-switch.ts` minus every `useRegionStore` write. Signature: `applyRegionSwitch(fromRegionId \| null, toRegionId, queryClient): Promise`. | | `apps/user-ui/src/lib/neo-region-cache.ts` | `readNeoRegionSnapshot()` / `writeNeoRegionSnapshot()` / `clearNeoRegionSnapshot()` over `StorageServiceCasual`, key `freshyo_neo_region_v1`. Snapshot = `{ regionId, boundId, regionName, coords }`. | | `apps/user-ui/src/store/neoRegionStore.ts` | Store (section 3.2). Holds the data; `applyRegion` persists the snapshot; exposes the actions. | | `apps/user-ui/src/hooks/useRegionNeo.ts` | `useNeoRegionBootstrap` (orchestration, section 5) + `useRegionNeo` (non-null selector for wrapper children). | | `apps/user-ui/components/LocationWrapperNeo.tsx` | The gate (section 6.1). | | `apps/user-ui/src/components/location/neo/NeoLoadingScreen.tsx` | Spinner + "Finding your region…". | | `apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx` | Whole fallback: choose saved address / add / login. | | `apps/user-ui/src/components/location/neo/NeoAddressForm.tsx` | Adapter over the existing `AddressForm` + cross-region warning. | | `apps/user-ui/src/components/location/neo/NeoConfirmLocation.tsx` | Map + pin + dropdown + actions. | | `apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx` | WebView around `/location-selector?...&fixed=1`. | | `apps/user-ui/tests/lib/neo-region-decision.test.ts` | The 9-row table. | | `apps/user-ui/tests/lib/neo-region-store.test.ts` | Selection invariant + `selectAddress`/`changeRegion`. | | `apps/user-ui/tests/components/neo-location-wrapper.test.tsx` | Four render branches. | --- ## 5. `useNeoRegionBootstrap` orchestration Module-level guards (not store fields): ```ts let snapshotRead: Promise | null = null let decisionStarted = false ``` Effect, in order: 1. If `useAuthOptional() == null` → do nothing. This keeps instances above `AuthProvider` (through `useGetEssentialConsts`) as read-only consumers, so they cannot settle the launch decision without a user. 2. `const snapshot = await readNeoRegionSnapshot()` once; if present, `applyRegion({ ...snapshot, origin: 'cache', selectedAddressId: null })`. 3. `startTracking()` (existing `locationStore`, idempotent) — one fix, no movement tracking. 4. Wait for the fix to settle: `granted` + coords, or `denied` / `services-off` / `unavailable` / `error`, or an 8 s timeout. 5. `listRegions` starts as a `useQuery` on mount and `getUserAddresses` starts as the existing `useQuery` when auth settles — both in parallel with the fix. The decision gate waits for `isFetched || isError` on regions and (when signed in) addresses; `run` then reads their data instead of fetching. 6. `run` starts the snapshot read and `trpc.common.resolveRegionByLocation.fetch({ lat, lng })` together in one `Promise.all`; the resolve is `null` on failure. Round coords to 1e-5 for the request only. 7. `decideNeoRegion(...)`. 9. Apply. If the decision's region differs from the published one, run `applyRegionSwitch(previous, next, queryClient)` first — a decision that moves region is a real switch (cart stash/clear + cache invalidation): - `ready` → `applyRegion({ regionId, boundId, regionName, coords, origin, selectedAddressId })`; it persists the snapshot and clears both flags. - `needs-address-flow` → `openAddressFlow()`. - `needs-confirmation` → `applyRegion({ B, origin: 'device', selectedAddressId: null })` then `setNeedsConfirmation(true)` (region is already B; see decision 3). 10. Set `decisionStarted = true` before `run`; the auth-change and recovery-poll paths reset it deliberately. Address subscription: every `getUserAddresses` result → `setAddresses(...)` (filters null-region rows, validates the selection). Polling: while `needsAddressFormFlow` is true **and the location is unusable** (`denied`, `services-off`, `unavailable`, `error`), every 3 s call `probe()`; on a false → true transition, reset `decisionStarted`, clear the flag and re-run the effect. When the flow is up only because the user has no address, the fix already exists, so polling is skipped (otherwise it would re-decide and flicker every 3 s). Same recovery behaviour as `LocationTestWrapper` today, moved into the hook. `changeRegion`: ``` previous = get().regionId await applyRegionSwitch(previous, regionId, queryClient) applyRegion({ regionId, boundId: boundId ?? regionFromList.effectiveBoundId, regionName, coords: regionCentre, origin: 'manual', selectedAddressId: null }) persist snapshot; setNeedsConfirmation(false) ``` `selectAddress(id)`: ``` address = get().addresses.find(a => a.id === id) if (!address || address.regionId == null) return if (address.regionId !== get().regionId) await applyRegionSwitch(get().regionId, address.regionId, queryClient) boundId = address.boundId ?? await resolveBound(address.regionId, address.coords) ?? effectiveBoundId applyRegion({ regionId, boundId, regionName, coords: address.coords, origin: 'address', selectedAddressId: id }) persist snapshot; setNeedsConfirmation(false) ``` The hook re-exports both actions from the store so `useRegionNeo().changeRegion === store.changeRegion`. --- ## 6. Components ### 6.1 `LocationWrapperNeo` ```tsx useNeoRegionBootstrap() const regionId = useNeoRegionStore(s => s.regionId) const boundId = useNeoRegionStore(s => s.boundId) const regionName = useNeoRegionStore(s => s.regionName) const coords = useNeoRegionStore(s => s.coords) const needsForm = useNeoRegionStore(s => s.needsAddressFormFlow) const needsConfirm = useNeoRegionStore(s => s.needsAddressConfirmation) if (needsForm) return if (regionId == null || boundId == null || regionName == null || coords == null) { return } if (needsConfirm) return return <>{children} ``` The wrapper never calls `useRegionNeo`; it reads the store directly. That is what makes the hook's non-null contract true: every component that calls it is rendered by this gate, after the four region fields exist. The fallback screens (`NeoAddressFlow`, `NeoAddressForm`, and the shared `AddressForm`) also read the store directly, because they are rendered *before* a region exists. Mounted inside `AuthProvider`, directly replacing `LocationTestWrapper` (which is commented out). ### 6.2 `NeoAddressFlow` (the whole fallback) Modes: `'choose' | 'add' | 'login'` (same shape as the old flow, new implementation). - `choose`: list `addresses` from the store; tapping one calls `selectAddress(id)` and closes (the modal case) / lets the wrapper render children (the gate case). A lone address auto-opens once. - If unauthenticated, the list is empty; renders a login entry point, plus add. - `add`: renders `NeoAddressForm`. - `login`: renders the existing `Login` screen in place (same as the old flow), returning to `choose` on success. - Manual opens (location bar / switcher) set `needsAddressFormFlow = true`; the wrapper shows the same surface. No device re-check is forced. ### 6.3 `NeoAddressForm` Renders the existing `AddressForm` with: - `draftMode={!isAuthenticated}` - `onResolvedRegion` → stored in local state (used for the warning + success handling) - `onSuccess(addressId?)`: - `addressId != null` → `await selectAddress(addressId)` - draft (no id) → `await changeRegion(resolved.regionId, resolved.boundId)` (the draft is posted by `PendingAddressSync` after login) - clear `needsAddressFormFlow` - Cross-region warning: when `onResolvedRegion.regionId !== store.regionId`, render an inline warning: *"This address is in . Saving will switch your region and clear your cart for ."* - `AddressForm` gains one optional prop `onBeforeSubmit?: () => Promise | boolean` (default `true`), checked in its `onSubmit` before any mutation. `NeoAddressForm` passes a handler that shows a `BottomDialog` with Continue/Cancel when the region differs. The other three mounts are unaffected. Note: the old form already implements the chart's add-address logic — device fix prefilled, map picker via `LocationMapStep`, `resolveBound` gate, "outside delivery area → try selecting on the map", submit disabled until serviceable. No new form logic is written. ### 6.4 `NeoConfirmLocation` - `NeoFixedPinMap` at `coords`. - `BottomDropdown` listing `addresses` (foreign regions included), current selection highlighted. - "Keep this location" → `setNeedsConfirmation(false)`. - Picking an address → `selectAddress(id)` (which switches, clears the flag). - "Add new address" → `setNeedsConfirmation(false)`; `openAddressFlow()`. ### 6.5 `NeoFixedPinMap` + web-ui `?fixed=1` `NeoFixedPinMap` renders `WebView` at: ``` ${WEB_UI_BASE_URL}/location-selector?lat=&lng=&fixed=1 ``` In `apps/web-ui/src/routes/location-selector.tsx`, when `fixed=1`: - marker created at the given point, `draggable: false`; - no `dragstart` / `dragend` / `click` listeners that rewrite the point; - Continue button hidden; - the map may still pan/zoom; the pin does not move. This is the only web-ui change. --- ## 7. Modified files | File | Change | |---|---| | `app/_layout.tsx` | Comment out ``; add `` in the same position (inside `AuthProvider`). | | `src/components/AddressForm.tsx` | Reads `regionId` / `boundId` from the neo store directly (it is also shown in the fallback, before a region exists); adds the optional `onBeforeSubmit` prop. Behaviour otherwise unchanged. | | `src/hooks/prominent-api-hooks.ts` | Reads `boundId` / `regionId` / `selectedAddressId` from the neo store directly (it runs above `AuthProvider`, outside the wrapper). | | `app/(drawer)/(tabs)/me/index.tsx` | `region?.name` → `regionName`. | | `components/cart-page.tsx` | `useRegion` → `useRegionNeo`; `selectedAddressId` + `setSelectedAddressId` → `selectedAddressId` + `selectAddress`; `addresses` from the store for the gate condition. | | `components/checkout-page.tsx` | `useRegion` → `useRegionNeo`. | | `components/CheckoutAddressSelector.tsx` | Read `selectedAddressId` from the hook; drop the `selectedAddress`/`onAddressSelect` props; selection → `selectAddress`; add-address modal success → `selectAddress`. Remove the local auto-select-default effect (the decision now owns it). | | `components/CheckoutAddressDisplay.tsx` | Render `fullAddress`; no tRPC query, no `useAddressStore`, no `selected ?? default` fallback. | | `components/PaymentAndOrderComponent.tsx` | `regionId` / `boundId` from the hook. | | `components/ProductDetail.tsx` | `regionId` from the hook. | | `components/QuickDeliveryAddressSelector.tsx` | `regionId` + `selectedAddressId` from the hook; `setSelectedAddressId` → `selectAddress`. | | `src/components/LocationBar.tsx` | `regionName` + `fullAddress` from the hook; no tRPC, no `useAddressStore`. | | `src/components/location/AddressSwitcherSheet.tsx` | Mount `NeoAddressFlow` instead of `LocationFallbackFlow`. | | `src/components/NotifRegionSync.tsx` | `regionId` from the hook; `origin === 'device'` from the store instead of `bound != null`. | | `components/CartAddressGate.tsx` | `coords` from the hook; on form success `selectAddress(addressId)` then `onDone()`. Keep its 3 s poll (or rely on the hook's poll — flag the duplicate and keep the gate's, which only runs when `coords` is null). | | `src/components/PendingAddressSync.tsx` | After create: refetch addresses into the store, then `selectAddress(created.id)`. | | `apps/web-ui/src/routes/location-selector.tsx` | `fixed=1` mode. | | `tests/helpers/test-utils.tsx` | Add `seedNeoRegion({regionId, boundId, regionName, coords, addresses, selectedAddressId})`. | | `tests/helpers/reset.ts` | Reset the neo store between tests. | Untouched (kept deliberately): `src/hooks/useRegion.ts`, `src/store/regionStore.ts`, `src/store/addressStore.ts`, `src/lib/region-switch.ts`, `components/LocationTestWrapper.tsx`, `src/components/location/LocationFallbackFlow.tsx`. --- ## 8. Region switching `neo-region-switch.ts` copies the body of `confirmRegionSwitch` minus the old store write: 1. `if (from !== to)` → `stashRegionCarts(from)`, `clearLocalCart('regular')`, `clearLocalCart('flash')`. 2. Clear quick-delivery/checkout selections, tags, product/slot caches; remove region-scoped query keys. 3. `restoreRegionCarts(to)`. 4. `queryClient.invalidateQueries()`. The store then writes `regionId/boundId/regionName/coords/origin`; selection is cleared by `changeRegion` and set by `selectAddress`. `confirmRegionSwitch` stays untouched for the old code paths; nothing new imports it. --- ## 9. Persistence - Key: `freshyo_neo_region_v1` (via `StorageServiceCasual`). - Snapshot: `{ regionId, boundId, regionName, coords, selectedAddress }`. - The selected `NeoAddress` object is cached too. On hydration it is seeded as a provisional address and selected, so the location bar / checkout can render it before the live address list arrives; the live list then replaces it and clears the selection if the address no longer exists. - Applying the persisted snapshot uses `origin: 'cache'` and does not touch the flags. - Written on every `ready` / `changeRegion` / `selectAddress` (`changeRegion` persists `selectedAddress: null`). - The persisted selection wins over the default when the decision runs, provided it still belongs to the chosen region. - Cleared only if `regionId` is missing from `listRegions` (then re-decide as no-cache). --- ## 10. Polling The hook owns the 3 s probe. It runs only while `needsAddressFormFlow` is true and re-runs the decision when the device becomes usable. `CartAddressGate` keeps its own poll only for the "no fix yet on the cart" case; this is noted as the one duplicated poll. --- ## 11. Consumer migration details | Consumer | Fields used | Notes | |---|---|---| | `me/index.tsx` | `regionName` | subtitle text | | `cart-page.tsx` | `regionId`, `selectedAddressId`, `addresses` | gate condition = `addresses.length === 0` | | `checkout-page.tsx` | `regionId`, `selectedAddressId` | route guard + the order's address | | `CheckoutAddressSelector.tsx` | `regionId`, `selectedAddressId` | drop props; `selectAddress` | | `CheckoutAddressDisplay.tsx` | `fullAddress` | no fallback lookup | | `PaymentAndOrderComponent.tsx` | `regionId`, `boundId` | flash eligibility | | `ProductDetail.tsx` | `regionId` | query enabled | | `QuickDeliveryAddressSelector.tsx` | `regionId`, `selectedAddressId` | same-region warning uses `regionId` | | `LocationBar.tsx` | `regionName`, `fullAddress` | sheet opens the new flow | | `NotifRegionSync.tsx` | `regionId`, `origin` | `origin === 'device'` | | `prominent-api-hooks.ts` | `regionId`, `boundId`, `selectedAddressId` | must work above `AuthProvider` | | `AddressForm.tsx` | `regionId`, `boundId` | store selectors (fallback-safe) | `useAddressStore` remains in the tree but nothing writes it after this change. `LocationFallbackFlow` and `LocationTestWrapper` become unreferenced. --- ## 12. Tests New: - `neo-region-decision.test.ts` — one test per row of the table, plus the confirmation predicate (guest / no address / address in B / same region). - `neo-region-store.test.ts` — `selectAddress` switches when the region differs; `changeRegion` clears the selection; `setAddresses` clears a vanished selection; logout clears addresses/selection. - `neo-location-wrapper.test.tsx` — loading / flow / confirmation / children. Updated (not run): - `tests/helpers/test-utils.tsx`, `tests/helpers/reset.ts` — seed/reset the neo store. - `tests/pages/cart.test.tsx`, `tests/pages/checkout.test.tsx`, `tests/pages/home.test.tsx`, `tests/pages/me-hub.test.tsx`, `tests/pages/addresses.test.tsx`, `tests/pages/payment-and-order.test.tsx`, `tests/pages/flash-checkout.test.tsx` — swap `useRegion`/`useAddressStore` seeds for the neo store. - `tests/lib/prominent-api-hooks.test.tsx`, `tests/lib/notifications.test.tsx` — `origin` and hook nullability. - `tests/components/checkout-address.test.tsx`, `quick-delivery-address-selector.test.tsx`, `address-form.test.tsx` — new selection source. - `tests/components/location-components.test.tsx` and `tests/lib/use-region.test.tsx` continue to test the old, still-present components/hook; leave them alone unless they import a changed file. Per AGENTS: tests are written/updated alongside the code but **not executed** unless requested. --- ## 13. Build order 1. `change-log.txt` entry (timestamped diff summary) — before any non-md/txt edit. 2. `neo-region-decision.ts`. 3. `neo-region-cache.ts` + `neoRegionStore.ts` + `neo-region-switch.ts`. 4. `useRegionNeo.ts`. 5. `LocationWrapperNeo.tsx` + `NeoLoadingScreen.tsx`. 6. web-ui `?fixed=1` + `NeoFixedPinMap.tsx` + `NeoConfirmLocation.tsx`. 7. `NeoAddressFlow.tsx` + `NeoAddressForm.tsx` (+ `AddressForm.onBeforeSubmit`). 8. Migrate consumers (section 7) + `PendingAddressSync`. 9. Mount in `_layout.tsx`, comment out `LocationTestWrapper`. 10. Tests + helpers. 11. Manual pass (section 14). The app stays on the old wrapper until step 9, so every intermediate state is runnable. --- ## 14. Manual verification 1. Fresh install, location on, inside bounds → children render; `regionName` correct; no flow screen. 2. Fresh install, location off, no address → `NeoAddressFlow`; the 3 s poll recovers after enabling location. 3. Fresh install, location off, logged in with a default address → app opens on the default's region, no flow. 4. Guest adds an address → saved locally → region follows it → login → draft posted, selected, first = default. 5. Cached A, device A → no switch. 6. Cached A, device B, guest or no address → silent switch to B, no confirmation. 7. Cached A, device B, address in B → switch to B with that address selected. 8. Cached A, device B, addresses only in A → confirmation screen: dropdown populated; "Keep" stays on B; picking A switches back; "Add new" opens the flow. 9. Add address out of bounds → submit blocked, "try selecting on the map" → map retry. 10. Add address in another region → warning → confirm → switch + cart stashed/restored. 11. Cart with no address → gate; save → `selectAddress` → cart shows `fullAddress`. 12. Logout → addresses/selection cleared; region stays. --- ## 15. Risks / notes - **Upper-tree consumers:** `useGetEssentialConsts` runs above `AuthProvider`. `useRegionNeo()` returns `null` there until the wrapper populates the store; the query already tolerates a null bound. No orchestration runs without auth. - **Double poll:** the hook polls while the fallback is up; `CartAddressGate` polls when the cart has no fix. Accepted for now. - **Two switches in row 6:** the device switch happens before the confirmation renders; choosing an address switches again. Cart stashing makes this safe; `confirmRegionSwitch`'s contract (ask before switching) is not honoured for the device switch by design. - **`AddressForm.onBeforeSubmit`** is the only behavioural change to a shared old component; default `true` keeps the other three mounts identical. - **Fixed-pin map** is the only cross-app change; `web-ui` is otherwise untouched. - **`needsAddressFormFlow`** is used both by the launch decision and by manual opens (location bar); manual opens never reset the decision. --- ## 16. Out of scope - Deleting the old hook/store/components. - Rewriting the address book (`me/addresses`) onto the neo store. - Cross-region warning in the checkout add-address modal (it inherits `selectAddress` switching, but no warning dialog). - Any backend or database change. - web-ui location-aware launch (`RegionGate` stays as-is).