# SOLUTION: Messages UI Scroll/Back Bugs

**Date:** Jan 30, 2026  
**Commits:** 4c42810, 5d0135c  
**Status:** ✅ DEPLOYED TO PRODUCTION

---

## Summary

Fixed two bugs in the Messages UI:

1. **Scroll triggers click** - Scrolling through message list would accidentally open conversations
2. **Back button navigation** - Browser back went to dashboard instead of message list

---

## Changes Made

### File 1: `admin/src/hooks/useLongPress.js`

**Problem:** The existing touchmove-based scroll detection failed when the scroll container consumed touch events during momentum scrolling.

**Solution:** Added position-based scroll detection as a failsafe:

```javascript
// Added new ref
const startRect = useRef(null);

// In start(): Save element position on touchstart
if (event.currentTarget) {
  startRect.current = event.currentTarget.getBoundingClientRect();
}

// In clear(): Check if position changed on touchend
if (startRect.current && event?.currentTarget) {
  const currentRect = event.currentTarget.getBoundingClientRect();
  const positionDelta = Math.abs(currentRect.top - startRect.current.top);
  if (positionDelta > 10) {
    cancelledByScroll.current = true;
  }
}
```

**Why this works:** Element position changes during scroll even when touchmove events aren't fired to the element. Checking on touchend catches scrolls that touchmove missed.

---

### File 2: `admin/src/pages/Messages.jsx`

**Problem 1:** URL and state were one-way synced (state→URL only). Browser back changed URL but state didn't update.

**Solution:** Added bidirectional sync with URL as source of truth:

```javascript
// Simplified: Load conversation on activeLeadId change only
useEffect(() => {
  if (activeLeadId) {
    loadConversation(activeLeadId);
  } else {
    setActiveConversation(null);
    setActiveTriage(null);
  }
}, [activeLeadId, loadConversation]);

// NEW: Sync URL → state for browser back/forward
useEffect(() => {
  const leadFromUrl = searchParams.get('lead') || null;
  if (leadFromUrl !== activeLeadId) {
    setActiveLeadId(leadFromUrl);
  }
}, [searchParams]); // Intentionally omit activeLeadId
```

**Problem 2:** `setSearchParams` replaces URL without adding history entry.

**Solution:** Changed all navigation to use `navigate()`:

```javascript
// Before
onClick={() => setActiveLeadId(conversation.lead.id)}

// After
onClick={() => navigate(`/inbox?lead=${conversation.lead.id}`)}
```

Updated locations:
- AITriageSection onSelectConversation
- EnhancedConversationCard onClick (categorized view)
- EnhancedConversationCard onClick (filtered view)
- ConversationView onBack
- MiniLeadPopup onMessage
- NewMessageModal onSelectLead
- handleQuickAction (reply, custom, template, smart_reply, default)

---

## Testing Checklist

### Fix 1 (Scroll Detection)
- [ ] Fast scroll through message list → lift finger → should NOT open conversation
- [ ] Slow scroll → lift finger → should NOT open conversation
- [ ] Quick tap on card → SHOULD open conversation
- [ ] Long-press → SHOULD show context menu
- [ ] Test on iPhone Safari
- [ ] Test on Android Chrome

### Fix 2 (Back Button)
- [ ] Click conversation → browser back → should show message list
- [ ] Click conversation → browser back → browser back again → should leave inbox
- [ ] Deep link `/inbox?lead=xxx` → back → goes to previous page (not message list)
- [ ] In-app back arrow → shows message list
- [ ] Browser forward button works correctly after back

---

## Rollback

If issues arise:
```bash
git revert 4c42810
```

---

## Deployment Verification (Jan 30, 2026)

**Railway Deployment:**
- Commits pushed to main: ✅ `4c42810`, `5d0135c`
- Auto-deploy triggered: ✅
- Health check: ✅ HTTP 200
- App uptime: 811s (recent restart confirms deploy)
- Status: `{"status":"healthy","database":"ok","openai":"configured"}`

**QA Notes:**
- These are **mobile UI fixes** - cannot fully verify via API/curl
- Fix 1 (scroll detection) requires iPhone Safari + Android Chrome testing
- Fix 2 (back button) requires mobile browser testing
- **Michael will need to test on his phone** to confirm both fixes work

**Verification Performed:**
- [x] Code reviewed and approved
- [x] Commits pushed to main
- [x] Railway deployment succeeded
- [x] Health endpoint returns 200
- [x] App is running and accessible
- [ ] Mobile scroll test (pending user verification)
- [ ] Mobile back button test (pending user verification)

---

## Related Documents

- Investigation: `docs/INVESTIGATION.md`
- Fix Plan: `docs/messages-scroll-fix-plan.md`
