๐Ÿ“ฆ EqualifyEverything / equalify-reflow

๐Ÿ“„ PipelineViewerPage.tsx ยท 992 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Panel, Group as PanelGroup, Separator as PanelResizeHandle } from 'react-resizable-panels';
import { cn } from '@/lib/utils';
import { buildMarkdownBundle, triggerBlobDownload } from '@/lib/bundleDownload';
import { Button } from '@/components/ui/button';
import { MarkdownViewer } from '@/components/viewer/MarkdownViewer';
import { StageTabs } from '@/components/pipeline-viewer/StageTabs';
import { PIPELINE_STAGES, REVIEW_STAGE } from '@/types/pipeline-viewer';
// import { ChangesSidebar } from '@/components/pipeline-viewer/ChangesSidebar';
import { ChangesModal } from '@/components/pipeline-viewer/ChangesModal';
import { StructureMetadataModal } from '@/components/pipeline-viewer/StructureMetadataModal';
import { WarningsBanner } from '@/components/pipeline-viewer/WarningsBanner';
import { KeyboardShortcuts, type FocusRegion } from '@/components/pipeline-viewer/KeyboardShortcuts';
import { ClassificationError } from '@/components/pipeline-viewer/ClassificationError';
import { FeedbackModal } from '@/components/pipeline-viewer/FeedbackModal';
import { PiiReviewPanel } from '@/components/pipeline-viewer/PiiReviewPanel';
import { usePipelineViewer } from '@/hooks/usePipelineViewer';
import { useFeedbackConfig } from '@/hooks/useFeedbackConfig';
import {
  Upload,
  Loader2,
  FileText,
  Image as ImageIcon,
  BarChart3,
  ChevronDown,
  ChevronUp,
  Copy,
  Check,
  DollarSign,
  Clock,
  Play,
  Pause,
  Maximize2,
  MessageSquarePlus,
} from 'lucide-react';

const FLAG_STYLES: Record<string, { bg: string; text: string; label: string }> = {
  academic: { bg: 'bg-indigo-50', text: 'text-indigo-700', label: 'Academic' },
  images: { bg: 'bg-emerald-50', text: 'text-emerald-700', label: 'Images' },
  tables: { bg: 'bg-sky-50', text: 'text-sky-700', label: 'Tables' },
  equations: { bg: 'bg-violet-50', text: 'text-violet-700', label: 'Equations' },
  scanned: { bg: 'bg-amber-50', text: 'text-amber-700', label: 'Scanned' },
};

const LAYOUT_STYLES: Record<string, { bg: string; text: string; label: string }> = {
  single_column: { bg: 'bg-slate-100', text: 'text-slate-700', label: 'Single Column' },
  double_column: { bg: 'bg-blue-100', text: 'text-blue-800', label: 'Double Column' },
  presentation: { bg: 'bg-rose-100', text: 'text-rose-700', label: 'Presentation' },
};

type PageAttrs = {
  layout: string;
  is_academic: boolean;
  has_images: boolean;
  has_tables: boolean;
  has_equations: boolean;
  is_scanned: boolean;
};

function CollapsibleSection({
  title,
  count,
  defaultOpen = true,
  children,
}: {
  title: string;
  count?: number;
  defaultOpen?: boolean;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border-b last:border-b-0">
      <button
        onClick={() => setOpen(!open)}
        className="w-full flex items-center justify-between px-4 py-2.5 hover:bg-gray-50 transition-colors"
      >
        <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
          {title}{count != null ? ` (${count})` : ''}
        </h4>
        {open ? (
          <ChevronUp className="w-3.5 h-3.5 text-muted-foreground" />
        ) : (
          <ChevronDown className="w-3.5 h-3.5 text-muted-foreground" />
        )}
      </button>
      {open && <div className="px-4 pb-3">{children}</div>}
    </div>
  );
}

function StructureMetadataPanel({ metadata, onExpand }: { metadata: Record<string, unknown>; onExpand?: () => void }) {
  const pageAttributes = (metadata.page_attributes ?? {}) as Record<string, PageAttrs>;
  const outline = (metadata.outline ?? []) as Array<{ level: number; text: string; page: number }>;
  const footnotes = (metadata.footnotes ?? []) as Array<{
    number: string;
    body_text: string;
    source_page: number;
  }>;
  const codeBlocks = (metadata.code_blocks ?? []) as Array<{
    language: string;
    first_line: string;
    page: number;
    reasoning: string;
  }>;

  const pages = Object.entries(pageAttributes);
  const totalPages = pages.length;

  // Compute document-level summary from page attributes
  const layouts = new Map<string, number>();
  const flagCounts: Record<string, number> = { academic: 0, images: 0, tables: 0, equations: 0, scanned: 0 };
  for (const [, attrs] of pages) {
    layouts.set(attrs.layout, (layouts.get(attrs.layout) ?? 0) + 1);
    if (attrs.is_academic) flagCounts.academic++;
    if (attrs.has_images) flagCounts.images++;
    if (attrs.has_tables) flagCounts.tables++;
    if (attrs.has_equations) flagCounts.equations++;
    if (attrs.is_scanned) flagCounts.scanned++;
  }

  const hasAnyData = totalPages > 0 || outline.length > 0 || footnotes.length > 0 || codeBlocks.length > 0;

  return (
    <div className="w-72 flex-shrink-0 border-l bg-white flex flex-col overflow-y-auto">
      <div className="px-4 py-3 border-b flex items-center justify-between">
        <h3 className="text-sm font-semibold text-gray-800">Structure Metadata</h3>
        {onExpand && (
          <button
            onClick={onExpand}
            className="p-1 rounded hover:bg-gray-100 transition-colors"
            title="Expand to full view"
          >
            <Maximize2 className="w-3.5 h-3.5 text-muted-foreground" />
          </button>
        )}
      </div>

      {/* Document summary */}
      {totalPages > 0 && (
        <div className="px-4 py-3 border-b bg-gray-50/50">
          <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
            Document Summary
          </h4>

          {/* Layout distribution */}
          <div className="flex flex-wrap gap-1.5 mb-2">
            {[...layouts.entries()].map(([layout, count]) => {
              const style = LAYOUT_STYLES[layout] ?? { bg: 'bg-gray-100', text: 'text-gray-700', label: layout };
              return (
                <span
                  key={layout}
                  className={cn('px-2 py-1 rounded-md text-[11px] font-medium', style.bg, style.text)}
                >
                  {style.label}
                  {count < totalPages && (
                    <span className="ml-1 opacity-60">{count}/{totalPages}</span>
                  )}
                </span>
              );
            })}
          </div>

          {/* Flag summary bar */}
          <div className="flex flex-wrap gap-1">
            {Object.entries(flagCounts)
              .filter(([, count]) => count > 0)
              .map(([flag, count]) => {
                const style = FLAG_STYLES[flag]!;
                return (
                  <span
                    key={flag}
                    className={cn('px-1.5 py-0.5 rounded text-[10px] font-medium', style.bg, style.text)}
                  >
                    {style.label} {count < totalPages ? `${count}p` : ''}
                  </span>
                );
              })}
          </div>
        </div>
      )}

      {/* Per-page attributes */}
      {totalPages > 0 && (
        <CollapsibleSection title="Page Attributes" count={totalPages} defaultOpen={totalPages <= 12}>
          <div className="space-y-1.5">
            {pages.map(([page, attrs]) => {
              const layoutStyle = LAYOUT_STYLES[attrs.layout] ?? { bg: 'bg-gray-100', text: 'text-gray-700', label: attrs.layout };
              const activeFlags = [
                attrs.is_academic && 'academic',
                attrs.has_images && 'images',
                attrs.has_tables && 'tables',
                attrs.has_equations && 'equations',
                attrs.is_scanned && 'scanned',
              ].filter(Boolean) as string[];

              return (
                <div key={page} className="flex items-start gap-1.5 text-xs">
                  <span className="px-1.5 py-0.5 rounded bg-gray-100 text-gray-600 font-mono font-medium shrink-0 w-6 text-center">
                    {page}
                  </span>
                  <div className="flex flex-wrap gap-1 min-w-0">
                    <span
                      className={cn('px-1.5 py-0.5 rounded font-medium text-[10px]', layoutStyle.bg, layoutStyle.text)}
                    >
                      {layoutStyle.label.toLowerCase().replace(' ', '-')}
                    </span>
                    {activeFlags.map((flag) => {
                      const style = FLAG_STYLES[flag]!;
                      return (
                        <span
                          key={flag}
                          className={cn('px-1.5 py-0.5 rounded font-medium text-[10px]', style.bg, style.text)}
                        >
                          {style.label.toLowerCase()}
                        </span>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </CollapsibleSection>
      )}

      {/* Outline */}
      {outline.length > 0 && (
        <CollapsibleSection title="Outline" count={outline.length} defaultOpen={outline.length <= 25}>
          <div className="space-y-0.5">
            {outline.map((entry, idx) => (
              <div
                key={idx}
                className="text-xs text-muted-foreground"
                style={{ paddingLeft: `${(entry.level - 1) * 12}px` }}
              >
                <span className="text-gray-400 mr-1">{'#'.repeat(entry.level)}</span>
                <span>{entry.text}</span>
                <span className="text-gray-300 ml-1">p{entry.page}</span>
              </div>
            ))}
          </div>
        </CollapsibleSection>
      )}

      {/* Code blocks */}
      {codeBlocks.length > 0 && (
        <CollapsibleSection title="Code Blocks" count={codeBlocks.length}>
          <div className="space-y-2">
            {codeBlocks.map((cb, idx) => (
              <div key={idx} className="text-xs">
                <div className="flex items-center gap-1.5 mb-0.5">
                  <span className="px-1.5 py-0.5 rounded bg-gray-800 text-gray-100 font-mono font-medium text-[10px]">
                    {cb.language}
                  </span>
                  <span className="text-gray-400">p{cb.page}</span>
                </div>
                <p className="text-muted-foreground line-clamp-1 pl-1 font-mono text-[10px]">{cb.first_line}</p>
              </div>
            ))}
          </div>
        </CollapsibleSection>
      )}

      {/* Footnotes */}
      {footnotes.length > 0 && (
        <CollapsibleSection title="Footnotes" count={footnotes.length}>
          <div className="space-y-2">
            {footnotes.map((fn, idx) => (
              <div key={idx} className="text-xs">
                <div className="flex items-center gap-1.5 mb-0.5">
                  <span className="px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 font-medium">
                    [{fn.number}]
                  </span>
                  <span className="text-gray-400">p{fn.source_page}</span>
                </div>
                <p className="text-muted-foreground line-clamp-3 pl-1">{fn.body_text}</p>
              </div>
            ))}
          </div>
        </CollapsibleSection>
      )}

      {!hasAnyData && (
        <div className="flex-1 flex items-center justify-center p-4">
          <p className="text-xs text-muted-foreground text-center">
            No structural metadata found.
          </p>
        </div>
      )}
    </div>
  );
}

export function PipelineViewerPage() {
  const {
    result,
    uploading,
    error,
    processing,
    currentStepName,
    statusMessage,
    processFile,
    reset,
    sessionId,
    piiFindings,
    awaitingPiiDecision,
    piiDenied,
    submitPiiDecision,
  } = usePipelineViewer();
  const feedbackEnabled = useFeedbackConfig();

  const [currentPage, setCurrentPage] = useState(1);
  const [activeStepIdx, setActiveStepIdx] = useState(0);
  const [copiedImage, setCopiedImage] = useState(false);
  const [dragOver, setDragOver] = useState(false);
  const [autoAdvance, setAutoAdvance] = useState(true);
  const [changesModalOpen, setChangesModalOpen] = useState(false);
  const [metadataModalOpen, setMetadataModalOpen] = useState(false);
  const [feedbackModalOpen, setFeedbackModalOpen] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const skipNavRef = useRef<HTMLElement>(null);
  const loadingStatusRef = useRef<HTMLDivElement>(null);

  const hasClassificationError = !!(
    result &&
    Object.keys(result.versions).length === 0 &&
    result.steps.some((s) => s.name === 'classification' && s.error)
  );

  // Coarse view state drives the skip-nav targets so screen reader users get
  // the right landing spot for whichever screen they're looking at.
  const viewState: 'idle' | 'uploading' | 'error' | 'result' = uploading
    ? 'uploading'
    : error || hasClassificationError
      ? 'error'
      : result
        ? 'result'
        : 'idle';

  // Single polite live region copy โ€” drives the aria-live announcement.
  const liveAnnouncement = useMemo(() => {
    if (error) return `Error: ${error}`;
    if (uploading && !processing) return 'Uploading document. Extracting content.';
    if (processing && currentStepName) return `Processing step: ${currentStepName}.`;
    if (processing) return 'Document received. Processing pipeline started.';
    if (result && Object.keys(result.versions).length > 0) return 'Processing complete.';
    return '';
  }, [uploading, processing, currentStepName, error, result]);

  // Move focus to the loading status region the moment the upload starts so
  // a blind user knows the stream is live and has a live-region neighbour.
  useEffect(() => {
    if (uploading && loadingStatusRef.current) {
      loadingStatusRef.current.focus();
    }
  }, [uploading]);

  // When processing starts, move focus off the (now-unmounted) loading region
  // and onto the active stage tab โ€” prefer the one the pipeline flagged as
  // currently processing, falling back to the first (Extraction) tab so the
  // user has a deterministic anchor before any step has streamed in.
  useEffect(() => {
    if (!processing) return;
    requestAnimationFrame(() => {
      const stagesRoot = document.getElementById('region-stages');
      if (!stagesRoot) return;
      const target =
        stagesRoot.querySelector<HTMLButtonElement>('button[aria-current="step"]') ??
        stagesRoot.querySelector<HTMLButtonElement>('button:not([disabled])') ??
        stagesRoot.querySelector<HTMLButtonElement>('button');
      target?.focus();
    });
  }, [processing]);

  // Auto-advance to newest step tab as steps stream in
  const stepsLength = result?.steps.length ?? 0;
  useEffect(() => {
    if (autoAdvance && stepsLength > 0) {
      setActiveStepIdx(stepsLength - 1);
    }
  }, [stepsLength, autoAdvance]);

  const totalPages = result?.total_pages ?? 0;
  const activeStep = result?.steps[activeStepIdx] ?? null;

  const isPiiStepActive = activeStep?.name === 'pii_scan';
  const piiPanelState: 'scanning' | 'awaiting' | 'approved' | 'denied' | 'clean' | 'error' | null =
    !isPiiStepActive
      ? null
      : awaitingPiiDecision
        ? 'awaiting'
        : piiDenied
          ? 'denied'
          : activeStep?.error
            ? 'error'
            : (piiFindings && piiFindings.length > 0)
              ? 'approved'
              : piiFindings
                ? 'clean'
                : 'scanning';
  const stepVersion = activeStep?.version_after ?? 'v0';

  const activeVersion = stepVersion;

  // Whether this version has per-page markdowns (v0, v1) vs full-document only (v2, v3)
  const hasPerPageMarkdown = !!result?.page_markdowns[activeVersion];

  // Current page markdown for the active version โ€” fall back to full document for v2/v3
  const pageMarkdown = hasPerPageMarkdown
    ? (result?.page_markdowns[activeVersion]?.[String(currentPage)] ?? '')
    : (result?.versions[activeVersion] ?? '');
  const pageImage = result?.page_images[String(currentPage)] ?? null;

  // Map figure paths to base64 data URIs for inline rendering
  const figureMap = useMemo(() => {
    if (!result?.figures.length) return {};
    const map: Record<string, string> = {};
    for (const fig of result.figures) {
      if (fig.image_base64) {
        map[`figures/${fig.ref_id}.png`] = `data:image/png;base64,${fig.image_base64}`;
      }
    }
    return map;
  }, [result?.figures]);

  // Aggregate all changes from the active stage (not just the active step)
  const stageChanges = useMemo(() => {
    if (!result || !activeStep) return [];
    const allStages = [...PIPELINE_STAGES, REVIEW_STAGE];
    const stage = allStages.find((s) => s.steps.includes(activeStep.name))
      ?? (PIPELINE_STAGES.every((s) => !s.steps.includes(activeStep.name)) ? REVIEW_STAGE : null);
    if (!stage) return activeStep.changes;
    return result.steps
      .filter((s) => stage.steps.includes(s.name))
      .flatMap((s) => s.changes);
  }, [result, activeStep]);

  /** Convert a base64 PNG string to a Blob. */
  const base64ToBlob = useCallback((b64: string, mime = 'image/png'): Blob => {
    const bytes = atob(b64);
    const buf = new Uint8Array(bytes.length);
    for (let i = 0; i < bytes.length; i++) buf[i] = bytes.charCodeAt(i);
    return new Blob([buf], { type: mime });
  }, []);

  /** Copy current page image to clipboard. */
  const handleCopyImage = useCallback(async () => {
    if (!pageImage) return;
    try {
      const blob = base64ToBlob(pageImage);
      await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
      setCopiedImage(true);
      setTimeout(() => setCopiedImage(false), 1500);
    } catch {
      navigator.clipboard.writeText(`[Page ${currentPage} image โ€” clipboard not supported]`);
      setCopiedImage(true);
      setTimeout(() => setCopiedImage(false), 1500);
    }
  }, [pageImage, currentPage, base64ToBlob]);

  /**
   * Download a zip containing the version's markdown and a `figures/` folder
   * of PNGs. Markdown already uses `figures/{ref_id}.png` relative paths, so
   * the bundle is self-contained without any path rewriting.
   */
  const downloadBundle = useCallback(async (version: string) => {
    if (!result?.versions[version]) return;
    const baseName = result.filename.replace(/\.pdf$/i, '');
    const blob = await buildMarkdownBundle(result, version, baseName);
    triggerBlobDownload(blob, `${baseName}-${version}.zip`);
  }, [result]);

  const handleDownloadVersion = useCallback(
    (stepIndex: number) => {
      if (!result) return;
      const step = result.steps[stepIndex];
      if (!step?.version_after) return;
      void downloadBundle(step.version_after);
    },
    [result, downloadBundle],
  );

  const handleDownloadCurrentMarkdown = useCallback(() => {
    void downloadBundle(activeVersion);
  }, [activeVersion, downloadBundle]);

  const handleProcess = useCallback(
    async (file: File) => {
      setCurrentPage(1);
      setActiveStepIdx(0);
      await processFile(file, {
        imagesScale: 2.0,
        doTableStructure: true,
      });
    },
    [processFile],
  );

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setDragOver(false);
      const file = e.dataTransfer.files[0];
      if (file && file.name.toLowerCase().endsWith('.pdf')) {
        handleProcess(file);
      }
    },
    [handleProcess],
  );

  const handleFileSelect = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) handleProcess(file);
    },
    [handleProcess],
  );

  // Focus a landmark region by ID with a visible focus ring
  const handleFocusRegion = useCallback((region: FocusRegion) => {
    if (region === 'skip') {
      const firstLink = skipNavRef.current?.querySelector<HTMLAnchorElement>('a');
      firstLink?.focus();
      return;
    }
    const idMap = { pages: 'region-pages', stages: 'region-stages', preview: 'region-preview', changes: 'region-changes' };
    const el = document.getElementById(idMap[region]);
    if (el) {
      el.focus();
      el.scrollIntoView({ block: 'nearest' });
      // Apply a visible focus ring via inline style (Tailwind focus: doesn't reliably work on programmatic focus)
      el.style.outline = '2px solid #1e3a5f';
      el.style.outlineOffset = '-2px';
      const cleanup = () => {
        el.style.outline = '';
        el.style.outlineOffset = '';
        el.removeEventListener('blur', cleanup);
      };
      el.addEventListener('blur', cleanup);
    }
  }, []);

  return (
    <div className="flex flex-col h-screen bg-gray-50">
      {/* Skip navigation menu โ€” targets change with view state */}
      <nav
        ref={skipNavRef}
        aria-label="Skip navigation"
        className="sr-only focus-within:not-sr-only focus-within:absolute focus-within:z-[60] focus-within:top-0 focus-within:left-0 focus-within:bg-white focus-within:border focus-within:rounded-md focus-within:shadow-lg focus-within:p-3"
      >
        <ul className="flex flex-col gap-1">
          {viewState === 'idle' && (
            <li><a href="#region-upload" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to PDF upload</a></li>
          )}
          {viewState === 'uploading' && (
            <li><a href="#region-status" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to processing status</a></li>
          )}
          {viewState === 'error' && (
            <li><a href="#region-error" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to error message</a></li>
          )}
          {viewState === 'result' && (
            <>
              <li><a href="#region-preview" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to Rendered Preview</a></li>
              <li><a href="#region-stages" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to Stage Picker</a></li>
              <li><a href="#region-pages" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to Page Picker</a></li>
              <li><a href="#region-changes" className="text-sm text-uic-blue underline focus:outline-2 focus:outline-uic-blue px-2 py-1 block rounded hover:bg-uic-blue/5">Skip to Changes Panel</a></li>
            </>
          )}
        </ul>
      </nav>

      {/* Polite live region โ€” announces upload / pipeline state transitions
          to assistive technology without moving focus. */}
      <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">
        {liveAnnouncement}
      </div>

      <KeyboardShortcuts onFocusRegion={handleFocusRegion} />

      {/* Header */}
      <header aria-labelledby="region-header-heading" className="flex items-center px-6 py-3 bg-white border-b shadow-sm">
        <h1 id="region-header-heading" className="text-lg font-bold text-uic-blue flex items-center gap-2">
          {import.meta.env.VITE_SHOW_UIC_LOGO === 'true' && (
            <img
              src="/uic-logo.png"
              alt="University of Illinois Chicago"
              className="h-7 w-7"
            />
          )}
          Equalify Reflow
          <span
            className="text-[10px] font-semibold uppercase tracking-wider bg-uic-blue/10 text-uic-blue border border-uic-blue/20 px-2 py-0.5 rounded-full"
          >
            Beta
          </span>
        </h1>
      </header>

      {/* Classification error โ€” document was rejected before processing */}
      {result && Object.keys(result.versions).length === 0 && (() => {
        const classStep = result.steps.find((s) => s.name === 'classification' && s.error);
        return classStep ? (
          <section
            id="region-error"
            tabIndex={-1}
            aria-labelledby="region-error-heading"
            className="outline-none"
          >
            <h2 id="region-error-heading" className="sr-only">Classification error</h2>
            <ClassificationError step={classStep} onReset={reset} />
          </section>
        ) : null;
      })()}

      {/* Pipeline layout โ€” always visible */}
      {!(result && Object.keys(result.versions).length === 0 && result.steps.some((s) => s.name === 'classification' && s.error)) && (
        <div className="flex-1 flex flex-col min-h-0">
          {/* Step tabs */}
          <nav id="region-stages" tabIndex={-1} aria-labelledby="region-stages-heading" className="outline-none rounded-sm">
          <h2 id="region-stages-heading" className="sr-only">Pipeline stages</h2>
          <StageTabs
            steps={result?.steps ?? []}
            activeStepIdx={activeStepIdx}
            onSelectStep={setActiveStepIdx}
            processingStepName={processing ? currentStepName : null}
            onDownloadVersion={handleDownloadVersion}
            onOpenChangesModal={() => setChangesModalOpen(true)}
          />
          </nav>

          {/* Warnings banner */}
          {result?.warnings && result.warnings.length > 0 && (
            <WarningsBanner warnings={result.warnings} />
          )}

          {/* Pre-result states: upload, loading, error */}
          {!result && (
            <div className="flex-1 flex items-center justify-center p-8">
              {uploading ? (
                <section
                  id="region-status"
                  ref={loadingStatusRef}
                  tabIndex={-1}
                  aria-labelledby="region-status-heading"
                  className="flex flex-col items-center gap-4 outline-none focus:outline-2 focus:outline-uic-blue focus:outline-offset-4 rounded-md"
                >
                  <h2 id="region-status-heading" className="sr-only">Processing status</h2>
                  <Loader2 className="w-10 h-10 animate-spin text-uic-blue" aria-hidden="true" />
                  <p className="text-muted-foreground">Extracting document content...</p>
                  {statusMessage ? (
                    <div className="bg-amber-50 border border-amber-200 rounded-lg px-4 py-3 max-w-md text-center">
                      <p className="text-sm text-amber-900">{statusMessage}</p>
                    </div>
                  ) : (
                    <p className="text-xs text-muted-foreground">Processing time depends on document length and complexity</p>
                  )}
                </section>
              ) : error ? (
                <section
                  id="region-error"
                  tabIndex={-1}
                  aria-labelledby="region-error-inline-heading"
                  className="max-w-md text-center outline-none"
                >
                  <h2 id="region-error-inline-heading" className="sr-only">Processing error</h2>
                  <p className="text-red-700 font-medium mb-2">Processing Error</p>
                  <p className="text-sm text-muted-foreground mb-4">{error}</p>
                  <Button variant="outline" onClick={reset}>
                    Try Again
                  </Button>
                </section>
              ) : (
                <section aria-labelledby="region-upload-heading">
                <h2 id="region-upload-heading" className="sr-only">Upload a document</h2>
                <button
                  id="region-upload"
                  type="button"
                  onDragOver={(e) => {
                    e.preventDefault();
                    setDragOver(true);
                  }}
                  onDragLeave={() => setDragOver(false)}
                  onDrop={handleDrop}
                  className={cn(
                    'w-full max-w-lg border-2 border-dashed rounded-xl p-12 text-center transition-colors cursor-pointer bg-transparent focus:outline-2 focus:outline-uic-blue focus:outline-offset-2',
                    dragOver ? 'border-uic-blue bg-uic-blue/5' : 'border-gray-400 hover:border-uic-blue',
                  )}
                  onClick={() => fileInputRef.current?.click()}
                  aria-label="Upload a PDF: press Enter or Space to open a file picker, or drop a file here"
                >
                  <Upload className="w-12 h-12 mx-auto mb-4 text-gray-500" aria-hidden="true" />
                  <p className="text-lg font-medium text-gray-800 mb-1">
                    Drop a PDF here or click to upload
                  </p>
                  <p className="text-sm text-muted-foreground">
                    See every processing step in the pipeline above
                  </p>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".pdf"
                    className="hidden"
                    onChange={handleFileSelect}
                  />
                </button>
                </section>
              )}
            </div>
          )}

          {/* Stats bar โ€” only when we have results */}
          {result && Object.keys(result.versions).length > 0 && (
          <section
            aria-labelledby="region-stats-heading"
            className="flex items-center gap-6 px-6 py-2 bg-white border-b text-sm"
          >
            <h2 id="region-stats-heading" className="sr-only">Document stats and controls</h2>
            <div className="flex items-center gap-3 text-xs text-muted-foreground">
              <span className="flex items-center gap-1">
                <FileText className="w-3.5 h-3.5" />
                {result.total_pages} pages
              </span>
              <span className="flex items-center gap-1">
                <BarChart3 className="w-3.5 h-3.5" />
                {result.stats.chars_per_page as number} chars/page
              </span>
              {(result.stats.is_likely_scanned as boolean) && (
                <span className="text-amber-600 font-medium">Likely scanned</span>
              )}
              {result.figures.length > 0 && (
                <span className="flex items-center gap-1">
                  <ImageIcon className="w-3.5 h-3.5" />
                  {result.figures.length} figures
                </span>
              )}
              {(() => {
                const totalMs = result.steps.reduce((s, st) => s + (st.elapsed_ms || 0), 0);
                const totalSec = totalMs / 1000;
                const timeStr = totalSec >= 60
                  ? `${Math.floor(totalSec / 60)}m ${Math.round(totalSec % 60)}s`
                  : `${totalSec.toFixed(1)}s`;
                return totalMs > 0 ? (
                  <span className="flex items-center gap-1">
                    <Clock className="w-3.5 h-3.5" />
                    {timeStr}
                  </span>
                ) : null;
              })()}
              {(() => {
                const totalCost = result.steps.reduce((s, st) => s + (st.cost_cents || 0), 0);
                const totalTokens = result.steps.reduce((s, st) => s + (st.input_tokens || 0) + (st.output_tokens || 0), 0);
                if (totalTokens === 0) return null;
                return (
                  <span className="flex items-center gap-1">
                    <DollarSign className="w-3.5 h-3.5" />
                    {(totalCost / 100).toFixed(4)} ยท {totalTokens.toLocaleString()} tokens
                  </span>
                );
              })()}
            </div>

            <div className="flex-1" />

            {/* Feedback โ€” only after pipeline finishes */}
            {feedbackEnabled && !processing && (
              <Button
                variant="outline"
                size="sm"
                className="h-7 text-xs gap-1.5 text-uic-blue border-uic-blue/30 hover:bg-uic-blue/5"
                onClick={() => setFeedbackModalOpen(true)}
                title="Report an issue with this conversion"
              >
                <MessageSquarePlus className="w-3.5 h-3.5" />
                Feedback
              </Button>
            )}

            {/* Auto-advance toggle */}
            <Button
              variant="outline"
              size="sm"
              className={cn(
                'h-7 text-xs gap-1.5',
                autoAdvance
                  ? 'text-uic-blue border-uic-blue/30 hover:bg-uic-blue/5'
                  : 'text-muted-foreground',
              )}
              onClick={() => setAutoAdvance(!autoAdvance)}
              title={autoAdvance ? 'Auto-advance is on โ€” click to pause' : 'Auto-advance is off โ€” click to resume'}
            >
              {autoAdvance ? <Play className="w-3.5 h-3.5" /> : <Pause className="w-3.5 h-3.5" />}
              Auto-advance
            </Button>

            {/* New upload */}
            <Button
              variant="outline"
              size="sm"
              className="h-7 text-xs"
              onClick={reset}
            >
              <Upload className="w-3.5 h-3.5 mr-1" />
              New PDF
            </Button>
          </section>
          )}

          {/* PII Review inline panel โ€” takes over the main area when the
              pii_scan step is active (scanning, awaiting decision, or done). */}
          {result && piiPanelState && (
            <section
              aria-labelledby="region-pii-heading"
              className="flex-1 min-h-0 overflow-hidden bg-white"
            >
              <h2 id="region-pii-heading" className="sr-only">PII review</h2>
              <PiiReviewPanel
                state={piiPanelState}
                findings={piiFindings ?? []}
                error={activeStep?.error ?? null}
                onDecision={submitPiiDecision}
              />
            </section>
          )}

          {/* Main content area โ€” only when we have results and are not on pii */}
          {!piiPanelState && result && Object.keys(result.versions).length > 0 && (
          <div className="flex-1 flex min-h-0 overflow-hidden">
            {/* Page sidebar */}
            {totalPages > 1 && (
              <nav id="region-pages" tabIndex={-1} aria-labelledby="region-pages-heading" className="w-16 border-r bg-white overflow-y-auto flex-shrink-0 outline-none rounded-sm">
                <h2 id="region-pages-heading" className="sr-only">Page navigation</h2>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
                  <button
                    key={p}
                    onClick={() => setCurrentPage(p)}
                    aria-label={`Page ${p}`}
                    aria-current={p === currentPage ? 'page' : undefined}
                    className={cn(
                      'w-full py-2 text-xs font-medium border-b transition-colors',
                      p === currentPage
                        ? 'bg-uic-blue/10 text-uic-blue border-l-2 border-l-uic-blue'
                        : 'text-muted-foreground hover:bg-gray-50',
                    )}
                  >
                    {p}
                  </button>
                ))}
              </nav>
            )}

            {/* Split view */}
            <PanelGroup orientation="horizontal" className="flex-1 min-w-0 overflow-hidden">
              <Panel defaultSize={45} minSize={20}>
                <div className="h-full flex flex-col">
                  {pageImage && (
                    <div className="flex items-center justify-between px-4 py-2 border-b bg-gray-50">
                      <span className="text-sm font-medium text-muted-foreground">
                        Page {currentPage} Image
                      </span>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={handleCopyImage}
                        title="Copy page image"
                        className={cn(
                          'gap-1.5',
                          copiedImage
                            ? 'text-green-600 hover:text-green-700 hover:bg-green-50'
                            : 'text-muted-foreground hover:text-foreground',
                        )}
                      >
                        {copiedImage ? (
                          <Check className="w-4 h-4" />
                        ) : (
                          <Copy className="w-4 h-4" />
                        )}
                        <span className="text-xs">{copiedImage ? 'Copied' : 'Copy Image'}</span>
                      </Button>
                    </div>
                  )}
                  <div className="flex-1 overflow-auto bg-gray-100 flex items-start justify-center p-4">
                    {pageImage ? (
                      <img
                        src={`data:image/png;base64,${pageImage}`}
                        alt={`Page ${currentPage}`}
                        className="max-w-full shadow-lg rounded"
                      />
                    ) : processing || uploading ? (
                      <div className="flex flex-col items-center gap-2 mt-20 text-muted-foreground">
                        <Loader2 className="w-6 h-6 animate-spin" />
                        <span className="text-sm">Loading page image...</span>
                      </div>
                    ) : (
                      <div className="text-muted-foreground text-sm mt-20">
                        No image available
                      </div>
                    )}
                  </div>
                </div>
              </Panel>

              <PanelResizeHandle className="w-1.5 bg-gray-200 hover:bg-uic-blue/30 transition-colors cursor-col-resize" />

              <Panel defaultSize={55} minSize={20}>
                <main id="region-preview" tabIndex={-1} aria-labelledby="region-preview-heading" className="h-full outline-none rounded-sm">
                <h2 id="region-preview-heading" className="sr-only">Document preview</h2>
                <MarkdownViewer
                  content={pageMarkdown}
                  figureMap={figureMap}
                  isComplete={true}
                  onDownloadMarkdown={handleDownloadCurrentMarkdown}
                  onCopy={() => {
                    navigator.clipboard.writeText(pageMarkdown);
                  }}
                />
                </main>
              </Panel>
            </PanelGroup>

            {/* Right sidebar */}
            <aside id="region-changes" tabIndex={-1} aria-labelledby="region-changes-heading" className="flex-shrink-0 outline-none rounded-sm">
            <h2 id="region-changes-heading" className="sr-only">Changes and metadata</h2>
            {activeStep?.name === 'structure' && activeStep.metadata ? (
              <StructureMetadataPanel metadata={activeStep.metadata} onExpand={() => setMetadataModalOpen(true)} />
            ) : (
              <div className="w-64 flex-shrink-0 border-l bg-white flex flex-col">
                <div className="px-4 py-3 border-b">
                  <h3 className="text-sm font-medium text-muted-foreground">Changes</h3>
                </div>
                {stageChanges.length === 0 ? (
                  <div className="flex-1 flex items-center justify-center p-4">
                    <p className="text-xs text-muted-foreground text-center">
                      No changes in this stage.
                      <br />
                      Docling produces v0 from scratch.
                    </p>
                  </div>
                ) : (
                  <div className="flex-1 flex flex-col items-center justify-center p-4 gap-3">
                    <span className="text-2xl font-bold text-amber-700">{stageChanges.length}</span>
                    <p className="text-xs text-muted-foreground text-center">
                      change{stageChanges.length !== 1 ? 's' : ''} in this stage
                    </p>
                    <Button
                      variant="outline"
                      size="sm"
                      className="text-xs gap-1.5"
                      onClick={() => setChangesModalOpen(true)}
                    >
                      <Maximize2 className="w-3.5 h-3.5" />
                      View Details
                    </Button>
                  </div>
                )}
              </div>
            )}
            </aside>
          </div>
          )}

        </div>
      )}

      {/* Modals */}
      {changesModalOpen && (
        <ChangesModal
          changes={stageChanges}
          totalPages={totalPages}
          onClose={() => setChangesModalOpen(false)}
        />
      )}
      {metadataModalOpen && activeStep?.metadata && (
        <StructureMetadataModal
          metadata={activeStep.metadata}
          onClose={() => setMetadataModalOpen(false)}
        />
      )}
      {feedbackModalOpen && (
        <FeedbackModal
          onClose={() => setFeedbackModalOpen(false)}
          sessionId={sessionId ?? null}
          documentTitle={result?.filename ?? null}
          currentPage={currentPage}
          currentStage={activeStep?.display_name ?? null}
        />
      )}
    </div>
  );
}