import React, { useEffect, useRef, useState } from 'react'; import { View } from 'react-native'; import dayjs from 'dayjs'; import { useQueryClient } from '@tanstack/react-query'; import { MyText, MyTouchableOpacity, BottomDialog, LoadingDialog, tw } from 'common-ui'; import { trpc } from '../src/trpc-client'; import { useAuth } from '../src/contexts/AuthContext'; import { useRegion } from '../src/contexts/RegionContext'; import { useAddressStore } from '../src/store/addressStore'; import { useRegionSwitchContext, fetchRegionSlotMap, snapshotCartContext, reconcileCartLines, CART_TYPES, type RegionSwitchLineResult, } from '../src/hooks/useRegionSwitch'; import { getLocalCart, saveLocalCart, saveCartSnapshot, setRegionSwitchInProgress, type LocalCartItem, } from '../hooks/cart-query-hooks'; const BIG_SHIFT_MS = 60 * 60 * 1000; interface PreviewLine extends RegionSwitchLineResult { bigShift: boolean; } interface AddressPreview { currentId: number; prevId: number | null; targetId: number; targetName: string; lines: PreviewLine[]; linesByType: Record; } const isBigShift = (line: RegionSwitchLineResult): boolean => { if (line.outcome !== 'moved') return false; if (line.oldSlotTime == null || line.newSlotTime == null) return true; return Math.abs(dayjs(line.newSlotTime).valueOf() - dayjs(line.oldSlotTime).valueOf()) > BIG_SHIFT_MS; }; const AddressRegionWatcher: React.FC = () => { const { isAuthenticated } = useAuth(); const { regionId: activeRegionId, setRegion } = useRegion(); const { selectedAddressId, setSelectedAddressId } = useAddressStore(); const { presentResults } = useRegionSwitchContext(); const utils = trpc.useUtils(); const queryClient = useQueryClient(); const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { enabled: isAuthenticated, }); const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity }); const [preview, setPreview] = useState(null); const [building, setBuilding] = useState(false); const prevRef = useRef<{ id: number; regionId: number } | null>(null); const dismissedRef = useRef(null); const seqRef = useRef(0); useEffect(() => { if (!isAuthenticated) return; const list = addressesData?.data ?? []; const current = list.find((a) => a.id === selectedAddressId) ?? null; if (!current || current.regionId == null) { if (selectedAddressId == null) prevRef.current = null; return; } const prev = prevRef.current; if (prev && prev.id === current.id) { // Same selection: only an external region switch could have misaligned // us. The explicit region choice wins — re-anchor silently, no dialog. prevRef.current = { id: current.id, regionId: current.regionId }; return; } // Fully converged already (e.g. a dismissed no-op state)? const dismissKey = `${current.id}|${current.regionId}|${activeRegionId}`; if (dismissedRef.current === dismissKey) { prevRef.current = { id: current.id, regionId: current.regionId }; return; } // Aligned with the active region: anchor silently. if (current.regionId === activeRegionId) { prevRef.current = { id: current.id, regionId: current.regionId }; return; } const seq = ++seqRef.current; const prevId = prev?.id ?? null; const targetName = regionsData?.regions?.find((r) => r.id === current.regionId)?.name ?? 'the new region'; // Snapshot outgoing carts, then move the active region (bound unknown here, // so the server resolves the region default). No cart edits, no dialog. const convergeRegion = async (targetRegionId: number, targetRegionName: string) => { setRegionSwitchInProgress(true); try { if (activeRegionId != null) { for (const cartType of CART_TYPES) { await saveCartSnapshot(activeRegionId, await getLocalCart(cartType), cartType); } } if (targetRegionId !== activeRegionId) { await setRegion(targetRegionId, targetRegionName); } } finally { setRegionSwitchInProgress(false); } }; void (async () => { try { const carts = await Promise.all(CART_TYPES.map((t) => getLocalCart(t))); if (seq !== seqRef.current) return; const { names, oldSlotTimes } = snapshotCartContext(); if (carts.every((c) => c.length === 0)) { // Nothing to reconcile: snapshot + converge silently. prevRef.current = { id: current.id, regionId: current.regionId }; await convergeRegion(current.regionId, targetName); return; } setBuilding(true); const fetched = await fetchRegionSlotMap(utils, current.regionId); if (seq !== seqRef.current) return; const lines: PreviewLine[] = []; const linesByType: Record = {}; CART_TYPES.forEach((cartType, i) => { const reconciled = reconcileCartLines(carts[i], fetched.slotMap, oldSlotTimes, names); linesByType[cartType] = reconciled.lines; for (const r of reconciled.results) { const full: RegionSwitchLineResult = { ...r, cartType }; lines.push({ ...full, bigShift: isBigShift(full) }); } }); if (seq !== seqRef.current) return; if (lines.every((l) => l.outcome === 'kept')) { // Slots carry over (prices follow via region-scoped reads): // snapshot + converge silently, no dialog. prevRef.current = { id: current.id, regionId: current.regionId }; await convergeRegion(current.regionId, targetName); return; } setPreview({ currentId: current.id, prevId, targetId: current.regionId, targetName, lines, linesByType, }); } catch (error) { console.error('Address region preview failed:', error); } finally { if (seq === seqRef.current) setBuilding(false); } })(); }, [selectedAddressId, activeRegionId, addressesData, isAuthenticated, regionsData, utils]); const handleConfirm = async () => { const p = preview; if (!p) return; setPreview(null); prevRef.current = { id: p.currentId, regionId: p.targetId }; setRegionSwitchInProgress(true); try { if (activeRegionId != null) { for (const cartType of CART_TYPES) { await saveCartSnapshot(activeRegionId, await getLocalCart(cartType), cartType); } } for (const cartType of CART_TYPES) { await saveLocalCart(p.linesByType[cartType] ?? [], cartType); } queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] }); queryClient.invalidateQueries({ queryKey: ['local-cart-flash'] }); if (p.targetId !== activeRegionId) { await setRegion(p.targetId, p.targetName); } presentResults({ regionName: p.targetName, lines: p.lines.map(({ bigShift: _dropped, ...rest }) => rest), error: null, }); } catch (error) { presentResults({ regionName: p.targetName, lines: [], error: error instanceof Error ? error.message : 'Failed to update cart', }); } finally { setRegionSwitchInProgress(false); } }; const handleCancel = () => { const p = preview; setPreview(null); seqRef.current += 1; if (!p) return; if (p.prevId == null) { // No previous selection to revert to: remember the dismissal so the // effect doesn't re-prompt for this address/region combination. dismissedRef.current = `${p.currentId}|${p.targetId}|${activeRegionId}`; prevRef.current = { id: p.currentId, regionId: p.targetId }; return; } // Reverting re-triggers the watcher effect, which anchors prevRef // silently since the regions now match. setSelectedAddressId(p.prevId); }; return ( <> Deliver to {preview?.targetName}? This address is in a different region. Your cart will change as follows: {preview?.lines.map((line, index) => ( {line.bigShift && line.outcome === 'moved' ? '⚠️ ' : ''}{line.name} × {line.quantity} {line.outcome === 'moved' && ( Slot moved: {line.oldSlotTime ? dayjs(line.oldSlotTime).format('ddd h:mm A') : 'previous slot'} → {line.newSlotTime ? dayjs(line.newSlotTime).format('ddd h:mm A') : ''} {line.bigShift ? ' (more than 1 hour)' : ''} )} {line.outcome === 'removed' && ( Removed{line.reason ? ` — ${line.reason}` : ''} )} ))} Back void handleConfirm()} > Confirm ); }; export default AddressRegionWatcher;