File size: 58,826 Bytes
bbafea0
 
f0a2a7a
 
 
 
 
 
 
 
2f52027
 
bbafea0
 
65a736f
6953c2b
f0a2a7a
2d06acb
 
 
e016c4b
2d06acb
698ffee
2d06acb
230079f
2a3a36f
45ad5e2
bbafea0
ab420b2
6953c2b
 
 
 
 
 
 
 
 
 
 
ab420b2
bbafea0
ab420b2
e016c4b
ab420b2
b645a7a
ab420b2
 
 
 
6953c2b
401b968
05ce0ac
 
 
 
 
2d06acb
2f52027
 
 
 
 
 
 
 
 
 
 
cefe2f8
 
bbafea0
 
edc0890
 
bbafea0
 
 
 
 
 
230079f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbafea0
ab420b2
6953c2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab420b2
e016c4b
ab420b2
 
 
2f52027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e016c4b
 
 
6953c2b
05ce0ac
 
 
6953c2b
e016c4b
 
 
698ffee
e016c4b
 
 
 
 
 
 
 
 
45ad5e2
 
698ffee
45ad5e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab420b2
 
 
e016c4b
05ce0ac
 
 
 
 
 
e016c4b
6953c2b
 
 
 
 
 
 
 
 
 
 
e016c4b
698ffee
ab420b2
 
 
05ce0ac
ab420b2
 
 
 
 
 
 
 
6953c2b
401b968
6953c2b
698ffee
6953c2b
 
 
 
 
 
 
 
 
 
401b968
6953c2b
 
 
ab420b2
edc0890
ab420b2
b645a7a
cefe2f8
ab420b2
 
b645a7a
698ffee
 
b645a7a
 
 
 
ab420b2
b645a7a
 
 
 
ab420b2
 
 
 
 
 
 
 
2d06acb
edc0890
2d06acb
 
 
cefe2f8
 
 
bbafea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698ffee
bbafea0
 
 
 
 
 
 
 
 
 
 
698ffee
bbafea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf0c608
bbafea0
 
 
 
 
 
 
 
 
 
 
 
cefe2f8
 
 
 
 
 
 
 
698ffee
cefe2f8
 
 
 
 
 
 
 
 
bbafea0
9ca4b0e
cefe2f8
9ca4b0e
cefe2f8
 
9ca4b0e
 
 
 
 
 
cefe2f8
 
 
 
 
 
 
 
 
 
2d06acb
 
2f52027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698ffee
2f52027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05ce0ac
 
f0a2a7a
 
 
 
 
 
 
 
 
 
e27778b
 
 
 
 
 
 
65a736f
 
 
 
 
 
f0a2a7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d06acb
401b968
cb49f6a
 
 
2d06acb
401b968
6953c2b
 
 
401b968
6953c2b
401b968
6953c2b
 
 
 
 
401b968
6953c2b
 
 
 
 
 
 
 
 
 
 
 
 
 
401b968
6953c2b
 
 
 
 
401b968
6953c2b
 
 
 
 
 
 
 
 
 
 
 
401b968
 
 
 
 
 
 
 
6953c2b
 
401b968
6953c2b
401b968
6953c2b
 
 
 
 
 
 
401b968
6953c2b
 
 
 
 
 
 
 
401b968
6953c2b
 
 
 
401b968
6953c2b
 
 
401b968
6953c2b
 
 
2d06acb
6953c2b
 
2d06acb
cb49f6a
 
 
 
 
 
 
 
 
 
2d06acb
 
 
 
 
 
 
 
 
2f52027
2d06acb
 
 
 
 
 
6953c2b
 
 
401b968
6953c2b
 
401b968
 
6953c2b
401b968
6953c2b
 
401b968
6953c2b
 
 
 
 
2d06acb
 
401b968
2d06acb
 
 
 
 
bbafea0
2d06acb
97b08c9
2d06acb
 
 
 
2f52027
2d06acb
 
 
6953c2b
 
 
401b968
6953c2b
 
401b968
6953c2b
401b968
6953c2b
 
401b968
6953c2b
 
 
 
 
2d06acb
 
 
bbafea0
2d06acb
f0a2a7a
bbafea0
 
 
 
 
 
 
 
 
65a736f
f0a2a7a
 
 
 
05ce0ac
 
 
2f52027
 
 
 
 
bbafea0
e27778b
2f52027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05ce0ac
 
bbafea0
 
 
 
05ce0ac
 
 
2d06acb
 
e27778b
 
edc0890
e27778b
 
2d06acb
e27778b
2d06acb
 
edc0890
2d06acb
 
 
bbafea0
 
2d06acb
bbafea0
05ce0ac
bbafea0
 
 
 
 
 
 
 
 
45ad5e2
e27778b
45ad5e2
 
e27778b
 
 
 
edc0890
 
 
 
 
65a736f
 
edc0890
 
 
 
 
 
 
 
 
65a736f
 
edc0890
 
 
 
 
e27778b
65a736f
e27778b
 
 
edc0890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45ad5e2
edc0890
 
 
45ad5e2
edc0890
 
 
 
 
 
 
 
45ad5e2
edc0890
45ad5e2
edc0890
45ad5e2
 
edc0890
 
 
 
 
2d06acb
e27778b
edc0890
 
 
 
 
 
 
 
 
 
2d06acb
05ce0ac
 
 
 
 
f0a2a7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d06acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab420b2
e016c4b
2d06acb
 
 
 
ab420b2
2d06acb
 
 
 
 
 
 
 
 
 
 
 
 
2a3a36f
 
 
 
 
 
 
230079f
2a3a36f
9ed5724
230079f
2d06acb
b645a7a
2a3a36f
 
 
 
 
 
 
 
 
 
 
 
 
 
9ed5724
2a3a36f
 
 
 
 
2d06acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e016c4b
2d06acb
 
 
 
 
 
 
 
 
 
 
2a3a36f
2d06acb
 
 
e016c4b
ab420b2
 
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Users,
    FileText,
    SlidersHorizontal,
    Loader2,
    ArrowUp,
    ArrowDown,
    ArrowUpDown,
    Check,
    X,
    Trash2,
    Handshake,
    Pencil,
    Plus,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import AppShell from '@/components/layout/AppShell';
import MainTableWorkspace from '@/components/workspace/MainTableWorkspace';
import { apiFetch } from '@/lib/api';
import SlideOverPanel from '@/components/workspace/SlideOverPanel';
import CompanyDetailsEditor from '@/components/workspace/CompanyDetailsEditor';
import ContactIdentityEditor from '@/components/workspace/ContactIdentityEditor';
import { EditableCell } from '@/components/workspace/EditableCell';
import { cn } from '@/lib/utils';

function makeFilterRow() {
    return {
        id: `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
        field: 'none',
        op: 'contains',
        value: '',
        fromVal: '',
        toVal: '',
    };
}

export default function Contacts() {
    const navigate = useNavigate();
    const [contacts, setContacts] = useState([]);
    const [fields, setFields] = useState([]);
    const [selectedContact, setSelectedContact] = useState(null);
    const [selectedContactDetails, setSelectedContactDetails] = useState(null);
    const [sequences, setSequences] = useState([]);
    const [loading, setLoading] = useState(true);
    const [seqLoading, setSeqLoading] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [filterRows, setFilterRows] = useState(() => [makeFilterRow()]);
    const [seedBusy, setSeedBusy] = useState(false);
    const [sortBy, setSortBy] = useState('created_at');
    const [sortDir, setSortDir] = useState('desc');
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState('50');
    const [total, setTotal] = useState(0);
    const [sectionOpen, setSectionOpen] = useState(true);
    const [addingInline, setAddingInline] = useState(false);
    const [inlineDraft, setInlineDraft] = useState({
        first_name: '',
        last_name: '',
        email: '',
        company: '',
        title: '',
    });
    const [inlineSaving, setInlineSaving] = useState(false);
    const [inlineError, setInlineError] = useState('');
    const inlineFirstNameRef = useRef(null);
    const [enrichLoading, setEnrichLoading] = useState(false);
    const [enrichError, setEnrichError] = useState('');
    const [rowSelection, setRowSelection] = useState({});
    const [bulkBusy, setBulkBusy] = useState(null);
    /** Inline inputs only for this row id; pencil toggles. Row click opens slide-over. */
    const [tableEditRowId, setTableEditRowId] = useState(null);

    const selectedIds = useMemo(
        () => Object.keys(rowSelection).filter((id) => rowSelection[id]).map(Number),
        [rowSelection]
    );

    const contactCompanyDetailsForEditor = useMemo(() => {
        if (!selectedContactDetails) return null;
        const rd = selectedContactDetails.raw_data || {};
        return {
            'Company Name': rd['Company Name'] ?? selectedContactDetails.company ?? '',
            'Company Name for Emails': rd['Company Name for Emails'] ?? '',
            Industry: rd['Industry'] ?? '',
            '# Employees': rd['# Employees'] ?? '',
            'Annual Revenue': rd['Annual Revenue'] ?? '',
            'Last Raised At': rd['Last Raised At'] ?? '',
            Website: rd['Website'] ?? '',
            City: rd['City'] ?? '',
            State: rd['State'] ?? '',
            Country: rd['Country'] ?? '',
        };
    }, [selectedContactDetails]);

    const allPageSelected = contacts.length > 0 && contacts.every((c) => rowSelection[c.id]);

    const filtersKey = useMemo(() => JSON.stringify(filterRows), [filterRows]);

    const updateFilterRow = (id, patch) => {
        setFilterRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r)));
    };

    const addFilterRow = () => {
        setFilterRows((rows) => [...rows, makeFilterRow()]);
    };

    const removeFilterRow = (id) => {
        setFilterRows((rows) => {
            if (rows.length <= 1) {
                return [makeFilterRow()];
            }
            return rows.filter((r) => r.id !== id);
        });
    };

    useEffect(() => {
        fetchFields();
        fetchContacts();
    }, []);

    useEffect(() => {
        if (!addingInline) return;
        const t = requestAnimationFrame(() => {
            inlineFirstNameRef.current?.focus();
        });
        return () => cancelAnimationFrame(t);
    }, [addingInline]);

    useEffect(() => {
        if (!addingInline) return;
        const onKey = (e) => {
            if (e.key === 'Escape') {
                e.preventDefault();
                setAddingInline(false);
                setInlineError('');
            }
        };
        window.addEventListener('keydown', onKey);
        return () => window.removeEventListener('keydown', onKey);
    }, [addingInline]);

    useEffect(() => {
        const timer = setTimeout(() => fetchContacts(), 250);
        return () => clearTimeout(timer);
    }, [searchQuery, filtersKey, sortBy, sortDir, page, pageSize]);

    useEffect(() => {
        setPage(1);
    }, [searchQuery, filtersKey, sortBy, sortDir, pageSize]);

    const fetchFields = async () => {
        try {
            const res = await apiFetch('/api/contact-fields');
            if (res.ok) {
                const data = await res.json();
                setFields(data.fields || []);
            }
        } catch (e) {
            console.error('Failed to fetch contact fields:', e);
        }
    };

    const patchContact = async (contactId, patch) => {
        try {
            const res = await apiFetch(`/api/contacts/${contactId}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(patch),
            });
            const data = await res.json().catch(() => ({}));
            if (!res.ok) {
                throw new Error(typeof data.detail === 'string' ? data.detail : 'Update failed');
            }
            setContacts((prev) => prev.map((c) => (c.id === contactId ? { ...c, ...data } : c)));
            setSelectedContact((c) => (c && c.id === contactId ? { ...c, ...data } : c));
            setSelectedContactDetails((d) => (d && d.id === contactId ? { ...d, ...data } : d));
        } catch (e) {
            console.error(e);
            alert(e.message || 'Could not save changes');
            await fetchContacts();
        }
    };

    const fetchContacts = async () => {
        setLoading(true);
        try {
            const params = new URLSearchParams();
            const pageLimit = Number(pageSize || 50);
            const pageOffset = (page - 1) * pageLimit;
            params.set('limit', String(pageLimit));
            params.set('offset', String(pageOffset));
            params.set('sort_by', sortBy);
            params.set('sort_dir', sortDir);
            if (searchQuery.trim()) params.set('search', searchQuery.trim());
            const activeFilters = filterRows
                .filter((r) => r.field && r.field !== 'none')
                .map((r) => ({
                    field: r.field,
                    op: r.op,
                    value: r.value,
                    from_value: r.fromVal,
                    to_value: r.toVal,
                }));
            if (activeFilters.length > 0) {
                params.set('filters', JSON.stringify(activeFilters));
            }
            const res = await apiFetch(`/api/contacts?${params.toString()}`);
            if (res.ok) {
                const data = await res.json();
                setContacts(data.contacts || []);
                setTotal(data.total || 0);
            }
        } catch (e) {
            console.error('Failed to fetch contacts:', e);
        } finally {
            setLoading(false);
        }
    };

    const seedDemoContacts = async () => {
        setSeedBusy(true);
        try {
            const res = await apiFetch('/api/contacts/seed-demo', { method: 'POST' });
            const data = await res.json().catch(() => ({}));
            if (!res.ok) {
                throw new Error(typeof data.detail === 'string' ? data.detail : 'Could not load demo data');
            }
            await fetchFields();
            await fetchContacts();
        } catch (e) {
            console.error(e);
            alert(e.message || 'Could not load demo data');
        } finally {
            setSeedBusy(false);
        }
    };

    const openContact = async (contact) => {
        setTableEditRowId(null);
        setSelectedContact(contact);
        setSelectedContactDetails(null);
        setEnrichError('');
        setSeqLoading(true);
        try {
            const [detailRes, seqRes] = await Promise.all([
                apiFetch(`/api/contacts/${contact.id}`),
                apiFetch(`/api/contacts/${contact.id}/sequences`),
            ]);
            if (detailRes.ok) {
                const detailData = await detailRes.json();
                setSelectedContactDetails(detailData);
            }
            if (seqRes.ok) {
                const seqData = await seqRes.json();
                setSequences(seqData.sequences || []);
            } else setSequences([]);
        } catch (e) {
            console.error('Failed to fetch contact sequences:', e);
            setSequences([]);
        } finally {
            setSeqLoading(false);
        }
    };

    const closePanel = () => {
        setTableEditRowId(null);
        setSelectedContact(null);
        setSelectedContactDetails(null);
        setSequences([]);
        setEnrichError('');
    };

    const toggleRow = (id) => {
        setRowSelection((prev) => ({ ...prev, [id]: !prev[id] }));
    };

    const toggleAllPage = () => {
        if (allPageSelected) {
            setRowSelection((prev) => {
                const next = { ...prev };
                contacts.forEach((c) => {
                    delete next[c.id];
                });
                return next;
            });
        } else {
            setRowSelection((prev) => {
                const next = { ...prev };
                contacts.forEach((c) => {
                    next[c.id] = true;
                });
                return next;
            });
        }
    };

    const runBulkAction = async (action) => {
        if (selectedIds.length === 0) return;
        const touched = new Set(selectedIds);
        setBulkBusy(action);
        try {
            if (action === 'delete') {
                if (
                    !window.confirm(
                        `Delete ${selectedIds.length} contact(s)? This cannot be undone.`
                    )
                ) {
                    return;
                }
                const res = await apiFetch('/api/contacts/bulk-delete', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ contact_ids: selectedIds }),
                });
                const data = await res.json().catch(() => ({}));
                if (!res.ok) {
                    throw new Error(
                        typeof data.detail === 'string' ? data.detail : 'Delete failed'
                    );
                }
            } else if (action === 'leads') {
                const res = await apiFetch('/api/contacts/bulk-convert-to-leads', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ contact_ids: selectedIds }),
                });
                const data = await res.json().catch(() => ({}));
                if (!res.ok) {
                    throw new Error(
                        typeof data.detail === 'string' ? data.detail : 'Convert failed'
                    );
                }
                const conv = data.converted ?? 0;
                if (conv === 0) {
                    alert(
                        data.errors?.length
                            ? 'No contacts were converted. Typical reasons: missing email, or a lead with the same email already exists. See console for per-row errors.'
                            : 'No contacts were converted.'
                    );
                    if (data.errors?.length) console.warn(data.errors);
                    await fetchContacts();
                    return;
                }
                if (data.errors?.length) {
                    console.warn(data.errors);
                    alert(
                        `Converted ${conv} contact(s) to leads. ${data.errors.length} row(s) failed — see console.`
                    );
                }
                navigate('/leads');
            }
            if (selectedContact && touched.has(selectedContact.id)) {
                closePanel();
            }
            setRowSelection({});
            await fetchContacts();
        } catch (e) {
            console.error(e);
            alert(e.message || 'Action failed');
        } finally {
            setBulkBusy(null);
        }
    };

    const bulkDisabled = selectedIds.length === 0 || bulkBusy;

    const bulkToolbar = (
        <div className="flex flex-wrap items-center gap-2 px-4 py-2.5 border-b border-slate-100 bg-slate-50/90">
            <span className="text-xs text-slate-500 mr-2">{selectedIds.length} selected</span>
            <Button
                type="button"
                variant="outline"
                size="icon"
                className="h-9 w-9 shrink-0 text-red-600 border-red-200 hover:bg-red-50"
                title="Delete"
                disabled={bulkDisabled}
                onClick={() => runBulkAction('delete')}
            >
                {bulkBusy === 'delete' ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                    <Trash2 className="h-4 w-4" />
                )}
            </Button>
            <Button
                type="button"
                variant="outline"
                size="icon"
                className="h-9 w-9 shrink-0 text-violet-700 border-violet-200 hover:bg-violet-50"
                title="Copy to Leads (contacts remain in Contacts)"
                disabled={bulkDisabled}
                onClick={() => runBulkAction('leads')}
            >
                {bulkBusy === 'leads' ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                    <Handshake className="h-4 w-4" />
                )}
            </Button>
        </div>
    );

    const isManualContact =
        selectedContactDetails?.source === 'manual' || selectedContact?.source === 'manual';

    const enrichContactFromGpt = async () => {
        if (!selectedContact?.id) return;
        setEnrichLoading(true);
        setEnrichError('');
        try {
            const res = await apiFetch(`/api/contacts/${selectedContact.id}/enrich`, {
                method: 'POST',
            });
            const data = await res.json().catch(() => ({}));
            if (!res.ok) {
                setEnrichError(
                    typeof data.detail === 'string' ? data.detail : 'Could not fetch enrichment'
                );
                return;
            }
            const { enrichment_report: _er, ...contactPayload } = data;
            setSelectedContactDetails(contactPayload);
            setSelectedContact((c) =>
                c && c.id === contactPayload.id
                    ? {
                          ...c,
                          first_name: contactPayload.first_name,
                          last_name: contactPayload.last_name,
                          email: contactPayload.email,
                          company: contactPayload.company,
                          title: contactPayload.title,
                          source: contactPayload.source,
                      }
                    : c
            );
            fetchContacts();
        } catch (e) {
            console.error(e);
            setEnrichError('Network error');
        } finally {
            setEnrichLoading(false);
        }
    };

    const beginAddContact = () => {
        setAddingInline(true);
        setInlineDraft({
            first_name: '',
            last_name: '',
            email: '',
            company: '',
            title: '',
        });
        setInlineError('');
    };

    const cancelAddContact = () => {
        setAddingInline(false);
        setInlineError('');
    };

    const saveAddContact = async () => {
        const email = inlineDraft.email.trim();
        if (!email) {
            setInlineError('Email is required');
            return;
        }
        if (!email.includes('@')) {
            setInlineError('Enter a valid email address');
            return;
        }
        setInlineSaving(true);
        setInlineError('');
        try {
            const res = await apiFetch('/api/contacts', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    first_name: inlineDraft.first_name.trim(),
                    last_name: inlineDraft.last_name.trim(),
                    email,
                    company: inlineDraft.company.trim(),
                    title: inlineDraft.title.trim(),
                }),
            });
            const data = await res.json().catch(() => ({}));
            if (res.status === 409) {
                setInlineError(
                    typeof data.detail === 'string' ? data.detail : 'A contact with this email already exists'
                );
                return;
            }
            if (!res.ok) {
                setInlineError(
                    typeof data.detail === 'string' ? data.detail : 'Could not save contact'
                );
                return;
            }
            setAddingInline(false);
            await fetchContacts();
        } catch (e) {
            console.error(e);
            setInlineError('Network error');
        } finally {
            setInlineSaving(false);
        }
    };

    const inlineInputKeyDown = (e) => {
        if (e.key !== 'Enter' || e.shiftKey) return;
        e.preventDefault();
        saveAddContact();
    };

    const totalPages = Math.max(1, Math.ceil(total / Number(pageSize || 50)));

    const toggleSort = (field) => {
        if (sortBy === field) {
            setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
        } else {
            setSortBy(field);
            setSortDir('asc');
        }
        setPage(1);
    };

    const isRowUiTarget = (e) =>
        Boolean(
            e.target.closest(
                'input, textarea, button, a, [role="combobox"], [role="listbox"], [data-radix-collection-item]'
            )
        );

    const focusFirstEditableInRow = (tr) => {
        if (!tr) return;
        const el = tr.querySelector('input:not([type="checkbox"]):not([type="hidden"]), textarea');
        el?.focus?.();
    };

    const SortHeader = ({ field, label, className = '' }) => {
        const active = sortBy === field;
        return (
            <th className={`px-3 py-2 font-medium ${className}`}>
                <button
                    type="button"
                    className="inline-flex items-center gap-1.5 text-left text-slate-600 hover:text-violet-700 transition-colors group"
                    onClick={() => toggleSort(field)}
                >
                    <span>{label}</span>
                    {active ? (
                        sortDir === 'asc' ? (
                            <ArrowUp className="h-3.5 w-3.5 text-violet-600 shrink-0" aria-hidden />
                        ) : (
                            <ArrowDown className="h-3.5 w-3.5 text-violet-600 shrink-0" aria-hidden />
                        )
                    ) : (
                        <ArrowUpDown
                            className="h-3.5 w-3.5 text-slate-300 group-hover:text-slate-400 shrink-0"
                            aria-hidden
                        />
                    )}
                </button>
            </th>
        );
    };

    const filtersBlock = (
        <div className="space-y-2 text-xs">
            <div className="flex items-start gap-1.5 text-slate-600 font-medium leading-snug">
                <SlidersHorizontal className="h-3.5 w-3.5 mt-0.5 shrink-0" />
                <span>Filters (AND)</span>
            </div>
            <div className="space-y-2">
                {filterRows.map((row) => (
                    <div
                        key={row.id}
                        className="space-y-2 rounded-lg border border-slate-200 bg-white/90 p-2 shadow-sm"
                    >
                        <div>
                            <label className="sr-only">Field</label>
                            <Select
                                value={row.field}
                                onValueChange={(v) => updateFilterRow(row.id, { field: v })}
                            >
                                <SelectTrigger className="h-8 border-slate-200 bg-white text-xs">
                                    <SelectValue placeholder="Field" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="none">No field filter</SelectItem>
                                    {fields.map((field) => (
                                        <SelectItem key={field} value={field}>
                                            {field}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        {row.field !== 'none' && (
                            <>
                                <div>
                                    <label className="sr-only">Operator</label>
                                    <Select
                                        value={row.op}
                                        onValueChange={(v) => updateFilterRow(row.id, { op: v })}
                                    >
                                        <SelectTrigger className="h-8 border-slate-200 bg-white text-xs">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="contains">contains</SelectItem>
                                            <SelectItem value="equals">equals</SelectItem>
                                            <SelectItem value="from">from</SelectItem>
                                            <SelectItem value="to">to</SelectItem>
                                            <SelectItem value="between">between</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                {(row.op === 'contains' || row.op === 'equals') && (
                                    <Input
                                        className="h-8 border-slate-200 bg-white text-xs"
                                        placeholder={`“${row.field}”`}
                                        value={row.value}
                                        onChange={(e) =>
                                            updateFilterRow(row.id, { value: e.target.value })
                                        }
                                    />
                                )}
                                {(row.op === 'from' || row.op === 'to' || row.op === 'between') && (
                                    <div className="flex flex-col gap-2">
                                        <Input
                                            className="h-8 border-slate-200 bg-white text-xs"
                                            placeholder="From"
                                            value={row.fromVal}
                                            onChange={(e) =>
                                                updateFilterRow(row.id, { fromVal: e.target.value })
                                            }
                                        />
                                        <Input
                                            className="h-8 border-slate-200 bg-white text-xs"
                                            placeholder="To"
                                            value={row.toVal}
                                            onChange={(e) =>
                                                updateFilterRow(row.id, { toVal: e.target.value })
                                            }
                                        />
                                    </div>
                                )}
                                <div className="flex justify-end pt-0.5">
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8 text-slate-400 hover:text-red-600"
                                        aria-label="Remove filter row"
                                        onClick={() => removeFilterRow(row.id)}
                                    >
                                        <Trash2 className="h-3.5 w-3.5" />
                                    </Button>
                                </div>
                            </>
                        )}
                    </div>
                ))}
            </div>
            <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8 w-full gap-1 text-xs"
                onClick={addFilterRow}
            >
                <Plus className="h-3.5 w-3.5" />
                Add filter
            </Button>
        </div>
    );

    return (
        <AppShell
            title="Contacts"
            subtitle="Apollo CSV contacts stored in SQLite with full field payload."
        >
            <MainTableWorkspace
                primaryAction={{ label: 'New contact', onClick: beginAddContact }}
                search={{
                    value: searchQuery,
                    onChange: (e) => setSearchQuery(e.target.value),
                    placeholder: 'Search contacts…',
                }}
                right={
                    <div className="flex flex-wrap items-center gap-2 justify-end">
                        <Button
                            type="button"
                            variant="secondary"
                            size="sm"
                            onClick={seedDemoContacts}
                            disabled={seedBusy}
                            title="Insert sample Apollo-style contacts for preview"
                        >
                            {seedBusy ? (
                                <Loader2 className="h-4 w-4 animate-spin shrink-0" aria-hidden />
                            ) : null}
                            Demo data
                        </Button>
                        <Button variant="outline" size="sm" onClick={() => fetchContacts()}>
                            Refresh
                        </Button>
                    </div>
                }
                filters={filtersBlock}
                filtersPlacement="left"
                sectionIcon={Users}
                sectionTitle="All contacts"
                sectionCount={total}
                sectionOpen={sectionOpen}
                onSectionToggle={() => setSectionOpen(!sectionOpen)}
                tableToolbar={bulkToolbar}
            >
                <div className="w-full min-w-0 overflow-x-auto">
                    {loading ? (
                        <div className="flex justify-center py-16 text-slate-500">
                            <Loader2 className="h-8 w-8 animate-spin" />
                        </div>
                    ) : contacts.length === 0 && !addingInline ? (
                        <div className="text-center py-16 text-slate-500 space-y-3">
                            <Users className="h-10 w-10 mx-auto opacity-40" />
                            <p>No contacts found</p>
                            <div className="flex flex-wrap items-center justify-center gap-2">
                                <Button
                                    type="button"
                                    variant="secondary"
                                    size="sm"
                                    onClick={seedDemoContacts}
                                    disabled={seedBusy}
                                >
                                    {seedBusy ? (
                                        <Loader2 className="h-4 w-4 animate-spin mr-2" aria-hidden />
                                    ) : null}
                                    Load demo rows (preview UI)
                                </Button>
                                <Button variant="outline" size="sm" onClick={beginAddContact}>
                                    New contact
                                </Button>
                            </div>
                        </div>
                    ) : (
                        <>
                            <table className="w-full text-sm min-w-[760px]">
                                <thead>
                                    <tr className="bg-slate-50 text-left border-b border-slate-200">
                                        <th className="px-3 py-2 font-medium w-10">
                                            <input
                                                type="checkbox"
                                                className="rounded border-slate-300"
                                                checked={allPageSelected}
                                                onChange={toggleAllPage}
                                                aria-label="Select all on page"
                                            />
                                        </th>
                                        <th className="w-9 px-0 py-2" aria-label="Table edit" />
                                        <SortHeader field="first_name" label="Name" />
                                        <SortHeader field="email" label="Email" />
                                        <SortHeader field="company" label="Company" />
                                        <SortHeader field="title" label="Title" />
                                    </tr>
                                </thead>
                                <tbody>
                                    {addingInline && (
                                        <tr
                                            className="border-b border-slate-100 bg-sky-50 shadow-[inset_4px_0_0_0_#10b981]"
                                            onClick={(e) => e.stopPropagation()}
                                        >
                                            <td className="px-3 py-2 w-10 align-top" aria-hidden />
                                            <td className="w-9 align-top" aria-hidden />
                                            <td className="px-3 py-2 align-top">
                                                <div className="flex flex-col gap-1.5 min-w-[160px]">
                                                    <Input
                                                        ref={inlineFirstNameRef}
                                                        className="h-8 border-slate-200 bg-white text-sm"
                                                        placeholder="First name"
                                                        value={inlineDraft.first_name}
                                                        onChange={(e) =>
                                                            setInlineDraft((d) => ({
                                                                ...d,
                                                                first_name: e.target.value,
                                                            }))
                                                        }
                                                        onKeyDown={inlineInputKeyDown}
                                                        disabled={inlineSaving}
                                                        aria-label="First name"
                                                    />
                                                    <Input
                                                        className="h-8 border-slate-200 bg-white text-sm"
                                                        placeholder="Last name"
                                                        value={inlineDraft.last_name}
                                                        onChange={(e) =>
                                                            setInlineDraft((d) => ({
                                                                ...d,
                                                                last_name: e.target.value,
                                                            }))
                                                        }
                                                        onKeyDown={inlineInputKeyDown}
                                                        disabled={inlineSaving}
                                                        aria-label="Last name"
                                                    />
                                                </div>
                                            </td>
                                            <td className="px-3 py-2 align-top">
                                                <Input
                                                    className="h-8 border-slate-200 bg-white text-sm max-w-[240px]"
                                                    type="email"
                                                    placeholder="Email"
                                                    value={inlineDraft.email}
                                                    onChange={(e) =>
                                                        setInlineDraft((d) => ({ ...d, email: e.target.value }))
                                                    }
                                                    onKeyDown={inlineInputKeyDown}
                                                    disabled={inlineSaving}
                                                    aria-label="Email"
                                                />
                                            </td>
                                            <td className="px-3 py-2 align-top">
                                                <Input
                                                    className="h-8 border-slate-200 bg-white text-sm max-w-[200px]"
                                                    placeholder="Company"
                                                    value={inlineDraft.company}
                                                    onChange={(e) =>
                                                        setInlineDraft((d) => ({
                                                            ...d,
                                                            company: e.target.value,
                                                        }))
                                                    }
                                                    onKeyDown={inlineInputKeyDown}
                                                    disabled={inlineSaving}
                                                    aria-label="Company"
                                                />
                                            </td>
                                            <td className="px-3 py-2 align-top">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <Input
                                                        className="h-8 border-slate-200 bg-white text-sm flex-1 min-w-[120px] max-w-[200px]"
                                                        placeholder="Title"
                                                        value={inlineDraft.title}
                                                        onChange={(e) =>
                                                            setInlineDraft((d) => ({
                                                                ...d,
                                                                title: e.target.value,
                                                            }))
                                                        }
                                                        onKeyDown={inlineInputKeyDown}
                                                        disabled={inlineSaving}
                                                        aria-label="Title"
                                                    />
                                                    <div className="flex items-center gap-1 shrink-0">
                                                        <Button
                                                            type="button"
                                                            size="icon"
                                                            variant="ghost"
                                                            className="h-8 w-8 text-emerald-700 hover:text-emerald-800 hover:bg-emerald-50"
                                                            onClick={saveAddContact}
                                                            disabled={inlineSaving}
                                                            aria-label="Save contact"
                                                        >
                                                            {inlineSaving ? (
                                                                <Loader2 className="h-4 w-4 animate-spin" />
                                                            ) : (
                                                                <Check className="h-4 w-4" />
                                                            )}
                                                        </Button>
                                                        <Button
                                                            type="button"
                                                            size="icon"
                                                            variant="ghost"
                                                            className="h-8 w-8 text-slate-500 hover:text-slate-800"
                                                            onClick={cancelAddContact}
                                                            disabled={inlineSaving}
                                                            aria-label="Cancel"
                                                        >
                                                            <X className="h-4 w-4" />
                                                        </Button>
                                                    </div>
                                                </div>
                                                {inlineError ? (
                                                    <p className="text-xs text-red-600 mt-1 w-full">{inlineError}</p>
                                                ) : null}
                                            </td>
                                        </tr>
                                    )}
                                    {contacts.map((contact) => {
                                        const active = selectedContact?.id === contact.id;
                                        const displayName =
                                            [contact.first_name, contact.last_name].filter(Boolean).join(' ') ||
                                            contact.email ||
                                            '—';
                                        return (
                                            <tr
                                                key={contact.id}
                                                role="button"
                                                tabIndex={0}
                                                onClick={(e) => {
                                                    if (isRowUiTarget(e)) return;
                                                    setTableEditRowId(null);
                                                    openContact(contact);
                                                }}
                                                onKeyDown={(e) => {
                                                    if (isRowUiTarget(e)) return;
                                                    if (e.key === 'Enter' || e.key === ' ') {
                                                        e.preventDefault();
                                                        setTableEditRowId(null);
                                                        openContact(contact);
                                                    }
                                                }}
                                                className={cn(
                                                    'cursor-pointer border-b border-slate-100',
                                                    active ? 'bg-violet-50/80' : 'hover:bg-violet-50/40'
                                                )}
                                            >
                                                <td className="px-3 py-2" onClick={(e) => e.stopPropagation()}>
                                                    <input
                                                        type="checkbox"
                                                        className="rounded border-slate-300"
                                                        checked={!!rowSelection[contact.id]}
                                                        onChange={() => toggleRow(contact.id)}
                                                        aria-label={`Select ${displayName}`}
                                                    />
                                                </td>
                                                <td
                                                    className="px-0 py-1.5 align-middle w-9"
                                                    onClick={(e) => e.stopPropagation()}
                                                >
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="icon"
                                                        className={cn(
                                                            'h-8 w-8 text-slate-500 hover:text-violet-700',
                                                            tableEditRowId === contact.id &&
                                                                'bg-violet-100 text-violet-800 hover:bg-violet-100'
                                                        )}
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            const tr = e.currentTarget.closest('tr');
                                                            const off = tableEditRowId === contact.id;
                                                            if (off) {
                                                                setTableEditRowId(null);
                                                                return;
                                                            }
                                                            setTableEditRowId(contact.id);
                                                            requestAnimationFrame(() =>
                                                                focusFirstEditableInRow(tr)
                                                            );
                                                        }}
                                                        aria-label={
                                                            tableEditRowId === contact.id
                                                                ? `Stop editing row for ${displayName}`
                                                                : `Edit fields in row for ${displayName}`
                                                        }
                                                    >
                                                        <Pencil className="h-4 w-4" aria-hidden />
                                                    </Button>
                                                </td>
                                                <td className="px-3 py-2 align-top">
                                                    {tableEditRowId === contact.id ? (
                                                        <div className="flex flex-col gap-1 min-w-[140px] max-w-[200px]">
                                                            <EditableCell
                                                                value={contact.first_name || ''}
                                                                onCommit={(v) =>
                                                                    patchContact(contact.id, { first_name: v })
                                                                }
                                                                inputClassName="font-medium text-violet-800"
                                                            />
                                                            <EditableCell
                                                                value={contact.last_name || ''}
                                                                onCommit={(v) =>
                                                                    patchContact(contact.id, { last_name: v })
                                                                }
                                                                inputClassName="font-medium text-violet-800"
                                                            />
                                                        </div>
                                                    ) : (
                                                        <div className="min-h-[2.25rem] py-1 text-sm font-medium text-violet-800 leading-snug">
                                                            {displayName}
                                                        </div>
                                                    )}
                                                </td>
                                                <td className="px-3 py-2 align-top max-w-[240px]">
                                                    {tableEditRowId === contact.id ? (
                                                        <EditableCell
                                                            type="email"
                                                            value={contact.email || ''}
                                                            onCommit={(v) => patchContact(contact.id, { email: v })}
                                                        />
                                                    ) : (
                                                        <div className="min-h-[2.25rem] py-1 text-sm text-slate-700 truncate">
                                                            {contact.email || '—'}
                                                        </div>
                                                    )}
                                                </td>
                                                <td className="px-3 py-2 align-top max-w-[220px]">
                                                    {tableEditRowId === contact.id ? (
                                                        <EditableCell
                                                            value={contact.company || ''}
                                                            onCommit={(v) =>
                                                                patchContact(contact.id, { company: v })
                                                            }
                                                        />
                                                    ) : (
                                                        <div className="min-h-[2.25rem] py-1 text-sm text-slate-700 truncate">
                                                            {contact.company || '—'}
                                                        </div>
                                                    )}
                                                </td>
                                                <td className="px-3 py-2 align-top max-w-[200px]">
                                                    {tableEditRowId === contact.id ? (
                                                        <EditableCell
                                                            value={contact.title || ''}
                                                            onCommit={(v) => patchContact(contact.id, { title: v })}
                                                        />
                                                    ) : (
                                                        <div className="min-h-[2.25rem] py-1 text-sm text-slate-600 truncate">
                                                            {contact.title || '—'}
                                                        </div>
                                                    )}
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                            <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 border-t border-slate-100 bg-slate-50/50">
                                <div className="flex flex-wrap items-center gap-3 text-xs text-slate-600">
                                    <span className="text-slate-500">Rows per page</span>
                                    <Select
                                        value={pageSize}
                                        onValueChange={(v) => {
                                            setPageSize(v);
                                            setPage(1);
                                        }}
                                    >
                                        <SelectTrigger className="h-8 w-[88px] border-slate-200 bg-white text-xs">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="25">25</SelectItem>
                                            <SelectItem value="50">50</SelectItem>
                                            <SelectItem value="100">100</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <span className="text-slate-500">
                                        Page {page} of {totalPages}
                                    </span>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => setPage((p) => Math.max(1, p - 1))}
                                        disabled={page <= 1}
                                    >
                                        Prev
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                                        disabled={page >= totalPages}
                                    >
                                        Next
                                    </Button>
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </MainTableWorkspace>

            <SlideOverPanel
                open={!!selectedContact}
                onClose={closePanel}
                title={
                    selectedContactDetails || selectedContact
                        ? `${selectedContactDetails?.first_name || selectedContact?.first_name || ''} ${selectedContactDetails?.last_name || selectedContact?.last_name || ''}`.trim() ||
                          'Contact'
                        : 'Contact'
                }
                subtitle={(selectedContactDetails?.email || selectedContact?.email) || ''}
                widthClassName="max-w-xl"
            >
                {selectedContact && (
                    <div className="flex flex-col">
                        {selectedContactDetails && (
                            <ContactIdentityEditor
                                firstName={selectedContactDetails.first_name || ''}
                                lastName={selectedContactDetails.last_name || ''}
                                email={selectedContactDetails.email || ''}
                                title={selectedContactDetails.title || ''}
                                onSave={(patch) => patchContact(selectedContact.id, patch)}
                                disabled={!selectedContact}
                                autoSave
                            />
                        )}

                        <div className="mt-8 pt-6 border-t border-slate-100">
                            {contactCompanyDetailsForEditor && selectedContact && (
                                <CompanyDetailsEditor
                                    variant="contact"
                                    companyDetails={contactCompanyDetailsForEditor}
                                    fallbackCompanyName={
                                        selectedContactDetails?.company || selectedContact.company || ''
                                    }
                                    onSave={(patch) => patchContact(selectedContact.id, patch)}
                                    className="mb-0"
                                    showFetch={isManualContact}
                                    onFetch={enrichContactFromGpt}
                                    fetchLoading={enrichLoading}
                                    fetchError={enrichError}
                                    autoSave
                                />
                            )}
                        </div>

                        <div className="mt-8 pt-6 border-t border-slate-100">
                        <h4 className="text-sm font-semibold text-slate-800 mb-2 flex items-center gap-2">
                            <FileText className="h-4 w-4" />
                            Generated sequences
                        </h4>
                        {seqLoading ? (
                            <p className="text-sm text-slate-500">Loading sequences…</p>
                        ) : sequences.length === 0 ? (
                            <p className="text-sm text-slate-500">No generated sequences for this contact yet.</p>
                        ) : (
                            <div className="space-y-3 max-h-[55vh] overflow-y-auto pr-1">
                                {sequences.map((seq) => (
                                    <div
                                        key={seq.id}
                                        className="rounded-xl border border-slate-200 p-4 bg-slate-50/50"
                                    >
                                        <div className="font-medium text-slate-800 mb-2">
                                            Email {seq.email_number} {seq.product ? `• ${seq.product}` : ''}
                                        </div>
                                        <div className="text-sm mb-2">
                                            <span className="font-semibold text-slate-700">Subject: </span>
                                            <span className="text-slate-700">{seq.subject}</span>
                                        </div>
                                        <div className="rounded-lg border border-slate-200 bg-white p-3 text-sm text-slate-700 whitespace-pre-wrap">
                                            {seq.email_content}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                        </div>
                    </div>
                )}
            </SlideOverPanel>
        </AppShell>
    );
}