---
phase: 12-filled-document-preview
plan: 02
subsystem: ui
tags: [react, next.js, preview-gate, pdf-preview, field-placer, text-fill]

# Dependency graph
requires:
  - phase: 12-filled-document-preview
    plan: 01
    provides: POST /api/documents/[id]/preview route and PreviewModal component
provides:
  - Preview button in PreparePanel calling POST /api/documents/[id]/preview
  - Send button gated on previewToken (disabled until at least one preview generated)
  - Text fill changes reset previewToken to null (re-disables Send)
  - Field changes (drag/drop/delete/resize) reset previewToken via onFieldsChanged callback
  - DocumentPageClient.tsx: shared state bridge between PreparePanel and FieldPlacer
  - Body scroll lock and portal-based z-index fix in PreviewModal
  - Text fill values drawn at placed text field box coordinates in preview PDF
affects: [PreparePanel.tsx, FieldPlacer.tsx, PdfViewer.tsx, PdfViewerWrapper.tsx, page.tsx, PreviewModal.tsx, prepare-document.ts]

# Tech tracking
tech-stack:
  added: []
  patterns:
    - Lifted previewToken state to DocumentPageClient to bridge sibling server-component children
    - onFieldsChanged callback prop pattern: FieldPlacer -> PdfViewer -> PdfViewerWrapper -> DocumentPageClient -> PreparePanel
    - useCallback for handleFieldsChanged in DocumentPageClient prevents unnecessary FieldPlacer re-renders
    - ReactDOM.createPortal to document.body for modal z-index escape from sticky sidebar stacking context
    - useEffect scroll lock: capture original overflow on mount, restore on unmount
    - Text fill coordinates: sort placed text fields by page asc / y desc; draw at field.x+4, field.y+4; font capped 6-11pt

key-files:
  created:
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/DocumentPageClient.tsx
  modified:
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PreparePanel.tsx
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/FieldPlacer.tsx
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PdfViewer.tsx
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PdfViewerWrapper.tsx
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/page.tsx
    - teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PreviewModal.tsx
    - teressa-copeland-homes/src/lib/pdf/prepare-document.ts

key-decisions:
  - "previewToken state lifted to DocumentPageClient — PreparePanel and FieldPlacer are siblings in a server component and cannot share state directly"
  - "DocumentPageClient created as minimal client wrapper holding previewToken state and handleFieldsChanged callback"
  - "PdfViewer and PdfViewerWrapper updated to forward onFieldsChanged prop down to FieldPlacer — no new abstractions introduced"
  - "previewToken passed as prop to PreparePanel with onPreviewTokenChange setter — PreparePanel calls onPreviewTokenChange(null) to reset on text fill changes"
  - "PreviewModal uses ReactDOM.createPortal to document.body to escape sticky sidebar stacking context; z-index 9999"
  - "Text fill values drawn at placed field box coordinates (field.x+4, field.y+4) not just top-of-page — makes fills visible at expected positions"
  - "Text fill UX redesign (per-field click-to-edit, quick-fill suggestions) deferred to Phase 12.1 as known gap"

patterns-established:
  - "Client state bridge pattern: when siblings are rendered by a server component, create a DocumentPageClient to hold shared state"
  - "Callback forwarding chain: DocumentPageClient.handleFieldsChanged -> PdfViewerWrapper -> PdfViewer -> FieldPlacer.onFieldsChanged"
  - "Portal modal pattern: always render full-screen modals via createPortal to avoid stacking context issues with sticky sidebars"

requirements-completed: [PREV-01]

# Metrics
duration: ~25min (including bug fixes and human verification)
completed: 2026-03-21
---

# Phase 12 Plan 02: UI Wiring — Preview Gate and Send Button Summary

**PreparePanel Preview button gating Send on previewToken, DocumentPageClient bridging state to FieldPlacer, scroll-lock portal modal, and text fill values drawn at placed field coordinates — human-verified and approved**

## Performance

- **Duration:** ~25 min (tasks 1+2 ~4 min, bug fixes ~10 min, human verification)
- **Started:** 2026-03-21T21:33:00Z
- **Completed:** 2026-03-21T21:55:00Z
- **Tasks:** 2 auto tasks + 1 human-verify checkpoint (approved)
- **Files modified:** 6 modified, 1 created

## Accomplishments
- PreparePanel now has Preview button, previewToken state (lifted to DocumentPageClient), handlePreview fetch, and Send button gated on token — Send is disabled until at least one preview has been generated
- TextFillForm onChange wrapped to call onPreviewTokenChange(null) on every text fill change, re-disabling Send
- FieldPlacer.tsx updated with onFieldsChanged?: () => void prop — called after every persistFields() (drag, resize, delete)
- DocumentPageClient.tsx created as minimal state bridge holding previewToken and passing handleFieldsChanged to FieldPlacer chain
- PreviewModal fixed: body scroll lock via useEffect and portal-based rendering via createPortal to escape sticky sidebar z-index
- Text fill values now drawn at placed field box coordinates in the preview PDF (not only at top of page 1)
- Human verified and approved full Preview-gate-Send flow end-to-end

## Task Commits

Each task was committed atomically:

1. **Task 1: PreparePanel preview state, button, gating, modal, DocumentPageClient wiring** - `de195a3` (feat)
2. **Task 2: FieldPlacer onFieldsChanged callback prop** - `720d07f` (feat)
3. **Bug fix: body scroll lock and z-index portal fix** - `43f396b` (fix)
4. **Bug fix: text fill values drawn at field box coordinates** - `bce2a98` (fix)

## Files Created/Modified
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/DocumentPageClient.tsx` (created) — Client wrapper holding previewToken state; passes reset callback to PdfViewerWrapper and previewToken/setter to PreparePanel
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PreparePanel.tsx` (modified) — Added previewToken/onPreviewTokenChange props, handlePreview function, Preview button, gated Send button, PreviewModal render, handleTextFillChange wrapper
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/FieldPlacer.tsx` (modified) — Added onFieldsChanged?: () => void to props; called after all 4 persistFields invocations (drag, drop, resize, delete)
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PdfViewer.tsx` (modified) — Accepts and forwards onFieldsChanged prop to FieldPlacer
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PdfViewerWrapper.tsx` (modified) — Accepts and forwards onFieldsChanged prop to PdfViewer
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/page.tsx` (modified) — Replaced PreparePanel+PdfViewerWrapper with DocumentPageClient
- `teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PreviewModal.tsx` (modified) — Added useEffect scroll lock, ReactDOM.createPortal to document.body, z-index 9999
- `teressa-copeland-homes/src/lib/pdf/prepare-document.ts` (modified) — Text fill values drawn at placed field box coordinates; sorted by page/y; font size 6-11pt; fieldConsumedKeys tracks which entries were rendered at field positions vs. Strategy B top-of-page fallback

## Decisions Made
- previewToken state lifted to DocumentPageClient because PreparePanel and PdfViewerWrapper (which hosts FieldPlacer) are siblings in a Next.js server component and cannot share React state directly
- DocumentPageClient is the minimal client wrapper — it only holds previewToken state and the handleFieldsChanged callback; no additional business logic added
- PdfViewer and PdfViewerWrapper updated to thread onFieldsChanged prop through — existing composition pattern preserved
- PreviewModal uses createPortal to escape sticky sidebar stacking context — this is the correct fix for z-index issues caused by CSS stacking contexts, not just raising z-index values
- Text fill UX redesign (per-field click-to-edit, quick-fill suggestions panel) identified as a UX gap during human verification — deferred to Phase 12.1 rather than blocking Phase 12 sign-off

## Deviations from Plan

### Auto-fixed Issues

**1. [Rule 3 - Blocking] Created DocumentPageClient.tsx wrapper**
- **Found during:** Task 1
- **Issue:** PreparePanel and FieldPlacer are siblings in a server component; they cannot share React state or callbacks directly
- **Fix:** Created minimal DocumentPageClient.tsx holding previewToken state and handleFieldsChanged callback; updated PdfViewer and PdfViewerWrapper to thread onFieldsChanged prop; updated page.tsx to use DocumentPageClient — exactly as the plan's "only if necessary" note specified
- **Files modified:** DocumentPageClient.tsx (created), PdfViewer.tsx, PdfViewerWrapper.tsx, page.tsx
- **Commit:** de195a3

**2. [Rule 1 - Bug] PreviewModal scroll lock and z-index/portal fix**
- **Found during:** Human verification (Task 3)
- **Issue:** Background page was scrollable while modal was open; modal appeared behind sticky sidebar overlay boxes due to CSS stacking context
- **Fix:** Added useEffect that locks document.body.overflow on mount and restores on unmount; changed modal render to ReactDOM.createPortal targeting document.body with z-index 9999
- **Files modified:** PreviewModal.tsx
- **Commit:** 43f396b

**3. [Rule 1 - Bug] Text fill values drawn at placed field box coordinates**
- **Found during:** Human verification (Task 3)
- **Issue:** Text type fields previously drew nothing at their placed box positions; textFillData values were only stamped at top of page 1 via Strategy B, making fills invisible at the expected placed locations in preview
- **Fix:** Sorted placed text fields by page asc / y desc (reading order); assigned textFillData entries sequentially to field box positions; drew text at field.x+4, field.y+4 with font size capped 6-11pt; fieldConsumedKeys set prevents double-rendering in Strategy B fallback
- **Files modified:** prepare-document.ts
- **Commit:** bce2a98

---

**Total deviations:** 3 auto-fixed (1 blocking wiring requirement, 2 bugs)
**Impact on plan:** All auto-fixes necessary for correctness and user-visible functionality. No scope creep.

## Known Gap — Deferred to Phase 12.1

**Text fill UX redesign** was identified during human verification as a gap in user experience. The current flow presents text fill fields as a single generic form panel, making it difficult to understand which fill corresponds to which placed field on the document.

**Deferred work:**
- Per-field click-to-edit inline editing (click a placed text field box to focus its input)
- Quick-fill suggestions panel (property address, client name auto-populate)
- Visual linkage between TextFillForm rows and placed field boxes

**Decision:** This is a UX improvement, not a correctness blocker. The Preview-gate-Send flow works end-to-end. Phase 12.1 will close this gap.

## Issues Encountered
- PreviewModal background scroll and z-index issues emerged during human verification — both resolved via scroll lock + portal pattern before checkpoint approval

## User Setup Required
None — no external service configuration required.

## Next Phase Readiness
- PREV-01 requirement complete; Phase 12 is fully done
- Phase 13 (AI-assisted field placement or next planned phase) can proceed
- Phase 12.1 (text fill UX redesign) is a planned gap-closure phase
- STATE.md blocker note about Vercel serverless filesystem still applies — write-to-disk preview pattern requires confirmation of deployment target before production deploy

---
*Phase: 12-filled-document-preview*
*Completed: 2026-03-21*

## Self-Check: PASSED

- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PreparePanel.tsx
- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/FieldPlacer.tsx
- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/DocumentPageClient.tsx
- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PdfViewer.tsx
- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PdfViewerWrapper.tsx
- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/page.tsx
- FOUND: teressa-copeland-homes/src/app/portal/(protected)/documents/[docId]/_components/PreviewModal.tsx
- FOUND: teressa-copeland-homes/src/lib/pdf/prepare-document.ts
- FOUND commit: de195a3 (Task 1)
- FOUND commit: 720d07f (Task 2)
- FOUND commit: 43f396b (Bug fix: scroll lock + portal)
- FOUND commit: bce2a98 (Bug fix: text fill at field coordinates)
- TypeScript: zero errors (npx tsc --noEmit)
- Human verification: APPROVED
- PREV-01 requirement: COMPLETE
