[2026-10-07 13:00:00] BACKEND per-region storefront cache generation (fixed contract; UI clients done by a second agent).

Planned diffs (backend + db_helper only; NO UI app touched; NO migration run; NO tests):

packages/shared/types/region.types.ts
  - Add RegionCacheVersions { regionId, cacheVersion, availabilityVersionNum, slotsVersionNum }.

packages/db_helper_sqlite/src/db/schema.ts
  - New table regionCacheVersions (region_id NOT NULL UNIQUE FK->regions.id,
    cache_version / availability_version_num / slots_version_num NOT NULL DEFAULT 1).

packages/db_helper_sqlite/drizzle/0008_region_cache_versions.sql (new, NOT run)
  - CREATE TABLE IF NOT EXISTS + UNIQUE index + INSERT seed row per existing region.
packages/db_helper_sqlite/drizzle/meta/_journal.json
  - Append journal entry idx 8 -> 0008_region_cache_versions.

packages/db_helper_sqlite/src/lib/region-cache-versions.ts (new)
  - getRegionCacheVersions(regionId) (auto-creates row when missing),
    incrementRegionCacheVersion / incrementRegionAvailabilityVersionNum /
    incrementRegionSlotsVersionNum. Global key_val_store counters untouched.
packages/db_helper_sqlite/index.ts — export the four helpers.

packages/db_helper_sqlite/src/stores/store-helpers.ts
  - regionId FIRST param on getAllProductsForCache, getAvailabilityForCache,
    getAllStoresForCache, getAllDeliverySlotsForCache, getAllSpecialDealsForCache,
    getAllProductTagsForCache, getAllTagsForCache, getAllTagProductMappings,
    getAllSlotsWithProductsForCache, getAllBannersForCache
    (+ getAllProductCombosForCache, same treatment — needed so combo rows stay
    in-region; not in the contract list, reported).
  - SQL where region_id on region-owned tables; JS-filter SKU-linked rows via the
    parent product_info.region_id; banner skuIds / slot skuIds / tag relatedStores
    filtered to in-region ids.
packages/db_helper_sqlite/src/user-apis/stores.ts
  - getStoreSummaries(regionId, ...), getStoreDetail(regionId, storeId) (null
    outside region), getStoresSummary(regionId).
packages/db_helper_sqlite/src/user-apis/banners.ts — getActiveBanners(regionId).
packages/db_helper_sqlite/src/user-apis/slots.ts
  - getActiveSlotsList(regionId), getProductAvailability(regionId, in-region SKUs).
packages/db_helper_sqlite/src/user-apis/product.ts
  - getSuspendedSkuIds(regionId); new getSkuRegionId/getSkuRegionIds (server-side
    SKU->region resolution for region-less live user endpoints; no client trust).
apps/backend/src/sqliteImporter.ts — re-export new/changed helpers.

apps/backend/src/trpc/apis/common-apis/common.ts
  - scaffoldProducts(regionId): reads scoped DB helper directly (NOT the
    in-memory product-store); nextDeliveryDate = latest in-region slot per SKU
    (matches old DESC semantics); tags/mappings scoped; images signed.
  - scaffoldAvailability(regionId). getAllProductsSummary keeps no-input shape
    for admin UIs (untouched apps) by aggregating per-region scaffolds (reported).
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
  - scaffoldEssentialConsts(regionId): global consts + region's three versions +
    assetsDomain/apiCacheKey + regionId + regionSettings via
    getEffectiveRegionSettings. essentialConsts now REQUIRES {regionId} input
    (UI callers cannot be updated here — reported for the client agent).
  - getStoresSummary endpoint keeps no-input shape via per-region aggregation
    (reported).
apps/backend/src/trpc/apis/user-apis/apis/stores.ts
  - scaffoldStores(regionId), scaffoldStoreWithProducts(regionId, storeId)
    (404/NOT_FOUND outside region).
apps/backend/src/trpc/apis/user-apis/apis/slots.ts
  - scaffoldSlotsWithProducts(regionId) via scoped DB helper directly
    (slot-store NOT keyed by region); getSlots endpoint aggregates per region.
apps/backend/src/trpc/apis/user-apis/apis/banners.ts — scaffoldBanners(regionId).
apps/backend/src/trpc/apis/user-apis/apis/product.ts + cart.ts (live, region-less)
  - Resolve region server-side per requested SKU ids, then call region-keyed
    in-memory stores (no client-region trust).
apps/backend/src/stores/product-store.ts + slot-store.ts
  - regionId FIRST param on initialize*/getAll*/get*/getMultipleProductsSlots.
apps/backend/src/stores/product-tag-store.ts + banner-store.ts
  - initialize*(regionId).
apps/backend/src/lib/gen-store.ts
  - KV key `essential_consts:{regionId}`; refreshGenKv(regionId?) (no-arg =
    all regions, kept for seed/flash/const callers); readEssentialConstsFromKv
    requires regionId (throws when missing — no silent global fallback).
apps/backend/src/lib/cloud_cache.ts
  - createRegionCacheFiles(regionId) writing ONLY per-region paths
    ({key}/regions/{id}/v-{cv}/products|stores|banners|essential-consts.json +
    stores/{storeId}.json, regions/{id}/av-{av}/availability.json,
    regions/{id}/slots/v-{sv}/slots.json); per-region purge + KV mirror.
  - createAllCacheFiles(regionId?) iterates all regions (or one); GLOBAL file
    generation REMOVED (all known consumers are the UI cache hooks being migrated
    by the client agent; backend tests also read them — reported, not updated).
  - createSlotsCacheFile(regionId, refresh) / createAvailabilityCacheFile(regionId,
    refresh) — admin slots/product routers pass ctx.staffUser region.
apps/backend/src/stores/store-initializer.ts
  - initializeAllStores(regionId?) resolves target regions (one or all) and
    inits each; scheduleStoreInitialization(regionId?) forwards region to the DO.
apps/backend/src/jobs/cache-creator.ts (CacheCreator DO)
  - schedule(regionId?) accumulates pendingRegions; alarm drains them (all-region
    when empty). No global mutable current-region.
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
  - create: fire-and-forget createRegionCacheFiles(newRegion.id) with error log.
apps/backend/src/trpc/apis/admin-apis/apis/{store,banner,product,slots}.ts
  - Pass ctx.staffUser region into scheduleStoreInitialization /
    createSlotsCacheFile / createAvailabilityCacheFile.

In-memory store decision: scaffolds read the scoped DB helpers directly; the
in-memory stores (product/slot) are keyed by region (regionId first param) and
live region-less user endpoints resolve the region server-side from SKU ids.
Global-files: REMOVED (see above).
Typecheck: tsc --noEmit for db_helper_sqlite + backend; fix own errors.

[2026-10-07 00:34:48] sqlite drizzle query logging — enable SQL logging on the current D1 instance.

File: packages/db_helper_sqlite/src/db/db_index.ts
Diff plan:
  - Add isQueryLoggingDisabled() helper reading (globalThis as any).ENV?.DRIZZLE_LOG
    ?? (globalThis as any).process?.env?.DRIZZLE_LOG (safe on Workers, no direct
    process.env access). Logging is ON unless flag is false/'false'/'0'.
  - Add queryLogger = { logQuery(query, params) } printing `[drizzle] <query>` + params
    via console.log.
  - Pass `logger` into drizzle(database, { schema, logger }) in initDb so every query
    through the current instance is logged. Set DRIZZLE_LOG=false to silence.

[2026-10-07 10:11:12] Phase 1 (superadmin) — regions, bounds, bound settings, superadmin identities.

New migration 0006 plus a new superadmin API channel and superadmin UI. Planned diffs:

packages/db_helper_sqlite/src/db/schema.ts
  - Add RegionGeoJson interface and tables regions, region_bounds,
    region_bound_settings (region_id + bound_id + key + value), superadmins.
  - Add relations for the above.

packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (new)
  - Create the four tables + unique indexes.
  - Seed region "Mahabubnagar"; two bounds (Mbnr-1 priority 1, Mbnr-2 priority 2)
    with exact GeoJSON; 11 bound settings rows per bound; bootstrap superadmin.
packages/db_helper_sqlite/drizzle/meta/_journal.json
  - Append journal entry idx 6 -> 0006_regions_and_superadmins.

packages/db_helper_sqlite/src/superadmin-apis/regions.ts (new)
  - Region/bound/settings persistence + effective-bound (lowest priority).
packages/db_helper_sqlite/src/superadmin-apis/auth.ts (new)
  - Superadmin lookup.
packages/db_helper_sqlite/index.ts
  - Export the new persistence helpers.

packages/shared/types/region.types.ts (new), superadmin.types.ts (new)
packages/shared/types/index.ts
  - Re-export the new types.

apps/backend/src/trpc/trpc-index.ts
  - Add superadmin context field and superadminProcedure guard.
apps/backend/src/app.ts
  - Resolve superadmin identity from token (identityType/superadminId).
apps/backend/src/trpc/router.ts
  - Register superadmin router.
apps/backend/src/trpc/apis/superadmin-apis/apis/{auth,regions,superadmin-trpc-index}.ts (new)
apps/backend/src/sqliteImporter.ts
  - Re-export new superadmin/region helpers.

apps/superadmin-ui/src/lib/trpc-client.ts
  - Use a separate superadmin_token storage key.
apps/superadmin-ui/src/lib/auth-context.tsx
  - Authenticate via superadmin.auth (login/me).
apps/superadmin-ui/src/routes/login.tsx
  - Superadmin username/password copy.
apps/superadmin-ui/src/routes/regions.tsx (new)
apps/superadmin-ui/src/routes/dashboard.tsx, src/components/AppShell.tsx
  - Add Regions navigation.
apps/superadmin-ui/src/routeTree.gen.ts
  - Register the /regions route (normally regenerated by the router plugin).

[2026-10-07 10:49:25] Phase 2 (staff/admin) — per-bound regional settings in admin-ui.

apps/admin-ui/components/context/staff-auth-context.tsx
  - Extend the session `Staff` shape with optional `regionId: number | null`
    (login already returns it); expose `regionId` on the auth context value.
  - Capture regionId from the login response (setStaff(data.staff)).
  - Non-breaking: existing consumers of `staff` keep working.

apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
  - Replace the single global constants form with one tab per region bound
    (admin.region.bounds, ascending priority). Each tab shows the bound
    description (or "Bound #id") + priority and marks the lowest-priority
    bound as "Effective" (its settings apply to checkout).
  - Selected bound loads admin.region.getBoundSettings and renders the 11
    regional keys as editable inputs (reuse ConstantInput; add a
    `allowSectionNavigation` prop so popularItems/allItemsOrder become inline
    comma-separated inputs instead of links to the global editors).
  - Save via admin.region.updateBoundSettings with only changed keys
    (string|null values). Default-select lowest-priority bound; reinitialize
    the form (Formik enableReinitialize + key) so drafts do not leak between
    tabs. Loading / error / "no bounds configured" states.
  - Keep the existing global constants form reachable via a top-level
    "Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
  - Show the current region name (admin.region.current) in the header.
  - No staff-account creation UI exists in admin-ui (createStaffUser/
    getRoles are unused); nothing to remove.

[2026-10-07 10:51:16] Phase 3 (user-ui) — browsing region store, selection UI, switch/reset, address region, regional checkout + history labels.

New files:
- apps/user-ui/src/store/regionStore.ts (new)
  - zustand store persisted via zustand/middleware `persist` + `createJSONStorage`
    over common-ui `StorageServiceCasual`. State: `selectedRegionId: number | null`,
    `selectedRegion: RegionSummary | null`, monotonic `regionGeneration` marker
    (race guard). Actions: `setRegion(region)`, `clearRegion()`. Persist key
    `freshyo-region`, version 1.
- apps/user-ui/src/lib/region-switch.ts (new)
  - Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
    local carts (clearLocalCart), resets quick-delivery selected slot, address
    selection, slot/store stores and flash-cart/flash-navigation state, calls
    regionStore.setRegion, then invalidates all react-query caches.
- apps/user-ui/src/components/RegionSelector.tsx (new)
  - Lists trpc.common.listRegions. `mode='gate'` renders a full-screen first-run
    chooser; `mode='switch'` is dialog content and opens an Alert confirmation
    stating the whole cart will be cleared, then runs confirmRegionSwitch.
- apps/user-ui/src/components/RegionGate.tsx (new)
  - Hydration-aware gate: waits for persisted region, validates the saved region
    against common.listRegions (clears stale ids), renders RegionSelector until a
    region exists, otherwise children.

Modified files:
- packages/shared/types/app-common.types.ts
  - Add optional `regionId?: number` to AddressFormProps.initialValues.
- apps/user-ui/src/components/AddressForm.tsx
  - Query common.listRegions; required inline region dropdown; new addresses
    default to the browsing region while edits keep the stored region unless
    explicitly changed; include `regionId` in create/update payloads + Yup rule.
- apps/user-ui/components/CheckoutAddressSelector.tsx
  - Region-aware selection: cross-region address prompts confirmation, runs
    confirmRegionSwitch and routes home; default auto-select only for the current
    region; attach-location update now sends regionId.
- apps/user-ui/components/QuickDeliveryAddressSelector.tsx
  - Same cross-region address handling (confirmation + centralized switch +
    navigate home); shows a switch prompt when the selected/default address
    belongs to another region.
- apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx
  - Carry regionId on the edit view-model/initialValues and include it in the
    set-default updateAddress payload.
- apps/user-ui/components/PaymentAndOrderComponent.tsx
  - Read selectedRegionId from regionStore, block submit without a region, and
    pass `regionId` to user.order.placeOrder; surface backend errors safely.
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx
  - Render `regionName` badge on each order (list stays account-wide).
- apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx
  - Show order region label in the detail header.
- apps/user-ui/components/FirstUserWrapper.tsx
  - Wrap children in RegionGate so a user with no saved region is prompted.
- apps/user-ui/app/(drawer)/(tabs)/me/index.tsx
  - Add a "Delivery Region" entry that opens RegionSelector in switch mode.

[2026-10-07 10:54:56] Phase 1 follow-up — backend region wiring + migrations 0006/0007.

packages/db_helper_sqlite/src/db/schema.ts
  - region_id added (nullable, app-enforced) to product_info, staff_users,
    store_info, vendor_snippets, product_tag_info, product_group_info,
    delivery_slot_info, coupons, home_banners, addresses, orders.
  - ordersRelations gains region relation.
packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql (new)
  - ALTER TABLE add nullable region_id + backfill all rows to Mahabubnagar + indexes.
packages/db_helper_sqlite/drizzle/meta/_journal.json
  - journal entry idx 7 -> 0007_region_columns_backfill.
packages/db_helper_sqlite/src/admin-apis/staff-user.ts
  - createStaffUserWithRegion(); getAllStaff now returns regionId.
packages/db_helper_sqlite/src/user-apis/address.ts
  - createUserAddress/updateUserAddress accept and persist regionId; mapUserAddress returns regionId.
packages/db_helper_sqlite/src/user-apis/order.ts
  - OrderWithRelations gains regionId/region; order reads include region relation.
packages/shared/types/user.ts
  - UserAddress.regionId; UserOrderSummary.regionId/regionName.

apps/backend/src/trpc/apis/superadmin-apis/apis/staff.ts (new)
  - superadmin.staff.list/roles/create (region required).
apps/backend/src/trpc/apis/admin-apis/apis/region.ts (new)
  - admin.region.current/bounds/effective/getBoundSettings/updateBoundSettings (staff region scoped).
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
  - common.listRegions + common.regionSettings (public).
apps/backend/src/trpc/apis/user-apis/apis/address.ts
  - createAddress/updateAddress require regionId.
apps/backend/src/trpc/apis/user-apis/apis/order.ts
  - placeOrder requires regionId; address/region mismatch rejected; order stores region; history returns regionName.
apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts
  - staff login returns staff.regionId.
apps/backend/src/sqliteImporter.ts
  - re-export createStaffUserWithRegion and region helpers.

apps/admin-ui, apps/user-ui: region-aware screens per the two UI workstreams
  (bound tabs + staff region; region store/selector/switch + address region + history labels).

Typecheck: db_helper_sqlite, backend and superadmin-ui all pass (tsc --noEmit). No migrations run, no tests run, no git.

[2026-10-07 11:12:00] Phase 1 addendum — 0007 now rebuilds the region FK subgraph with region_id NOT NULL.

packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql
  - After the nullable ADD COLUMN + backfill, rebuild every table in the region_id
    FK subgraph (31 tables incl. product_skus, order_items, orders, staff_notif_creds,
    coupon_* etc.) per docs/recreate-referenced-tables.md: create __new parent-first,
    copy all columns, drop leaves-first, rename parents-first, recreate indexes.
  - region_id is now NOT NULL (FK to regions) in the rebuilt tables.
  - CHECK on product_reviews written unqualified.

Schema note: Drizzle schema keeps region_id nullable to avoid breaking existing
insert call sites; the DB is stricter. Remaining admin create paths (product, store,
banner, coupon, tag, group, slot) must be updated to supply the staff region.

[2026-10-07 11:24:00] Wire regionId into all region-owned create paths (region is required, no defaults).

DB helpers (packages/db_helper_sqlite/src):
  - admin-apis/product.ts: createProduct(input, regionId), createProductTag(input, regionId),
    createProductGroup(..., regionId) now write region_id.
  - admin-apis/store.ts: createStore(input, products, regionId).
  - admin-apis/banner.ts: createBanner(input, regionId).
  - admin-apis/vendor-snippets.ts: createVendorSnippet({..., regionId}).
  - admin-apis/slots.ts: createSlotWithRelations(input, regionId); snippet inserts inherit region.
  - admin-apis/coupon.ts: createCouponWithRelations(..., regionId),
    createReservedCouponWithProducts(..., regionId), generateCancellationCoupon(..., regionId),
    createCouponForUser(..., regionId).
  - admin-apis/staff-user.ts: createStaffUser(..., regionId).
  - user-apis/coupon.ts: redeemReservedCoupon copies reservedCoupon.regionId into the coupon.
  - schema.ts + 0007: reserved_coupons is now region-owned too (ALTER + backfill + rebuild NOT NULL + index).
  - Removed all `?? 1` fallbacks; regionId is mandatory and must be supplied by the caller.

Routers (apps/backend/src/trpc/apis/admin-apis/apis):
  - product.ts / store.ts / banner.ts / vendor-snippets.ts create procedures now use staffProcedure
    and pass ctx.staffUser.regionId.
  - slots.ts / coupon.ts / staff-user.ts pass ctx.staffUser.regionId (and order.regionId for
    cancellation coupons).

Typecheck: db_helper_sqlite and backend pass.

[2026-10-07 11:27:35] Fix 0007 migration failure (FOREIGN KEY constraint failed).

Root cause (proven on a copy of the local D1 DB, statement-by-statement):
  - The drop/rebuild ordering was correct; the real problem is legacy DATA written
    before FK enforcement that violates the FKs the rebuilt tables declare:
      * 5 orders.address_id values no longer exist in addresses.
      * 11 payments rows whose order no longer exists (ALL payment rows are orphans).
    The __new_orders copy (statement #75) and later __new_payments copy (#83) fail
    on these live orphan rows.
  - Additionally the first partial run had already committed phase 1 (ALTERs +
    backfill + 19 __new_ copies), so re-running the file as-is would fail on duplicate columns.

Planned diff for packages/db_helper_sqlite/drizzle/0007_region_columns_backfill.sql:
  - Remove the ALTER-ADD-COLUMN + backfill phase entirely. region_id is added by the
    rebuild itself, computed at DB level in each copy SELECT
    ((SELECT id FROM regions WHERE name='Mahabubnagar')). No app-level defaults.
  - Add a repair phase before the copy:
      * DELETE FROM payments WHERE order_id NOT IN (SELECT id FROM orders);
      * remove the 5 orphan orders AND their dependents: delete their
        payments/order_items/order_status/refunds, null out coupon_usage.order_id /
        coupon_usage.order_item_id / complaints.order_id / user_incidents.order_id.
  - Drop the pre-rebuild region indexes (created after rename only).
  - Journal entry unchanged (idx 7).
  - After migration: user resets local D1 state and re-runs 0006 + 0007;
    verify with PRAGMA foreign_key_check and row counts.

[2026-10-07 11:41:00] 0007 repair extended + proof harness run (read-only, on a COPY of the local DB).

  - Repair phase also deletes order_status and refunds of the 5 orphan orders
    (their copies would otherwise fail FK to __new_orders first).
  - Proof harness on a copy of the actual local D1 DB (freshyo-dev, FK enforcement ON,
    statement-by-statement like wrangler):
      * All statements pass; PRAGMA foreign_key_check = 0 violations; zero __new_ leftovers.
      * Row deltas exactly as intended: orders -5, order_items -19, order_status -5,
        payments -11 (all), refunds -2; every other table unchanged.
      * region_id NOT NULL enforced and FK rejection verified post-rename (writes rejected).
      * All 13 original unique indexes recreated (4 table-prefixed + 9 unique_*).
  - Important: wrangler runs the file in one transaction — the earlier failed run left
    NO partial state, so the fixed 0007 can simply be re-run (0006 already applied).

[2026-10-07 11:45:00] Superadmin staff-user CRUD (regions reassignment + removal).

  - admin-apis/staff-user.ts (db_helper_sqlite): add updateStaffUserRegion(staffId, regionId)
    and deleteStaffUser(staffId). Delete removes staff_notif_creds rows, clears nullable
    references (user_incidents.added_by), and refuses when the staff still owns a store
    or created coupons / reserved coupons (NOT NULL dependent FKs would break).
  - export both helpers from packages/db_helper_sqlite/index.ts and re-export them in
    apps/backend/src/sqliteImporter.ts.
  - superadmin-apis/apis/staff.ts: add superadmin.staff.update (reassign region) and
    superadmin.staff.remove (delete with blockedBy reason).
  - superadmin-ui: new routes/staff.tsx CRUD screen (list, add with role+region, region
    reassignment, delete w/ confirmation + blocked-reason display); AppShell nav entry
    "Admin Users"; routeTree.gen.ts registers /staff.

[2026-10-07 11:41:17] Enable Maestro MCP server in project opencode.jsonc.

  - Ran: opencode mcp add maestro -- maestro mcp
    (registers local stdio MCP server "maestro" running `maestro mcp`,
    Maestro 2.11.0 built-in MCP server, project-local config).

[2026-10-07 12:03:54] Phase 4 (admin-web) — per-bound regional settings port from admin-ui.

Planned diffs:

apps/admin-web/src/components/context/staff-auth-context.tsx
  - Extend session `Staff` shape with optional `regionId: number | null`
    (login already returns it); expose `regionId` on the auth context value.
  - Non-breaking: existing consumers of `staff` keep working.

apps/admin-web/src/routes/dashboard.customize-app.tsx
  - Replace the single global constants form with one tab per region bound
    (admin.region.bounds, ascending priority). Each tab shows the bound
    description (or "Bound #id") + priority and marks the lowest-priority
    bound as "Effective" (its settings apply to checkout).
  - Selected bound loads admin.region.getBoundSettings and renders the 11
    regional keys as editable inputs (ConstantInput gains an
    `allowSectionNavigation` prop so popularItems/allItemsOrder become inline
    comma-separated inputs instead of links to the global editors).
  - Save via admin.region.updateBoundSettings with only changed keys
    (string|null values). Default-select lowest-priority bound; reinitialize
    the form (Formik enableReinitialize + key) so drafts do not leak between
    tabs. Loading / error / "no bounds configured" states.
  - Keep the existing global constants form reachable via a top-level
    "Regional Settings" / "Global Constants" switch (admin.const.* unchanged).
  - Show the current region name (admin.region.current) in the header.
  - No staff-account creation UI exists in admin-web (createStaffUser/
    getRoles unused); nothing to remove.

[2026-10-07 $(date +%H:%M:%S)] Phase 4 (web-ui) — port browsing-region features from user-ui (Expo) to web-ui (TanStack Start).

New files:
- apps/web-ui/src/lib/stores/region-store.ts (new)
  - zustand `persist` store over an SSR-safe localStorage wrapper (web equivalent
    of Expo's StorageServiceCasual). Same shape as user-ui regionStore:
    selectedRegionId / selectedRegion / regionGeneration + setRegion / clearRegion.
    Persist key `freshyo-region`, version 1.
- apps/web-ui/src/lib/region-switch.ts (new)
  - Centralized `confirmRegionSwitch(region, queryClient)`: clears regular+flash
    local carts (localStorage + react-query cart keys), resets quick-delivery
    selected slot, address selection, slot store ids, cart-store added product,
    flash-cart product, flash-navigation flag, clears central product/slot
    snapshots, persists the new region, then invalidates all react-query caches.
    Callers must confirm with the user before invoking.
- apps/web-ui/src/components/RegionSelector.tsx (new)
  - Lists trpc.common.listRegions. mode='gate' full-screen first-run chooser
    (direct select, no cart exists yet); mode='switch' dialog content with an
    inline "entire cart will be cleared" confirmation before confirmRegionSwitch.
- apps/web-ui/src/components/RegionGate.tsx (new)
  - Hydration-aware gate: waits for persisted region, validates saved region
    against common.listRegions (clears stale ids), renders children until
    hydrated (SSR-safe, avoids hydration mismatch) then a blocking overlay with
    RegionSelector until a region exists.

Modified files:
- apps/web-ui/src/routes/__root.tsx
  - Wrap app children in RegionGate (inside trpc/Auth providers).
- apps/web-ui/src/components/AddressForm.tsx
  - Required region <select> from common.listRegions; new addresses default to
    the browsing region, edits keep the stored region; regionId in
    create/update payloads + Yup required rule.
- apps/web-ui/src/hooks/checkout-hooks.ts (useCheckoutAddress)
  - Default auto-select only for current-region addresses; expose cross-region
    helper data (addresses carry regionId).
- apps/web-ui/src/components/CheckoutAddressSelector.tsx
  - Cross-region tap -> confirm (entire cart cleared) -> confirmRegionSwitch ->
    navigate home; same-region selection preserves cart.
- apps/web-ui/src/routes/home.checkout.tsx + flash.checkout.tsx
  - Same cross-region address handling; placeOrder payloads gain regionId;
    backend mismatch errors surfaced.
- apps/web-ui/src/components/PaymentAndOrderComponent.tsx
  - Reads selectedRegionId, blocks submit without a region, passes regionId to
    placeOrder, surfaces backend mismatch message.
- apps/web-ui/src/routes/me.orders.tsx + me.orders.$id.tsx
  - Account-wide history (no region filter) with regionName labels.
- apps/web-ui/src/routes/me.addresses.tsx
  - Address view-model carries regionId; edit initialValues keep stored region;
    set-default payload includes regionId (blocked with a message when missing).
- apps/web-ui/src/routes/me.tsx
  - "Delivery Region" menu entry opening RegionSelector in switch mode.
- Query keys: same as Expo (version-keyed global catalog caches, no region in
  keys); region switch clears central stores + invalidates all queries so no
  stale cross-region snapshots survive.

Typecheck: `npx tsc --noEmit --project apps/web-ui/tsconfig.json` from repo root.

[2026-10-07 12:14:52] Browser verification fix — allow localhost:4176 in backend CORS.

apps/backend/src/app.ts
  - CORS origin list gains 'http://localhost:4176' (admin-web auto-bumps to 4176
    when superadmin-ui already holds 4175; without this the browser blocks API calls).

[2026-10-07 12:18:39] Browser verification (Playwright MCP): web-ui region gate + admin-web bound tabs.
  - web-ui :4174 region gate renders with Mahabubnagar; selection dismisses gate.
  - admin-web :4176 staff login (uitest/test1234, regionId 1) works; customize-app shows
    Region: Mahabubnagar, Mbnr-1 P1 EFFECTIVE / Mbnr-2 P2 tabs, all 11 settings loaded.
  - E2E save verified twice in D1 (deliveryCharge 20->25, minRegularOrderValue 300->350
    on bound 1 only; bound 2 untouched), then restored to seeded values via SQL.
  - test staff row 'uitest' left in local D1 for reuse (region 1, role admin).
  - Note: backend CORS already included :4176. One benign console error (numberOfLines prop).

[2026-10-07 12:20:40] Isolation test fixtures in LOCAL dev D1 only (not app code).
  - Region 2 'Testnagar' + 1 bound (priority 1, square GeoJSON) + 11 settings rows
    (deliveryCharge 30 / minRegularOrderValue 500 to distinguish from Mahabubnagar).
  - Staff 'uitest2' (region 2, role admin, password test1234) for cross-region API tests.
  - All fixture rows are test-only and removable.

[2026-10-07 12:24:46] Region-scope CATALOG admin read paths (staff sees own region only).

Planned diffs:

packages/db_helper_sqlite/src/admin-apis/product.ts
  - getAllProducts(regionId), getProductById(regionId, id),
    getAllProductTags(regionId), getAllProductTagInfos(regionId),
    getProductTagInfoById(regionId, tagId), getProductTagById(regionId, tagId),
    getProductReviews(regionId, productId, limit, offset),
    getAllProductGroups(regionId): regionId as FIRST param; list endpoints add
    eq(<table>.regionId, regionId); single-ID reads use and(id, regionId) and
    return null outside the region; reviews scoped via product_info.region_id
    join (reviews + count). checkProductExistsByName /
    checkProductTagExistsByName stay GLOBAL. Writes, price/stock mutations,
    respondToReview untouched.

packages/db_helper_sqlite/src/admin-apis/store.ts
  - getAllStores(regionId), getStoreById(regionId, id); add `and` import.

packages/db_helper_sqlite/src/admin-apis/banner.ts
  - getBanners(regionId), getBannerById(regionId, id); add `and` import.

apps/backend/src/trpc/apis/admin-apis/apis/product.ts, store.ts, banner.ts
  - Read procedures keep protectedProcedure (no auth restructure) and pass
    ctx.staffUser!.regionId, including read-before-write existence checks in
    updateStore / updateProductTag / deleteProductTag.

apps/backend/src/stores/banner-store.ts
  - getBannerById wrapper threads regionId through (dead code, no callers;
    updated only for typecheck).

apps/backend/src/stores/product-tag-store.ts
  - getTagsByStoreId resolves the store's own regionId via storeInfo and
    scopes getAllProductTags to it; user-apis callers untouched (stay working).

Typecheck: tsc --noEmit for packages/db_helper_sqlite + apps/backend.

[2026-10-07 12:24:34] Region-scope OPERATIONAL admin read paths (slots, snippets, coupons, orders, users, complaints).

Planned diffs (regionId added as FIRST param of each read helper; lists filter by
region; single-ID reads constrain by region and return null outside it; writes,
check*Exists validators, superadmin/user/region/const paths untouched):

packages/db_helper_sqlite/src/admin-apis/slots.ts
  - getActiveSlotsWithProducts(regionId, limit): where isActive + region_id.
  - getSlotsAfterDate(regionId|null, afterDate): region filter when non-null
    (null = global, used only by the public vendor getUpcomingSlots link).
  - getSlotByIdWithRelations(regionId, id): and(id, region_id), null outside.
  - getSlotDeliverySequence(regionId, slotId): and(id, region_id), null outside.

packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts (add `and` import)
  - getVendorSnippetById(regionId, id): and(id, region_id).
  - getVendorSnippetByCode(regionId|null, code): region-verified when non-null
    (null = global public vendor order-list links).
  - getAllVendorSnippets(regionId): where region_id.
  - getProductsByIds(regionId|null, skuIds): empty->[]; when region set, keep only
    SKUs whose parent product is in-region (columns gain product.regionId).
  - getVendorSlotById(regionId|null, slotId): region-verified when non-null.
  - getVendorOrdersBySlotId(regionId|null, slotId): and(slot, region) when non-null.

packages/db_helper_sqlite/src/admin-apis/coupon.ts (add `sql`/`SQL` imports)
  - getAllCoupons(regionId, cursor, limit, search): push region condition.
  - getCouponById(regionId, id): and(id, region_id).
  - getReservedCoupons(regionId, cursor, limit, search): push region condition.
  - getOrderWithUser(regionId, orderId): and(id, region_id).
  - getUsersForCoupon(regionId, search, limit, offset): EXISTS in-region order filter
    (users scoped via orders.region_id, not addresses).

packages/db_helper_sqlite/src/admin-apis/order.ts (import deliverySlotInfo)
  - getOrderDetails(regionId, orderId): and(id, region_id).
  - getSlotOrders(regionId, slotId): verify slot in-region first (else empty list);
    then and(slot, region) on orders.
  - getAllOrders(regionId, input): seed whereCondition with region equality.

packages/db_helper_sqlite/src/admin-apis/user.ts (add `and`/`or`/`isNull` imports)
  - getUnresolvedComplaintsCount(regionId): unresolved AND (orderless OR order in-region).
  - getAllUsersWithFilters(regionId, limit, cursor, search): EXISTS in-region order.
  - getOrderCountsByUserIds / getLastOrdersByUserIds(regionId, userIds): AND region.
  - getSuspensionStatusesByUserIds(regionId, userIds): param added for uniformity;
    no filter (user_details has no region; callers pass in-region users only).
  - getUserBasicInfo(regionId, userId): null unless >=1 in-region order.
  - getUserOrders(regionId, userId): and(user, region).
  - getOrderStatusesByOrderIds / getItemCountsByOrderIds(regionId, orderIds):
    prefetch in-region order ids, query only those.
  - searchUsers(regionId, search): EXISTS in-region order (both branches).
  - getUserIncidentsWithRelations(regionId, userId): keep orderless or in-region-order
    incidents (JS filter on joined order.regionId).

packages/db_helper_sqlite/src/admin-apis/complaint.ts (add `and`/`or`/`isNull`, orders import)
  - getComplaintById(regionId, id): null when order-backed and order out-of-region/missing.
  - getComplaints(regionId, cursor, limit): left-join orders, keep orderless OR
    in-region-order complaints (+ cursor).

apps/backend/src/trpc/apis/admin-apis/apis/{slots,vendor-snippets,coupon,order,user,complaint}.ts
  - Thread ctx.staffUser.regionId (staffProcedure where imported, else
    protectedProcedure + ctx.staffUser!.regionId) into every scoped helper call.
  - Public vendor endpoints (getOrdersBySnippet, getOrdersBySnippetAndSlot,
    getUpcomingSlots) pass null = deliberately global vendor links (no staff region).
  - slots.getDeliverySequence gains the missing staff guard (needed for region).
  - complaint.resolve's pre-check becomes region-scoped (write helper untouched).
  - payments.ts: stub, no order reads -> no change.
  - Writes (updates/deletes/invalidates/suspends), check*Exists validators, notif-cred
    reads, and non-admin callers unchanged by design; residual cross-region write
    paths noted in final report, not altered.

Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.

[2026-10-07 12:31:10] Region-scope admin UPDATE/DELETE-by-ID paths + cross-region relationship validation on creates.

Planned diffs (regionId as FIRST param on helpers; single-ID mutations constrain with
and(id, regionId) and return null/false outside the region; creates validate related
IDs resolve to in-region rows and throw Error('... belongs to a different region')):

packages/db_helper_sqlite/src/admin-apis/product.ts
  - deleteProduct(regionId, id), updateProduct(regionId, id, input: region-scoped
    pre-read + update where; cross-region combo skuIds + storeId rejected.
  - createProduct: storeId must resolve to an in-region store; combo-item skuIds
    must resolve via parent product_info.region_id (validation BEFORE the
    generic try/catch so the message surfaces).
  - createProductTag: relatedStores must be in-region stores.
  - replaceTagProducts(regionId, tagId, productIds): tag must be in-region; skuIds
    must be in-region (via parent product).
  - updateProductTag(regionId, tagId, input) -> null outside region; validates
    relatedStores in-region. deleteProductTag(regionId, tagId) -> boolean.
  - createProductGroup/updateProductGroup: productIds (SKU ids) validated in-region.
  - updateProductGroup(regionId, ...), deleteProductGroup(regionId, ...) scoped.
  - updateProductPrices(regionId, updates): out-of-region SKUs reported as invalidIds.
  - toggleProductOutOfStock(regionId, productId): null outside region.
  - respondToReview(regionId, reviewId, ...): null when the review's product is
    out-of-region. check*Exists validators stay global.

packages/db_helper_sqlite/src/admin-apis/store.ts
  - updateStore(regionId, id, input, products?), deleteStore(regionId, id) scoped
    (delete/update throw 'Store not found' when outside region, as before).
  - createStore/updateStore: owner staff must be in-region; product SKU ids must
    resolve to in-region products.

packages/db_helper_sqlite/src/admin-apis/banner.ts
  - updateBanner(regionId, id, input) -> Banner|null; deleteBanner(regionId, id)
    -> boolean. createBanner/updateBanner: skuIds validated in-region.

packages/db_helper_sqlite/src/admin-apis/slots.ts
  - updateSlotWithRelations(regionId, input), updateSlotCapacity(regionId, ...),
    updateSlotDeliverySequence(regionId, ...) scoped (null outside region).
  - createSlotWithRelations/updateSlotWithRelations: skuIds + snippet skuIds +
    groupIds validated in-region. staleSlotsCleanup left global (maintenance).

packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts
  - updateVendorSnippet(regionId, id, updates) -> null outside region; new slotId +
    skuIds validated in-region. deleteVendorSnippet(regionId, id) scoped.
  - createVendorSnippet: slotId + skuIds validated in-region.
  - updateVendorOrderItemPackaging left global (public vendor link, no staff ctx).

packages/db_helper_sqlite/src/admin-apis/coupon.ts
  - updateCouponWithRelations(regionId, id, ...) -> null outside region; new
    applicableProducts validated in-region. invalidateCoupon(regionId, id) ->
    Coupon|null. createCouponWithRelations/createReservedCouponWithProducts:
    applicableProducts validated in-region. generateCancellationCoupon verifies
    the order's region matches. createCouponForUser unchanged (note).

packages/db_helper_sqlite/src/admin-apis/order.ts
  - updateOrderNotes/updateOrderPackaged/updateOrderDelivered/removeDeliveryCharge/
    cancelOrder/deleteOrderById(regionId, ...) scoped (null/false/order_not_found
    outside region). updateOrderItemPackaging(regionId, ...) resolves the parent
    order's region first. updateAddressCoords(regionId, ...) constrains
    addresses.regionId. rebalanceSlots(regionId, slotIds) only touches in-region
    slots/orders. deleteOrdersWithRelations left global (note: caller is the
    global lib/delete-orders cleanup path).

packages/db_helper_sqlite/src/admin-apis/user.ts — untouched (upsertUserSuspension
account-global, createUserIncident no region needed — noted only).
packages/db_helper_sqlite/src/admin-apis/complaint.ts — resolveComplaint(regionId,
id, response) -> boolean, constrained via the getComplaintById region pattern.

apps/backend/src/trpc/apis/admin-apis/apis/{product,store,banner,slots,
vendor-snippets,coupon,order,complaint}.ts — thread ctx.staffUser.regionId
(staffProcedure where imported, else protectedProcedure + ctx.staffUser!.regionId)
into every changed helper; map null/false to NOT_FOUND (no cross-region leak);
create-validation Errors surface as-is.

Typecheck: npx tsc --noEmit --project packages/db_helper_sqlite/tsconfig.json AND
apps/backend/tsconfig.json; fix introduced errors. No tests, no git, no migrations.

[2026-10-07 12:52:57] Region isolation testing — two-region (Mahabubnagar + Testnagar) verification.
  API (26/26 checks pass):
  - Creates in both regions via admin API: stores, tags, products, slots, coupons, banners.
  - Lists isolated: staff1 sees R1-only tags, staff2 sees R2-only tags.
  - Cross-region reads 404 without leaking (tag by id both ways; order details both ways).
  - Cross-region updates rejected (store update, slot capacity); own-region update works.
  - Cross-region create validation: R1 product with R2 store rejected.
  - Address saves regionId; mismatched checkout (region 1 order + region 2 address) rejected.
  - Region-2 order placed end-to-end (id 2454, regionId 2); staff1 list/detail exclude it,
    staff2 list/detail include it; user history carries regionName labels.
  - Duplicate (region_id, priority) rejected by unique index (proven at DB level).
  Browser (Playwright MCP):
  - web-ui gate lists both regions; switch Testnagar->Mahabubnagar with seeded cart:
    confirm dialog clears cart 1->0; cancel preserves cart + region.
  - admin-web customize bound tabs + E2E save verified earlier.
  - staff2 bounds endpoint returns Test-1 only; staff1 returns Mbnr-1/2 only.
  Left in LOCAL dev D1 (test-only, removable): region Testnagar + bound + settings,
  staff uitest/uitest2, ISO stores/tags/products/slots/coupons/banners, test address 875,
  order 2454. Temp scripts removed from repo.
  NOT covered: superadmin Regions/Staff UI pages (need superadmin password);
  storefront browsing still serves the global cache (per-region cache files pending).

[2026-10-07 13:05:00] Region-aware storefront catalog (user-ui + web-ui) against the FIXED backend contract.

Planned diffs (frontend only; backend untouched — another agent implements the contract):

apps/user-ui/src/hooks/prominent-api-hooks.ts
  - useGetEssentialConsts reads selectedRegionId from regionStore and calls
    trpc.common.essentialConsts with { regionId } (cast for forward-compat;
    current backend ignores the extra input at runtime). Enabled only when a
    region is selected; persisted discovery key becomes per-region
    (essential_consts_r<regionId>) so regions never share snapshots.
  - Regional URL builders from discovery data (effectiveSettings.regionId with
    selectedRegionId fallback):
      products/stores/per-store files:
        {assetsDomain}{apiCacheKey}/regions/{regionId}/v-{cacheVersion}/{file}
      availability:
        {assetsDomain}regions/{regionId}/av-{availabilityVersion}/availability.json
      slots:
        {assetsDomain}regions/{regionId}/slots/v-{slotsVersion}/slots.json
    Null regionId -> null URL -> catalog queries stay disabled (gate covers
    the no-region case).
  - New useRegionalConsts(): discovery data with the 5 delivery/minimum fields
    (deliveryCharge, freeDeliveryThreshold, flashDeliveryCharge,
    flashFreeDeliveryThreshold, minRegularOrderValue) overridden from
    effectiveSettings.settings (numeric parse, global fallback). Display-only;
    backend stays authoritative for the actual charge.

apps/user-ui/src/lib/region-switch.ts
  - confirmRegionSwitch additionally drops old-region react-query catalog
    snapshots (removeQueries on all-products/stores/slots/availability/
    store-with-products) before setRegion + invalidateQueries refetches
    discovery and catalog for the new region. Central stores cleared as before.
    Cancel path unchanged.

apps/user-ui/components/{cart-page,checkout-page,floating-cart-bar}.tsx
  - Delivery-charge/threshold messaging reads useRegionalConsts() (regional
    effective settings first, global fallback).

apps/web-ui/src/hooks/prominent-api-hooks.ts
  - Mirror of the user-ui hook changes above (localStorage persisted catalog
    caches stay version-gated; the versioned URL now contains the region so no
    cross-region placeholder can match). Banners go through the regional URL.
apps/web-ui/src/lib/region-switch.ts
  - Mirror of the user-ui switch extension.
apps/web-ui/src/components/{PaymentAndOrderComponent,FloatingCartBar}.tsx
  - Delivery-charge/threshold display prefers effectiveSettings via
    useRegionalConsts(); submit logic (regionId payload) untouched.

Admin apps: grep apps/admin-ui + apps/admin-web for essentialConsts/cache-file
consumers — report only, no edits.

Typecheck: npx tsc --noEmit --project apps/user-ui/tsconfig.json AND
apps/web-ui/tsconfig.json. No tests, no git, no migrations.

[2026-10-07 13:06:59] Per-region storefront cache phase — backend + clients implemented, pending 0008.
  Backend: region_cache_versions table + 0008 migration (NOT run); all *ForCache
  helpers + scaffolds region-first; KV essential_consts:{regionId}; regional paths
  regions/{id}/...; createRegionCacheFiles/createAllCacheFiles(regionId?);
  essentialConsts now REQUIRES {regionId}; CacheCreator DO drains per-region queue.
  Clients (user-ui + web-ui): discovery passes browsing regionId; regional URL builders;
  switch refetches discovery+catalog; checkout display uses effectiveSettings.
  Verified: all 4 typechecks pass; new code live on :8787 (regionId required; versions
  query fails until 0008 applied — expected).
  NEXT: user runs 0008 on dev D1, then per-region generation is triggered and verified.

[2026-10-07 13:13:31] Per-region storefront verified end-to-end.
  - 0008 applied by user; per-region generation triggered (store updates) — all
    counters 1->2 in both regions; regional files live on CDN.
  - File partition proven: r1 products.json 150 rows incl ISOProdR1, tags ISOTagR1 only;
    r2 1 row (ISOProdR2), tags ISOTagR2 only; zero cross-leaks either way.
  - Browser (web-ui): Testnagar storefront shows ISOTagR2+ISOProdR2, no R1 leaks;
    Mahabubnagar shows ISOTagR1, no R2 leaks. (ISOProdR1 below render window;
    present in-file; its tag mapping empty by fixture design.)
  - Cross-region tag mapping rejected: 'Product 152 belongs to a different region'.

[2026-10-07 13:39:44] Closed loop: region-1 product verified rendered in UI.
  - web-ui search 'ISOProdR1' while browsing Mahabubnagar: 1 result (ISOProdR1,
    Rs 100, 500g), no ISOProdR2. Screenshot verified then removed.
  - Earlier home-page absence explained: new SKU shows Out of Stock (no
    availability/stock row), so it never surfaces in the purchasable list.
    Not a region issue.

[2026-10-07 13:45:12] user-ui location bar on all top-level tabs.
  - src/components/LocationBar.tsx (new): pin + region name row; tap opens
    BottomDialog with RegionSelector mode=switch (lazily mounted; sheet handles
    its own cart-clear confirmation). Rendered inside scroll content so it
    scrolls out instead of sticking.
  - Insert at top of scroll content: home listHeader, order-again ScrollView,
    FlashDeliveryProducts ListHeader, stores ListHeader, me ScrollView.

[2026-10-07 13:49:26] home: LocationBar vertically first — moved static SearchBar into
  the FlatList header below LocationBar so both scroll out together.

[2026-10-07T14:07:48+05:30] Home: scroll location away and stick the second (search) section header.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
+++ apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
@@ -1,5 +1,5 @@
 import React, { useState, useCallback, useMemo, memo, useRef, useEffect } from "react";
-import { View, Dimensions, Image, RefreshControl } from "react-native";
+import { View, Dimensions, Image, RefreshControl, SectionList } from "react-native";
 import { ScrollView } from "react-native-gesture-handler";
 import { useRouter } from "expo-router";
 import {
@@ -653,8 +653,6 @@
   ], [pageTint]);
 
   const listHeader = useMemo(() => (
-    <>
-      <LocationBar />
     <ListHeader
       dashboardTags={dashboardTags}
       activeTagId={activeTagId}
@@ -666,7 +664,6 @@
       storesData={storesData}
       sortedSlots={sortedSlots}
     />
-    </>
   ), [dashboardTags, activeTagId, productsByTagId, expandedByTagId, handleToggleExpand, handleProductPress, storesData, sortedSlots]);
 
   const listContentContainerStyle = useMemo(() => [
@@ -698,34 +695,52 @@
   return (
     <TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
       <View style={pageTintStyle}>
-        <View
-          style={searchBarContainerStyle}
-        >
-          <SearchBar
-            testID="home-search"
-            value={""}
-            onChangeText={() => { }}
-            onPress={handleSearchPress}
-            editable={false}
-            containerStyle={tw`bg-white`}
-            onSubmitEditing={() => {
-              if (inputQuery.trim()) {
-                router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
-              }
-            }}
-            returnKeyType="search"
-          />
-        </View>
-
-        <MyFlatList
-          data={displayedProducts.slice(0, visibleCount)}
-          keyExtractor={(item) => item.id.toString()}
-          numColumns={3}
+        <SectionList
+          sections={[{ data: [[], ...Array.from(
+            { length: Math.ceil(Math.min(displayedProducts.length, visibleCount) / 3) },
+            (_, index) => displayedProducts.slice(index * 3, Math.min(index * 3 + 3, visibleCount))
+          )] }]}
+          keyExtractor={(row, index) => row.length ? row.map((item) => item.id).join('-') : 'catalog-header'}
+          stickySectionHeadersEnabled
           style={{ backgroundColor: '#FFFFFF' }}
           contentContainerStyle={listContentContainerStyle}
-          columnWrapperStyle={staticStyles.columnWrapper}
-          renderItem={renderProductItem}
-          ListHeaderComponent={listHeader}
+          ListHeaderComponent={<LocationBar />}
+          renderSectionHeader={() => (
+            <View style={searchBarContainerStyle}>
+              <SearchBar
+                testID="home-search"
+                value={""}
+                onChangeText={() => { }}
+                onPress={handleSearchPress}
+                editable={false}
+                containerStyle={tw`bg-white`}
+                onSubmitEditing={() => {
+                  if (inputQuery.trim()) {
+                    router.push(`/(drawer)/(tabs)/home/search-results?q=${encodeURIComponent(inputQuery.trim())}`);
+                  }
+                }}
+                returnKeyType="search"
+              />
+            </View>
+          )}
+          renderItem={({ item: row, index }) => index === 0 ? (
+            <>
+              {listHeader}
+              {displayedProducts.length === 0 && (
+                <View style={tw`items-center py-8`}>
+                  <MyText style={tw`text-gray-500`}>No products available</MyText>
+                </View>
+              )}
+            </>
+          ) : (
+            <View style={[staticStyles.columnWrapper, { flexDirection: 'row' }]}>
+              {row.map((item) => (
+                <React.Fragment key={item.id}>
+                  {renderProductItem({ item })}
+                </React.Fragment>
+              ))}
+            </View>
+          )}
           ListFooterComponent={
             hasMore ? (
               <View style={tw`items-center py-4`}>
@@ -748,11 +763,6 @@
               colors={[theme.colors.brand500]}
             />
           }
-          ListEmptyComponent={
-            <View style={tw`items-center py-8`}>
-              <MyText style={tw`text-gray-500`}>No products available</MyText>
-            </View>
-          }
           // NOTE: do not add removeClippedSubviews here - it breaks touch
           // delivery to the nested horizontal scrollables in ListHeaderComponent
           // (tag tabs / slots) on Android.

[2026-10-07 14:13:37] user-ui: single region source-of-truth hook.
  - NEW src/hooks/useRegion.ts: useRegion() returns { region, regionId,
    regionGeneration, hydrated, setRegion, clearRegion }. Wraps useRegionStore;
    owns the persist-hydration subscription so consumers no longer touch the store.
  - Routed all region/location reads through useRegion: LocationBar, RegionGate,
    RegionSelector (dropped selectedRegionId prop, reads hook), AddressForm,
    QuickDeliveryAddressSelector, PaymentAndOrderComponent, CheckoutAddressSelector,
    me/index.tsx, prominent-api-hooks (useGetEssentialConsts, useDiscoveryRegionId).
  - region-switch.ts keeps useRegionStore.getState() (non-hook lib, cannot call hooks).

[2026-10-07 14:26:08] location-based region resolution (backend + user-ui).
  Backend:
   - shared: add RegionBoundSummary + ResolvedRegion types (region.types.ts).
   - db_helper_sqlite: add getAllRegionsWithBounds() (regions ordered by id,
     each region's bounds ordered by ascending numeric priority); export it.
   - common tRPC: add public resolveRegionByLocation({lat,lng}) -> { region,
     bound } | null. Iterates every region, and within each region checks bounds
     least-priority-first; first containing bound wins. GeoJSON features
     (Polygon/MultiPolygon) converted with @turf.
  user-ui:
   - NEW src/store/locationStore.ts: zustand singleton that owns expo-location
     permission + watchPosition fixes (coords/status/error), start/stop/refresh.
   - src/hooks/useRegion.ts: now the location-aware single source of truth. While
     no region is chosen it starts tracking + calls resolveRegionByLocation and
     auto-sets the region; exposes coords/status/bound/isResolvingRegion. Stops
     tracking once a region exists.
   - RegionGate: shows spinner while resolving; only falls back to the chooser
     when location is unavailable/denied/no match.

[2026-10-07 15:02:02] user-ui: LocationTestWrapper owns the region chooser fallback.
  - NEW src/lib/is-emulator.ts: extracted emulator/simulator detection.
  - store/locationStore.ts: skip requesting location on emulators (status
    'unavailable'); check Location.hasServicesEnabledAsync(); race the first fix
    against a timeout so a missing GPS fix can no longer hang 'locating'.
  - LocationTestWrapper: rewritten as the region gate. Renders app once a region
    exists; spinner while deriving it from location; full-screen RegionSelector
    when location services are off, permission denied, on a simulator, or no
    bound contains the coordinates. Keeps the stale-region validation.
  - Moved LocationTestWrapper up (FirstUserWrapper) so the gate sits above
    Auth/Notification providers; removed it from app/_layout.tsx.
  - Removed src/components/RegionGate.tsx (superseded by LocationTestWrapper).

[2026-10-07 15:20:00] fix: region spinner stuck / infinite re-render.
  - regionStore: setRegion/clearRegion are now no-ops when nothing changes,
    so they no longer bump regionGeneration (and re-render) on every call.
  - useRegion: add resolvedAttempt flag -> isResolvingRegion flips false after
    the first definitive answer and never latches back on 'idle'; stop location
    tracking once settled; memoize/round the resolve query input; 8s resolve
    timeout fallback.
  - locationStore: round coords to ~1m and skip store updates when unchanged,
    so GPS jitter no longer churns a new query key every watch callback.
  - LocationTestWrapper: validation is membership-only (no setRegion in the
    effect), removing a possible self-triggering loop.

[2026-10-07 15:24:00] RegionSelector is controlled again (selectedRegionId prop) so
  the chooser no longer calls useRegion / starts location tracking; callers
  (LocationTestWrapper, LocationBar, me) pass the id from their useRegion.

[2026-10-07 15:42:21] regions cannot be created without bounds.
  - shared: add RegionBoundSeedInput + CreateRegionWithBoundsInput.
  - db_helper_sqlite: add createRegionWithBounds() (region + bounds inserted
    atomically in one transaction); export it.
  - superadmin regions.create: now requires bounds (min 1, valid GeoJSON +
    numeric priority) and returns { region, bounds }; duplicate priority -> 409.
  - superadmin-ui Regions page: create form now collects at least one bound
    (description/priority/GeoJSON supports multiple rows); legacy empty create
    removed.

[2026-10-07 15:58:00] admin-ui logout debug logging added temporarily.
  - (drawer)/_layout.tsx: log on drawer Logout item tap.
  - staff-auth-context.tsx: log on logout() entry and after deleteJWT resolves.

[2026-10-07 16:03:00] admin-ui logout: removed the temporary debug console.logs
  (drawer Logout handler and staff-auth-context logout()).

[2026-10-07 16:40:00] admin pickers leak cross-region data: fixed.
  - Root cause: three admin-only pickers used public, unscoped common endpoints.
  - common.getStoresSummary: public PROCEDURE aggregating ALL regions -> now
    protectedProcedure returning only the caller staff region's stores.
  - common.product.getAllProductsSummary: aggregated ALL regions -> now
    protectedProcedure returning scaffolledProducts(ctx.staffUser.regionId) only.
  - common.product.getAllSkusSummary: returned ALL SKUs -> protectedProcedure +
    new regionId arg on getAllSkusSummary (default null keeps old signature).
  - Affects admin-ui AND admin-web (both attach the staff JWT). The customer apps
    never call these (they use regional CDN cache files), so no public surface lost.

[2026-10-07 17:10:00] fix: essentialConsts returned region-1 values for region 3.
  Root cause: backend scaffold sent per-region settings as `regionSettings`
  but user-ui/web-ui read `effectiveSettings` -> override never applied, so the
  global (region-1-authored) top-level consts showed for every region.
  - backend scaffoldEssentialConsts now returns `effectiveSettings` (canonical)
    plus `regionSettings` alias for KV-cached payloads.
  - user-ui + web-ui read effectiveSettings ?? regionSettings, so even stale KV
    entries resolve correctly without waiting for a KV refresh.
  - After deploy, refresh KV (any const update / cache regen / seed calls
    refreshGenKv) so new payloads carry the canonical field.

[2026-10-07 17:25:00] fix: bound mutations now refresh KV.
  - updateBoundSettings wrote D1 only; KV mirror kept stale values.
    Now looks up the bound's region and awaits refreshGenKv(regionId).
  - Same staleness class fixed for createBound and updateBound (a new/changed
    bound can become the effective lowest-priority one).

[2026-10-07 17:40:00] fix: essentialConsts top-level fields now carry effective regional values.
  - scaffoldEssentialConsts resolved each business field as bound setting ??
    global const ?? default (numbers parsed, booleans coerced, raw passthrough
    otherwise), instead of storing globals flat next to the nested block.
  - Also exposes minRegularOrderValue/allItemsOrder/welcomeMessage top-level
    (previously nested-only). Helper return types stay `any` so the client
    contract is unchanged; only values changed.
  - Nested effectiveSettings (+regionSettings alias) retained for provenance
    and the client override path. Requires KV refresh post-deploy (any const
    save / cache regen / seed) to rewrite stored payloads.

[2026-10-07 17:55:00] essentialConsts payload is now flat: removed the nested
  effectiveSettings/regionSettings block. Top-level fields are the region's
  effective values (bound setting ?? global), so there is nothing nested left
  to re-appear. Clients keep reading the optional nested block only as a
  backward-compat fallback for payloads already cached in KV.

[2026-10-08 00:10:10] Part 1/2 - split consts model into three tables (global_consts / region_consts / region_bound_consts) + per-bound flat JSON in KV.

Planned diffs (backend + db_helper + admin-ui + admin-web + superadmin-ui; NO migration run; NO tests; NO git):

packages/db_helper_sqlite/src/db/schema.ts
  - Add globalConsts(key PK, value), regionConsts(region_id,key PK), regionBoundConsts(bound_id,key PK) tables.
  - Remove regionCacheVersions + regionBoundSettings tables and relations.
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (new, NOT run) + meta/_journal.json idx 9.
  - CREATE 3 tables; copy global / region (versions + region-level keys incl allItemsOrder from effective bound) / bound rows;
    DELETE migrated keys from key_val_store (keep leftovers); DROP region_bound_settings + region_cache_versions.
packages/db_helper_sqlite/src/lib/const-keys.ts
  - Add GLOBAL_CONST_KEYS / REGION_CONST_KEYS / BOUND_CONST_KEYS / LEGACY_CONST_KEYS; rename cacheVersion -> products_version_num; keep merged CONST_KEYS.
packages/db_helper_sqlite/src/admin-apis/const.ts
  - Add getAllGlobalConsts/upsertGlobalConsts, getRegionConsts/upsertRegionConsts, getBoundConsts/upsertBoundConsts, getLegacyConsts/upsertLegacyConsts;
    getAllConstants/upsertConstants route by scope. Remove dead global version counters.
packages/db_helper_sqlite/src/lib/region-cache-versions.ts
  - Back get/incrementRegion* with region_consts rows (products_version_num / availability_version_num / slots_version_num).
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
  - getBoundSettings/upsertBoundSettings -> region_bound_consts; add getRegionConstants/upsertRegionConstants;
    getEffectiveRegionSettings merged region+bound; add getEffectiveBoundId; getAllRegions + effectiveBoundId; seed defaults on create.
packages/db_helper_sqlite/src/db/seed.ts + seed.sql, index.ts exports.
packages/shared/types/region.types.ts - RegionSummary.effectiveBoundId.
apps/backend/src/lib/const-keys.ts, lib/const-store.ts, lib/gen-store.ts (essentialConsts_{boundId}),
  trpc/apis/common-apis/common-trpc-index.ts (scaffoldEssentialConsts(boundId), essentialConsts {boundId}, listRegions effectiveBoundId, regionSettings merged),
  lib/cloud_cache.ts, lib/flash-delivery-cron.ts, lib/seed.ts, sqliteImporter.ts,
  trpc/apis/admin-apis/apis/const.ts (global/legacy procedures + compat alias), admin-apis/apis/region.ts (region + bound constants),
  superadmin-apis/apis/regions.ts, new superadmin-apis/apis/const.ts router.
apps/admin-ui + apps/admin-web: customize-app 3 tabs (Global/Region/Bound); popular-items/all-items-order region-scoped; tagsOrder via legacy.
apps/superadmin-ui: constants.tsx -> superadmin.const.*; regions.tsx region + bound editors.
Typecheck: db_helper_sqlite, backend, admin-ui, superadmin-ui, admin-web.

[2026-10-08 00:29:40] Part 1/2 follow-up — finish the admin UIs (admin-ui, admin-web, superadmin-ui) + move tagsOrder into region_consts.

Backend/db (tagsOrder is now region-scoped, per user decision; overrides the plan which kept it legacy):
packages/db_helper_sqlite/src/lib/const-keys.ts
  - CONST_KEYS/LABELS/TYPES/VISIBILITY/DEFAULTS: add tagsOrder (string, hidden, default '[]').
  - REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
apps/backend/src/lib/const-keys.ts
  - REGION_CONST_KEYS: add 'tagsOrder'; LEGACY_CONST_KEYS: remove 'tagsOrder'.
packages/db_helper_sqlite/drizzle/0009_three_const_tables.sql (NOT run)
  - Copy tagsOrder from key_val_store into region_consts per region; delete it from key_val_store.
packages/db_helper_sqlite/src/db/seed.ts
  - Remove tagsOrder from legacy seed list (region_defaults now seeds it).
apps/backend/src/lib/seed.ts
  - Remove tagsOrder from legacy seed list.
apps/backend/src/trpc/apis/admin-apis/apis/region.ts
  - updateRegionConstants: trigger scheduleStoreInitialization when tagsOrder changes; ignore version-counter keys.
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
  - updateRegionConstants: ignore version-counter keys (read-only).
apps/backend/src/trpc/apis/common-apis/common.ts
  - scaffoldProducts: read tagsOrder from region_consts (region-scoped) instead of the global key_val_store.

Admin UIs (3 tabs Global/Region/Bound; Global holds legacy keys, globals hidden; Region hides version counters; Bound = 5 keys):
apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
  - Replace 2-way switch with 3 tabs; global uses admin.const.getGlobalConstants/getLegacyConstants, region uses admin.region.getRegionConstants/updateRegionConstants, bound keeps per-bound Formik; hide tab if no visible keys.
apps/admin-ui/app/(drawer)/dashboard/customize-app/popular-items.tsx
apps/admin-ui/app/(drawer)/dashboard/customize-app/all-items-order.tsx
  - Read/write popularItems/allItemsOrder via admin.region.getRegionConstants/updateRegionConstants.
apps/admin-ui/app/(drawer)/dashboard/product-tags/order.tsx
  - Read/write tagsOrder via admin.region.getRegionConstants/updateRegionConstants.
apps/admin-ui/components/OrderOptionsMenu.tsx
  - welcomeMessage read via admin.region.getRegionConstants.
apps/admin-web/src/routes/dashboard.customize-app.tsx
  - 3 tabs as above.
apps/admin-web/src/routes/dashboard.customize-app.popular.tsx
apps/admin-web/src/routes/dashboard.customize-app.ordering.tsx
  - Region-scoped popularItems/allItemsOrder.
apps/admin-web/src/routes/dashboard.product-tags.order.tsx
  - Region-scoped tagsOrder.
apps/superadmin-ui/src/routes/constants.tsx
  - Use superadmin.const.getGlobalConstants/updateGlobalConstants + getLegacyConstants/updateLegacyConstants; drop region/bound keys.
apps/superadmin-ui/src/routes/regions.tsx
  - Split into RegionConstantsEditor (superadmin.regions.getRegionConstants/updateRegionConstants, version counters hidden) and BoundSettingsEditor (5 bound keys).

web-ui and user-ui untouched. No migrations run. No tests run.

[2026-10-08 00:41:00] Part 1/2 follow-up completed. Backend/db_helper/admin-ui/admin-web/superadmin-ui typecheck clean (tsc --noEmit). Migration 0009 NOT run (user runs it). web-ui + user-ui untouched.
  Notes/decisions:
  - Global tab in admin-ui/admin-web shows the legacy leftovers (platformFeePercent,
    minOrderAmountForCoupon, flashDeliverySlotId); the 4 global keys stay hidden there and are
    managed in superadmin-ui. Tab is hidden entirely if it would render no visible keys.
  - Region tab hides the 3 version counters; tagsOrder is edited on the Tag Orders screen
    (admin apps) and in the superadmin Region settings editor (no dedicated tags screen there).
  - List screens send comma-joined ids to the region endpoint (input is a strict scalar union).
  - Stale: apps/admin-ui/tests/** still mock admin.const.getConstants/updateConstants (tests not run).

[2026-10-08 00:44:05] Part 2/2 — apps/user-ui consumes the per-bound flat JSON.

apps/user-ui/src/store/regionStore.ts
  - Add selectedBoundId (persisted); setRegion(region, boundId?) compares+stores it; clearRegion resets it.
apps/user-ui/src/hooks/useRegion.ts
  - Expose boundId from the store; on resolve persist setRegion(resolved.region, resolved.bound.id); setRegion signature gains boundId.
apps/user-ui/src/lib/region-switch.ts
  - confirmRegionSwitch(region, queryClient, boundId?) forwards boundId to setRegion.
apps/user-ui/src/components/RegionSelector.tsx
apps/user-ui/components/CheckoutAddressSelector.tsx
apps/user-ui/components/QuickDeliveryAddressSelector.tsx
  - Pass region.effectiveBoundId to confirmRegionSwitch.
apps/user-ui/src/hooks/prominent-api-hooks.ts
  - useGetEssentialConsts reads boundId from useRegion, queries { boundId }, persists under essential_consts_b{boundId}.
  - useDiscoveryRegionId reads flat data.regionId (fallback useRegion().regionId).
  - Cache URLs use products_version_num / availability_version_num / slots_version_num.
  - useRegionalConsts is a thin passthrough of the flat payload.
  - Drop DiscoveryData extension + discoverySettings + EffectiveRegionSettings import.
No tests run. web-ui untouched.

[2026-10-08 00:49:00] Part 2/2 completed. apps/user-ui typechecks clean; backend/db/admin apps still clean.
  Deviations/notes:
  - confirmRegionSwitch(region, queryClient, boundId?) defaults boundId to region.effectiveBoundId,
    so the address-selector call sites needed no change; RegionSelector passes it explicitly.
  - useRegion derives boundId = stored ?? region.effectiveBoundId ?? null and backfills a missing
    bound via common.listRegions (covers region state persisted before selectedBoundId existed).
  - useRegionalConsts keeps a loose (any) return so cart/checkout/floating-cart need no edits.

[2026-10-08 00:57:00] Globals are superadmin-only: removed the Global tab from the admin apps.
  apps/admin-ui/.../customize-app/index.tsx and apps/admin-web/.../dashboard.customize-app.tsx
  - Drop the Global tab, renderGlobal, global/legacy queries+mutations, GLOBAL_KEYS/LEGACY_KEYS,
    CONST_VISIBILITY; tab switcher is now Region | Bound only. tsc clean.
  - Global + legacy constants remain editable in apps/superadmin-ui/src/routes/constants.tsx.
  Backend note: staff `admin.const.*` (compat getConstants/updateConstants + the new
  getGlobalConstants/updateGlobalConstants/getLegacyConstants/updateLegacyConstants) still exist and
  are pinned by apps/backend/tests; not changed (no production UI caller remains).

[2026-10-08 01:12:47] Added packages/db_helper_sqlite/drizzle/merged_regions.sql — one squashed migration replacing 0006_regions_and_superadmins + 0007_region_columns_backfill + 0008_region_cache_versions + 0009_three_const_tables.
  - Drops the two throwaway staging tables (region_bound_settings, region_cache_versions) that the originals created only to copy from and then drop; global_consts / region_consts / region_bound_consts are seeded directly instead.
  - Phase order preserved: (1) regions/region_bounds/superadmins + seeds (from 0006), (2) 0007 region_id rebuild verbatim, (3) const tables + direct seeds (from 0008+0009).
  - Verification: rebuilt SQLite from apps/backend/dumps/latest.sql; applied 0006..0009 -> expected; applied merged_regions.sql -> merged. Python comparison: schema objects 86/86, tables 55/55, rows 21795/21795, IDENTICAL apart from CURRENT_TIMESTAMP seeds (regions.created_at, superadmins.created_at). Also validated D1-style splitting on the statement-breakpoint marker: 187 chunks, 0 failures, integrity ok, same-result. No migrations run against any real DB. No tests run.
  - Follow-up (exact-data check): re-ran 0006..0009 vs merged_regions.sql back-to-back in the same second and compared every row of the 6 new tables + 31 rebuilt tables + key_val_store with no masking -> EXACTLY IDENTICAL (rows: regions 1, region_bounds 2, superadmins 1, global_consts 3, region_consts 10, region_bound_consts 10; all 31 rebuilt tables match row-for-row, e.g. delivery_slot_info 1569, orders 2283, order_items 7959, order_status 2277, reserved_coupons 739; key_val_store 7 leftovers).
  - Squash applied: removed migrations 0006/0007/0008/0009 and replaced them with one file.
    * Backed up the pre-removal contents of 0006_regions_and_superadmins.sql,
      0007_region_columns_backfill.sql, 0008_region_cache_versions.sql and
      0009_three_const_tables.sql into
      packages/db_helper_sqlite/drizzle/stale/removed_region_migrations.txt
      (single txt, one section per file, verbatim).
    * Deleted those four .sql files.
    * Renamed packages/db_helper_sqlite/drizzle/merged_regions.sql ->
      packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (same
      verified squashed content; staging tables removed).
    * drizzle/meta/_journal.json still lists tags 0007_region_columns_backfill,
      0008_region_cache_versions and 0009_three_const_tables; left untouched
      (user handles migrations) but needs those entries removed to stay consistent.
    * docs/consts-three-tables-part1-backend-admin.md still references
      `0009_three_const_tables`; left as-is.
    No migrations run. No tests run.

[2026-10-08 19:28:11] user-ui: startup-only location check (no movement tracking).
apps/user-ui/src/store/locationStore.ts
  - Remove watchPositionAsync subscription (movement tracking) and coordsEqual; keep a single
    getCurrentPositionAsync (8s timeout). start() idempotent via a per-launch `started` flag.
apps/user-ui/src/hooks/useRegion.ts
  - Run the location check once on hydration EVEN when a region is saved; never stop/start on regionId.
  - Apply outcome once per launch: same region -> no-op; different -> confirmRegionSwitch(resolved.region,
    queryClient, resolved.bound.id) (clears carts, invalidates region queries); null/denied/unavailable
    -> keep saved region. Single-flight switch guard (module flag) + manual-pick race guard.
  - Rename resolvedAttempt -> startupResolved; isResolvingRegion only for the true first run.
No backend changes. No tests run.

[2026-10-08 19:34:00] startup-only location check implemented. user-ui typecheck clean.
  - locationStore: single getCurrentPositionAsync per launch, no watchPositionAsync.
  - useRegion: check runs on every launch (saved region included); same -> no-op,
    different -> confirmRegionSwitch (option a: clears carts, refreshes screens);
    unusable/null -> keep saved region (or chooser when none). Single-flight switch + manual-pick race guard.
