File size: 59,912 Bytes
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
3e19b1e
85f794d
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  Fragment, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState,
  type Dispatch, type FormEvent, type ReactNode, type SetStateAction,
} from "react";
import { ArrowCounterClockwise } from "@phosphor-icons/react/dist/csr/ArrowCounterClockwise";
import { ArrowRight } from "@phosphor-icons/react/dist/csr/ArrowRight";
import { CalendarBlank } from "@phosphor-icons/react/dist/csr/CalendarBlank";
import { Funnel } from "@phosphor-icons/react/dist/csr/Funnel";
import { MagnifyingGlass } from "@phosphor-icons/react/dist/csr/MagnifyingGlass";
import { X } from "@phosphor-icons/react/dist/csr/X";
import { useEscapeClose } from "../../ui/useEscapeClose";
import ProjectTasks from "./ProjectTasks";
import ProjectSkuPicker from "./ProjectSkuPicker";
import { PdpApprovalRow, PdpOverviewRows, PdpStep, type ProjectPdp } from "./pdp/ContinueWorkflow";
import { removeItems } from "./pdp/api";
import {
  EMPTY_FILTER, GRAINS, ProductToolbar, SelectBox, TABLES, normalizeProducts, number, readPage, scopedNodes,
  type Field, type FilterTree, type Row, type Sorts,
} from "./ProjectSkuPicker";
import {
  CenteredPopup, GRAIN_LABEL, PROJECT_PRIORITIES, HealthChip, Owner, OwnerSelect, PriorityGlyph, ProjectFooter,
  ProjectRequestError, StatusPicker, StatusPill, call, clampPercent, draftOf, enc, messageOf, pictureSrc, text,
  type Detail, type Priority, type Project, type ProjectDraft, type ProjectGrain,
  type ProjectInput, type Status, type Target,
} from "./ProjectsShared";
import "../../styles/sdlc85/project-overview.css";

type ProjectPerson = { username: string; name: string };
type OverviewProject = Project & { contributors?: ProjectPerson[] };
type OverviewDraft = ProjectDraft & { contributors: string[] };
type OverviewInput = ProjectInput & { contributors?: string[] };
type OverviewField = keyof OverviewDraft | "targets";
type TargetPair = { grain: ProjectGrain; key: string };
type RemoveRefusal = { grain?: ProjectGrain; key: string | null; reason: string };
type RemoveAnswer = { project: Project; targets: Target[]; refused?: RemoveRefusal[]; cause?: string };
type RemoveOutcome = { refused: RemoveRefusal[] } | { error: string };

function overviewDraftOf(project: OverviewProject): OverviewDraft {
  return { ...draftOf(project), contributors: (project.contributors ?? []).map(person => person.username).sort() };
}

/** The product row a Projects cell opened from. It scopes the SKU list and the Dashboard until cleared. */
export type RowScope = { grain: ProjectGrain; key: string };

/** A SKU target matches by key, an ASIN by `asin` and a Parent ASIN by `parentAsin`. ASIN keys ignore case. */
const ROW_SCOPE_VALUE: Record<ProjectGrain, (target: Target) => string> = {
  sku: target => target.grain === "sku" ? text(target.key) : text(target.sku),
  asin: target => target.grain === "asin" ? text(target.key) : text(target.asin),
  parent_asin: target => target.grain === "parent_asin" ? text(target.key) : text(target.parentAsin),
};

export function inRowScope(target: Target, scope: RowScope) {
  const value = ROW_SCOPE_VALUE[scope.grain](target);
  return scope.grain === "sku" ? value === scope.key : value.toUpperCase() === scope.key.toUpperCase();
}

/** The row filter chip wears the filter kit's active Filter look. Its clear control removes the scope. */
export function RowScopeChip({ scope, onClear }: { scope: RowScope; onClear: () => void }) {
  const name = GRAIN_LABEL[scope.grain];
  const label = `${name} is ${scope.key}`;
  return <div className="lp-proj-section-head">
    <span className="cg-tb-btn cg-tb-btn--filter is-active" role="group" aria-label={`Filter: ${label}`}
      data-row-scope={scope.grain}>
      <Funnel size={16} aria-hidden="true" />
      <span className="lp-proj-clip" title={label}>{label}</span>
      <button type="button" className="lp-proj-person-remove" aria-label={`Clear ${name} filter`} title="Clear filter"
        onClick={onClear}><X size={12} aria-hidden="true" /></button>
    </span>
  </div>;
}

type PeoplePickerProps = {
  label: string; selected: string[]; people: ProjectPerson[]; loading: boolean; error: string;
  disabled: boolean; active: boolean; multiple?: boolean; caption: string; onRetry: () => void;
  onChange: (selected: string[]) => void;
};

function PeoplePicker(props: PeoplePickerProps) {
  const [open, setOpen] = useState(false);
  const trigger = useRef<HTMLButtonElement>(null);
  const popupId = useId();
  const visible = open && props.active;
  useEffect(() => { if (!props.active) setOpen(false); }, [props.active]);
  return <div className="lp-proj-people-picker">
    <button ref={trigger} type="button" className="lp-proj-setup-edit" disabled={props.disabled}
      data-empty={!props.selected.length || undefined} aria-label={`Choose ${props.label.toLowerCase()}`}
      aria-haspopup="dialog" aria-expanded={visible} aria-controls={visible ? popupId : undefined}
      onClick={() => setOpen(value => !value)}>{props.caption}</button>
    {visible ? <PeopleOptions {...props} id={popupId} trigger={trigger.current} onClose={() => setOpen(false)} /> : null}
  </div>;
}

function PeopleOptions({ id, trigger, onClose, ...props }: PeoplePickerProps & {
  id: string; trigger: HTMLButtonElement | null; onClose: () => void;
}) {
  const panel = useRef<HTMLDivElement>(null);
  const search = useRef<HTMLInputElement>(null);
  const [query, setQuery] = useState("");
  const term = query.trim().toLocaleLowerCase();
  const matches = props.people.filter(person => `${person.name} ${person.username}`.toLocaleLowerCase().includes(term));
  useEscapeClose(true, onClose, { container: () => panel.current });
  useLayoutEffect(() => {
    search.current?.focus({ preventScroll: true });
    panel.current?.scrollIntoView({ block: "nearest" });
    return () => { if (trigger?.isConnected) trigger.focus({ preventScroll: true }); };
  }, [trigger]);
  useEffect(() => {
    const dismiss = (event: PointerEvent) => {
      if (event.target instanceof Node && !panel.current?.contains(event.target) && !trigger?.contains(event.target)) onClose();
    };
    document.addEventListener("pointerdown", dismiss, true);
    return () => document.removeEventListener("pointerdown", dismiss, true);
  }, [onClose, trigger]);
  return <div ref={panel} id={id} className="lp-proj-people-popover" role="dialog"
    aria-label={`Choose ${props.label.toLowerCase()}`} aria-busy={props.loading}>
    <div className="lp-proj-people-search">
      <input ref={search} type="search" className="lp-proj-input" aria-label="Search people"
        placeholder="Search people" value={query} onChange={event => setQuery(event.target.value)}
        onKeyDown={event => { if (event.key === "Enter") event.preventDefault(); }} />
      <button type="button" className="lp-proj-setup-edit" onClick={onClose}>Done</button>
    </div>
    {props.loading ? <p className="lp-proj-muted" role="status">Loading people…</p> : props.error ? <div>
      <p className="lp-proj-error" role="alert">{props.error}</p>
      <button type="button" className="lp-proj-setup-edit" disabled={props.disabled} onClick={props.onRetry}>Retry</button>
    </div> : <ul className="lp-proj-people-options" aria-label="Workspace people">
      {!props.multiple ? <li><label className="lp-proj-person-option">
        <input type="radio" name={id} checked={!props.selected.length} disabled={props.disabled}
          onChange={() => { props.onChange([]); onClose(); }} />
        <span>No owner</span>
      </label></li> : null}
      {matches.map(person => <li key={person.username}><label className="lp-proj-person-option">
        <input type={props.multiple ? "checkbox" : "radio"} name={id}
          checked={props.selected.includes(person.username)} disabled={props.disabled}
          onChange={() => {
            props.onChange(props.multiple
              ? props.selected.includes(person.username) ? props.selected.filter(username => username !== person.username)
                : [...props.selected, person.username].sort()
              : [person.username]);
            if (!props.multiple) onClose();
          }} />
        <Owner name={person.name} compact />
        <span className="lp-proj-person-name"><span>{person.name}</span>
          <span className="lp-proj-muted">{person.username}</span></span>
      </label></li>)}
    </ul>}
    {!props.loading && !props.error && !matches.length
      ? <p className="lp-proj-muted" role="status">{term ? "No people match" : "No people available"}</p> : null}
  </div>;
}

function PeopleStack({ people }: { people: Array<ProjectPerson & { role: string }> }) {
  const shown = people.slice(0, 3);
  const remaining = people.slice(shown.length);
  return <div className="lp-proj-people-stack" role="group" aria-label={`${people.length} project people`}>
    {shown.map(person => <span key={person.username} className="lp-proj-person-avatar" data-role={person.role}
      role="img" aria-label={`${person.name}, ${person.role}`}
      title={`${person.name}, ${person.role}`}><Owner name={person.name} compact /></span>)}
    {remaining.length ? <span className="lp-proj-people-count" role="img" aria-label={`${remaining.length} more people`}
      title={remaining.map(person => `${person.name}, ${person.role}`).join("\n")}>+{remaining.length}</span> : null}
  </div>;
}

function SetupRow({ field, label, error, children, readOnly = false }: {
  field: string; label: string; error?: string; children: ReactNode; readOnly?: boolean;
}) {
  const labelId = useId();
  const errorId = `${labelId}-error`;
  return <div className="lp-proj-setup-row" data-field={field} data-read-only={readOnly || undefined}
    data-error={Boolean(error) || undefined} role="group" aria-labelledby={labelId}
    aria-describedby={error ? errorId : undefined}>
    <span className="lp-proj-setup-label" id={labelId}>{label}</span>
    <div className="lp-proj-setup-value">
      {children}
      {error ? <p id={errorId} className="lp-proj-error lp-proj-setup-error" role="alert">{error}</p> : null}
    </div>
  </div>;
}

function SetupDate({ label, value, canEdit, busy, onChange, max, hint, invalid }: {
  label: string; value: string | null; canEdit: boolean; busy: boolean;
  onChange: (value: string | null) => void; max?: string; hint?: string; invalid?: boolean;
}) {
  const [editing, setEditing] = useState(false);
  const trigger = useRef<HTMLButtonElement>(null);
  const caption = value ? new Date(`${value}T00:00:00`).toLocaleDateString("en-US",
    { month: "short", day: "numeric", year: "numeric" }) : "Not set";
  if (!canEdit) return value ? <time dateTime={value}>{caption}</time> : <span className="lp-proj-muted">Not set</span>;
  return editing ? <input className="lp-proj-setup-input" type="date" aria-label={label}
    value={value ?? ""} disabled={busy} max={max} autoFocus aria-invalid={invalid || undefined}
    onKeyDown={event => {
      if (event.key === "Escape") {
        event.preventDefault(); event.stopPropagation(); setEditing(false);
        window.requestAnimationFrame(() => trigger.current?.focus());
      } else if (event.key === "Enter") {
        event.preventDefault(); setEditing(false);
        window.requestAnimationFrame(() => trigger.current?.focus());
      }
    }}
    onChange={event => onChange(event.target.value || null)} onBlur={() => setEditing(false)} />
    : <button ref={trigger} type="button" className="lp-proj-setup-edit lp-proj-date-edit" data-empty={!value || undefined}
        aria-label={`${value ? "Edit" : "Add"} ${label.toLowerCase()}`} title={hint}
        disabled={busy} onClick={() => setEditing(true)}>
        <CalendarBlank size={16} aria-hidden="true" />
        {value ? caption : `Add ${label.toLowerCase()}`}
      </button>;
}

function ProjectDeleteDialog({ name, busy, error, onCancel, onConfirm }: {
  name: string; busy: boolean; error: string; onCancel: () => void; onConfirm: () => void;
}) {
  const [typedName, setTypedName] = useState("");
  const inputId = useId();
  const dismiss = () => { if (!busy) onCancel(); };
  return <CenteredPopup title="Delete project" size="narrow" className="lp-proj-delete-popup" onClose={dismiss}>
    <form className="lp-proj-delete-form" aria-label="Confirm project deletion" aria-busy={busy}
      onSubmit={event => {
        event.preventDefault();
        event.stopPropagation();
        if (!busy && typedName === name) onConfirm();
      }}>
      <p id={`${inputId}-hint`} className="lp-proj-muted">This permanently deletes the project.</p>
      <label className="lp-proj-delete-name" htmlFor={inputId}>
        <span>Type <strong>{name}</strong> to confirm</span>
        <input id={inputId} type="text" className="lp-proj-input" value={typedName} disabled={busy}
          autoComplete="off" autoCapitalize="none" spellCheck={false}
          aria-describedby={`${inputId}-hint ${inputId}-feedback`}
          onChange={event => setTypedName(event.target.value)} />
      </label>
      <p id={`${inputId}-feedback`} className="lp-proj-delete-feedback" role={error ? "alert" : "status"}>
        {error || (busy ? "Deleting project…" : "")}
      </p>
      <div className="lp-proj-delete-actions">
        <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={busy} onClick={dismiss}>Cancel</button>
        <button type="submit" className="lp-proj-btn lp-proj-delete-button" disabled={busy || typedName !== name}>Delete</button>
      </div>
    </form>
  </CenteredPopup>;
}

export default function ProjectOverview({ id, detail, canEdit: mayEdit, onChanged, onDeleted, onCancel,
  error, setError, setDetail, setTick, formId, active, rowScope = null, onClearRowScope, pdp }: {
  id: string; detail: Detail; canEdit: boolean; onChanged: () => void; onDeleted: () => void; onCancel: () => void;
  error: string; setError: Dispatch<SetStateAction<string>>; setDetail: Dispatch<SetStateAction<Detail | null>>;
  setTick: Dispatch<SetStateAction<number>>; formId: string; active: boolean;
  rowScope?: RowScope | null; onClearRowScope?: () => void;
  pdp?: ProjectPdp;
}) {
  const [draft, setDraft] = useState<OverviewDraft>(() => overviewDraftOf(detail.project));
  const [people, setPeople] = useState<ProjectPerson[]>([]);
  const [peopleLoading, setPeopleLoading] = useState(true);
  const [peopleError, setPeopleError] = useState("");
  const [peopleAttempt, setPeopleAttempt] = useState(0);
  const [busy, setBusy] = useState(false);
  const [adding, setAdding] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const [editingDescription, setEditingDescription] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<OverviewField, string>>>({});
  const [saved, setSaved] = useState(false);
  const [taskCount, setTaskCount] = useState<number | null>(null);
  const writing = useRef(false);

  const taskProjectChanged = useCallback((change: Partial<Project>) => {
    setDetail(current => current ? { ...current, project: { ...current.project, ...change } } : current);
    const progress = change.progress;
    if (typeof progress === "number") setDraft(current => ({ ...current, progress }));
  }, [setDetail]);
  const tasksLoaded = useCallback((summary: { count: number; progress: number | null }) => {
    setTaskCount(summary.count);
    if (summary.progress !== null) taskProjectChanged({ progress: summary.progress });
  }, [taskProjectChanged]);
  const taskChanged = () => { setTick(value => value + 1); onChanged(); };

  const write = useCallback(async (path: string, method: string, body: unknown, after?: () => void,
    fields?: OverviewField[]) => {
    if (writing.current || !mayEdit || !detail?.canEdit) return;
    writing.current = true;
    setBusy(true);
    const fallback = method === "DELETE" ? "The project was not deleted." : "The change was not saved.";
    if (method === "DELETE") setError("");
    try {
      const answer = await call<{ project?: Project; targets?: Target[] }>(path, { method, body }, fallback);
      if (answer.project) {
        const project = answer.project;
        setDetail((current) => current ? { ...current, project, targets: answer.targets ?? current.targets } : current);
        if (method === "PATCH") setDraft(overviewDraftOf(project));
      }
      setError("");
      setFieldErrors({});
      if (method === "PATCH") setSaved(true);
      if (after) after(); else setTick((value) => value + 1);
      onChanged();
    } catch (reason) {
      const message = messageOf(reason, fallback);
      if (fields?.length) {
        const dateFields = fields.filter(field => field === "startOn" || field === "targetOn");
        const namedField = fields.find(field => message.toLowerCase().includes(
          ({ startOn: "start_on", targetOn: "target_on", completedOn: "completed_on",
            ownerUsername: "owner", contributors: "contribut" } as Partial<Record<OverviewField, string>>)[field] ?? field.toLowerCase()));
        const affected = message === "Target date cannot be before the start date." && dateFields.length
          ? dateFields : namedField ? [namedField] : fields;
        setFieldErrors(Object.fromEntries(affected.map(field => [field, message])));
        setError("");
      } else setError(message);
      if (reason instanceof ProjectRequestError && reason.status === 403) {
        setDetail((current) => current ? { ...current, canEdit: false } : current);
        onChanged();
      }
    } finally {
      writing.current = false;
      setBusy(false);
    }
  }, [detail?.canEdit, mayEdit, onChanged, setDetail, setError, setTick]);

  const patch = useCallback((change: OverviewInput, fields: Array<keyof OverviewDraft>) =>
    write(`/${enc(id)}`, "PATCH", change, undefined, fields), [id, write]);

  // One POST carries every selected target. A key still linked in the answer is a refusal.
  const removeTargets = useCallback(async (pairs: TargetPair[]): Promise<RemoveOutcome | null> => {
    if (writing.current || !mayEdit || !detail?.canEdit || !pairs.length) return null;
    writing.current = true;
    setBusy(true);
    const fallback = "Products were not removed.";
    try {
      if (pdp) {
        if (!pdp.detail?.canEdit) throw new Error("The workflow is unavailable. Reload the project.");
        pdp.accept((await removeItems(id, pairs.map(pair => pair.key))).workflow);
        setTick(value => value + 1);
        return { refused: [] };
      }
      const answer = await call<RemoveAnswer>(`/${enc(id)}/targets/remove`,
        { method: "POST", body: { targets: pairs } }, fallback);
      if (!answer?.project || !Array.isArray(answer.targets)) throw new Error("The remove answer is incomplete. Reload the project.");
      setDetail(current => current ? { ...current, targets: answer.targets, project: answer.project,
        cause: answer.cause } : current);
      setError("");
      setFieldErrors(current => ({ ...current, targets: undefined }));
      setTick(value => value + 1);
      onChanged();
      const named = Array.isArray(answer.refused) ? answer.refused.filter(item => item && typeof item.reason === "string") : [];
      const namedKeys = new Set(named.map(item => item.key));
      const linked = new Set(answer.targets.map(target => `${target.grain}:${target.key}`));
      const kept = pairs.filter(pair => linked.has(`${pair.grain}:${pair.key}`) && !namedKeys.has(pair.key))
        .map(pair => ({ ...pair, reason: "Still linked after removal" }));
      return { refused: [...named, ...kept] };
    } catch (reason) {
      if (reason instanceof ProjectRequestError && reason.status === 403) {
        setDetail(current => current ? { ...current, canEdit: false } : current);
        onChanged();
      }
      return { error: messageOf(reason, fallback) };
    } finally {
      writing.current = false;
      setBusy(false);
    }
  }, [detail?.canEdit, id, mayEdit, onChanged, setDetail, setError, setTick, pdp]);

  const { project, targets } = detail;
  const canEdit = mayEdit && detail.canEdit && (!pdp || Boolean(pdp.detail?.canEdit));
  const deleteOpen = confirming && canEdit && active;
  useEffect(() => {
    if (!canEdit || !active) { setConfirming(false); setAdding(false); }
  }, [canEdit, active]);
  // Readers load names too: the owners door admits every reader, and assignees show by name.
  useEffect(() => {
    const controller = new AbortController();
    setPeopleLoading(true);
    setPeopleError("");
    void call<{ owners: ProjectPerson[] }>("/owners", { signal: controller.signal }, "People did not load.")
      .then(answer => { if (!controller.signal.aborted) setPeople(answer.owners); })
      .catch(reason => { if (!controller.signal.aborted) setPeopleError(messageOf(reason, "People did not load.")); })
      .finally(() => { if (!controller.signal.aborted) setPeopleLoading(false); });
    return () => controller.abort();
  }, [canEdit, peopleAttempt]);

  const display = canEdit ? draft : project;
  const progress = Number.isFinite(display.progress) ? clampPercent(display.progress) : 0;
  const summaryOwner = project.owner || project.ownerUsername || null;
  const savedContributors = (project as OverviewProject).contributors ?? [];
  const identities = new Map([...savedContributors, ...people].map(person => [person.username, person]));
  const ownerName = (display.ownerUsername ? identities.get(display.ownerUsername)?.name : null)
    || display.owner || (display.ownerUsername === project.ownerUsername ? project.owner : null) || display.ownerUsername;
  const contributors = canEdit
    ? draft.contributors.map(username => identities.get(username) ?? { username, name: username }) : savedContributors;
  const projectPeople = [
    ...(ownerName ? [{ username: display.ownerUsername || "__legacy_owner__", name: ownerName, role: "Owner" }] : []),
    ...contributors.filter(person => person.username !== display.ownerUsername).map(person => ({ ...person, role: "Contributor" })),
  ];
  const pickerProps = { people, loading: peopleLoading, error: peopleError, disabled: busy, active,
    onRetry: () => setPeopleAttempt(value => value + 1) };
  const dirty = JSON.stringify(draft) !== JSON.stringify(overviewDraftOf(project));
  // A row scope applies only with its clear control, so the list never narrows without a way back.
  const scope = rowScope && onClearRowScope ? { ...rowScope, clear: onClearRowScope } : null;
  const scopedCount = scope ? targets.filter(target => inRowScope(target, scope)).length : null;
  const set =<K extends keyof OverviewDraft>(key: K, value: OverviewDraft[K]) => {
    setSaved(false);
    setFieldErrors(current => ({ ...current, [key]: undefined }));
    setDraft(current => current ? { ...current, [key]: value,
      ...(key === "status" && value !== "Completed" ? { completedOn: null } : {}),
      ...(key === "completedOn" && value ? { status: "Completed" as Status } : {}),
    } : current);
  };
  const save = (event: FormEvent) => {
    event.preventDefault();
    if (!canEdit || !dirty) return;
    const name = draft.name.trim();
    if (!name) { setFieldErrors({ name: "Name the project." }); return; }
    if (!Number.isInteger(draft.progress) || draft.progress < 0 || draft.progress > 100) {
      setFieldErrors({ progress: "Enter a whole percent from 0 to 100." }); return;
    }
    const today = new Date().toISOString().slice(0, 10);
    if (draft.completedOn && draft.completedOn > today) {
      setFieldErrors({ completedOn: "Choose today or an earlier date." }); return;
    }
    if (project.completedOn && draft.status === "Completed" && !draft.completedOn) {
      setFieldErrors({ completedOn: "Choose a completed date, or change Status to reopen the project." }); return;
    }
    const original = overviewDraftOf(project);
    const changed = (Object.keys(draft) as Array<keyof OverviewDraft>)
      .filter(key => JSON.stringify(draft[key]) !== JSON.stringify(original[key]));
    const fields = Object.fromEntries(changed.filter(key => key !== "owner").map(key => [key, draft[key]])) as OverviewInput;
    if (changed.includes("owner")) fields.ownerUsername = draft.ownerUsername;
    if (changed.includes("name")) fields.name = name;
    if (changed.includes("notes")) fields.notes = draft.notes?.trim() || null;
    setSaved(false);
    setFieldErrors({});
    void patch(fields, changed);
  };

  return <form id={formId} className="lp-proj-detail lp-proj-accent" data-status={display.status}
    data-can-edit={canEdit ? "true" : "false"} onSubmit={save} aria-label="Project overview" aria-busy={busy} noValidate>
    <div className="lp-proj-main">
      <div data-field="name">
        <div className="lp-proj-overview-heading">
          <h2 className="lp-proj-title" tabIndex={-1} aria-label={display.name || "Untitled project"}>
            {canEdit ? <>
              <span className="lp-proj-title-measure" aria-hidden="true">{draft.name || " "}</span>
              <input className="lp-proj-title-input" value={draft.name} aria-label="Project name"
              aria-invalid={Boolean(fieldErrors.name)} disabled={busy} required maxLength={300}
              aria-describedby={fieldErrors.name ? `${formId}-name-error` : undefined}
              onChange={event => set("name", event.target.value)} />
            </> : project.name}
          </h2>
          <StatusPill status={display.status} progress={progress} />
          <PeopleStack people={projectPeople} />
        </div>
        {fieldErrors.name ? <p id={`${formId}-name-error`} className="lp-proj-error lp-proj-setup-error" role="alert">
          {fieldErrors.name}
        </p> : null}
      </div>
      {scope ? <RowScopeChip scope={scope} onClear={scope.clear} /> : null}

      <section className="lp-proj-status-card" aria-label="Project status">
        <h3 className="lp-proj-status-card-heading">Project status: {display.status.toLowerCase()}</h3>
        <div className="lp-proj-status-card-summary">
          <h4>Summary</h4>
          <p>{progress}% complete. {project.health ? `Health is ${project.health.toLowerCase()}.` : "Health is not set."}</p>
        </div>
        <footer className="lp-proj-status-card-footer">
          <Owner name={summaryOwner} compact />
          <div className="lp-proj-status-card-metadata">
            <span className="lp-proj-status-card-owner">Owner: {summaryOwner || "No owner"}</span>
            <span className="lp-proj-status-card-updated">Updated: {project.updatedAt
              ? <time dateTime={project.updatedAt} title={project.updatedAt}>
                  {new Date(project.updatedAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                </time>
              : "Not available"}</span>
          </div>
        </footer>
      </section>

      <div className="lp-proj-setup-fields">
        {project.type === "pdp" && pdp ? <PdpOverviewRows pdp={pdp} /> : null}
        <SetupRow field="status" label="Status" error={fieldErrors.status} readOnly={!canEdit}>
          {canEdit
            ? <StatusPicker value={draft.status} disabled={busy} onChange={value => set("status", value)} />
            : <StatusPill status={project.status} progress={progress} />}
        </SetupRow>
        <SetupRow field="priority" label="Priority" error={fieldErrors.priority} readOnly={!canEdit}>
          <div className="lp-proj-setup-inline"><PriorityGlyph priority={display.priority} />
            {canEdit
              ? <select className="lp-proj-setup-input" aria-label="Priority" value={draft.priority} disabled={busy}
                  data-empty={draft.priority === "No priority" || undefined} aria-invalid={Boolean(fieldErrors.priority)}
                  onChange={(event) => set("priority", event.target.value as Priority)}>
                  {PROJECT_PRIORITIES.map((value) => <option key={value} value={value}>{value === "No priority" ? "Add priority" : value}</option>)}
                </select>
              : <span className={project.priority === "No priority" ? "lp-proj-muted" : undefined}>{project.priority}</span>}
          </div>
        </SetupRow>
        <SetupRow field="ownerUsername" label="Owner" error={fieldErrors.ownerUsername || fieldErrors.owner} readOnly={!canEdit}>
          {canEdit ? <PeoplePicker {...pickerProps} label="Owner" selected={draft.ownerUsername ? [draft.ownerUsername] : []}
            caption={ownerName || "Add owner"}
            onChange={values => { set("ownerUsername", values[0] ?? null); set("owner", null); }} /> : project.owner || project.ownerUsername
            ? <Owner name={project.owner || project.ownerUsername || null} /> : <span className="lp-proj-muted">No owner</span>}
        </SetupRow>
        {project.type === "pdp" && pdp ? <PdpApprovalRow pdp={pdp} canEdit={canEdit} /> : null}
        <SetupRow field="contributors" label="Contributors" error={fieldErrors.contributors} readOnly={!canEdit}>
          <div className="lp-proj-contributors">
            {contributors.map(person => <span key={person.username} className="lp-proj-contributor">
              <Owner name={person.name} />
              {canEdit ? <button type="button" className="lp-proj-person-remove" disabled={busy}
                aria-label={`Remove ${person.name} from contributors`}
                onClick={() => set("contributors", draft.contributors.filter(username => username !== person.username))}>
                <X size={12} aria-hidden="true" />
              </button> : null}
            </span>)}
            {canEdit ? <PeoplePicker {...pickerProps} label="Contributors" selected={draft.contributors} multiple
              caption="Add people" onChange={values => set("contributors", values)} />
              : !contributors.length ? <span className="lp-proj-muted">No contributors</span> : null}
          </div>
        </SetupRow>
        <div className="lp-proj-date-range" role="group" aria-label="Start to target">
          {([ ["startOn", "Start"], ["targetOn", "Target"] ] as const)
            .map(([field, label], index) => <div key={field} className="lp-proj-date-property">
              {index === 1 ? <ArrowRight size={16} className="lp-proj-date-arrow" aria-hidden="true" /> : null}
              <SetupRow field={field} label={label} error={fieldErrors[field]} readOnly={!canEdit}>
                <SetupDate label={`${label} date`} value={display[field]} canEdit={canEdit} busy={busy}
                  invalid={Boolean(fieldErrors[field])} onChange={value => set(field, value)} />
              </SetupRow>
            </div>)}
        </div>
        <SetupRow field="completedOn" label="Completed" error={fieldErrors.completedOn} readOnly={!canEdit}>
          <SetupDate label="Completed date" value={display.completedOn} canEdit={canEdit} busy={busy}
            max={new Date().toISOString().slice(0, 10)} invalid={Boolean(fieldErrors.completedOn)}
            hint={display.status !== "Completed" ? "Also sets Status to Completed" : undefined}
            onChange={value => set("completedOn", value)} />
        </SetupRow>
        <SetupRow field="progress" label="Progress" error={fieldErrors.progress} readOnly={!canEdit || taskCount !== 0}>
          {canEdit && taskCount === 0 ? <div className="lp-proj-setup-inline">
            <input className="lp-proj-setup-input lp-proj-setup-percent" type="number" aria-label="Progress"
              min={0} max={100} step={1} value={Number.isNaN(draft.progress) ? "" : draft.progress} disabled={busy}
              aria-invalid={Boolean(fieldErrors.progress)}
              onChange={event => set("progress", event.target.valueAsNumber)} /><span>%</span>
          </div> : <span title={taskCount ? "Calculated from active leaf tasks" : undefined}>{progress}%</span>}
        </SetupRow>
        <SetupRow field="health" label="Health" readOnly>
          {project.health ? <HealthChip health={project.health} /> : <span className="lp-proj-muted">Not set</span>}
        </SetupRow>
        <SetupRow field="notes" label="Description" error={fieldErrors.notes} readOnly={!canEdit}>
          {canEdit ? draft.notes || editingDescription
            ? <textarea className="lp-proj-setup-input lp-proj-setup-description" aria-label="Description"
                placeholder="Add description" value={draft.notes ?? ""} rows={4} disabled={busy}
                autoFocus={editingDescription} aria-invalid={Boolean(fieldErrors.notes)}
                onChange={event => set("notes", event.target.value)}
                onBlur={() => setEditingDescription(false)} />
            : <button type="button" className="lp-proj-setup-edit" data-empty disabled={busy}
                onClick={() => setEditingDescription(true)}>Add description</button>
            : <p className="lp-proj-notes-text">{project.notes || <span className="lp-proj-muted">Not set</span>}</p>}
        </SetupRow>
      </div>

      <ProjectTasks projectId={id} canEdit={canEdit} active={active} disabled={busy}
        people={people} peopleLoading={peopleLoading} peopleError={peopleError}
        onRetryPeople={() => setPeopleAttempt(value => value + 1)} onTasksLoaded={tasksLoaded}
        onProjectChanged={taskProjectChanged} onChanged={taskChanged}
        onForbidden={() => setDetail(current => current ? { ...current, canEdit: false } : current)} />

      {error && !deleteOpen ? <p className="lp-proj-error" role="alert">{error}</p> : null}
      {detail.cause ? <p className="lp-proj-muted" role="status">{detail.cause}</p> : null}
      <SetupRow field="targets" label="SKUs" error={fieldErrors.targets} readOnly={!canEdit}>
      <section className="lp-proj-section" aria-label="SKUs">
        <div className="lp-proj-section-head">
          <span className="lp-proj-muted">{!targets.length ? "None linked" : scopedCount !== null
            ? `${number(scopedCount)} of ${number(targets.length)} linked` : `${number(targets.length)} linked`}</span>
          {canEdit && !adding
            ? <button type="button" className="lp-proj-setup-edit" data-empty disabled={busy} onClick={() => setAdding(true)}>Add SKUs</button>
            : null}
        </div>
        {canEdit && active && adding
          ? <ProjectSkuPicker projectId={id} existing={targets} canEdit={canEdit && !busy} onClose={() => setAdding(false)} pdp={pdp}
              onAdded={answer => {
                setDetail(current => current ? { ...current, project: answer.project, targets: answer.targets,
                  cause: answer.cause } : current);
                setFieldErrors(current => ({ ...current, targets: undefined }));
                setTick(value => value + 1);
                onChanged();
              }} />
          : null}
        {targets.length
          ? <ProjectSkuList targets={targets} scope={scope} canEdit={canEdit} busy={busy} active={active}
              onRemove={removeTargets} pdp={pdp} />
          : null}
      </section>
      </SetupRow>
      <div className="lp-proj-setup-footer" aria-label="Project timestamps">
        {([ ["createdAt", "Created"], ["updatedAt", "Updated"] ] as const).map(([field, label]) =>
          <SetupRow key={field} field={field} label={label} readOnly>
            {project[field] ? <time dateTime={project[field]} title={project[field]}>
              {new Date(project[field]).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
            </time> : <span>Not available</span>}
          </SetupRow>)}
      </div>
      {saved && !dirty ? <span className="lp-proj-muted" role="status">Changes saved</span> : null}
    </div>

    <aside className="lp-proj-side">
      <ProjectFooter>{active ? <div className="lp-proj-save">
        <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={busy} onClick={onCancel}>Cancel</button>
        {canEdit ? <button type="submit" form={formId} className="lp-proj-btn lp-proj-btn-primary" disabled={busy || !dirty}>
          {busy ? "Saving…" : "Save changes"}
        </button> : null}
        {canEdit && dirty ? <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={busy}
          onClick={() => { setDraft(overviewDraftOf(project)); setError(""); setFieldErrors({}); setSaved(false); }}>Discard changes</button> : null}
      </div> : null}</ProjectFooter>
      {canEdit
        ? <div className="lp-proj-delete">
            <button type="button" className="lp-proj-btn lp-proj-delete-button" disabled={busy}
              aria-haspopup="dialog" aria-expanded={deleteOpen}
              onClick={() => { setError(""); setConfirming(true); }}>Delete project</button>
          </div>
        : null}
    </aside>
    {deleteOpen ? <ProjectDeleteDialog key={project.name} name={project.name} busy={busy} error={error}
      onCancel={() => setConfirming(false)}
      onConfirm={() => void write(`/${enc(id)}`, "DELETE", undefined, onDeleted)} /> : null}
  </form>;

}

type LinkedView = { signature: string; linked: Set<string>; keys: string[]; values: Map<string, Row> };
type ListRow = { key: string; target: Target; values: Row | null };
type ReadFailure = { message: string; forbidden: boolean };

/** Identities the project detail already carries, so grouping by them needs no row read. */
const TARGET_VALUES = new Map<string, (target: Target) => string>([
  ["sku", target => text(target.sku)], ["asin", target => text(target.asin)],
  ["parent_asin", target => text(target.parentAsin)], ["title", target => text(target.title)],
]);

const LIST_COLUMNS: Record<ProjectGrain, Array<{ key: string; label: string; value: (target: Target) => string }>> = {
  sku: [{ key: "sku", label: "SKU", value: target => target.key },
    { key: "asin", label: "Child ASIN", value: target => text(target.asin) },
    { key: "parent_asin", label: "Parent ASIN", value: target => text(target.parentAsin) }],
  asin: [{ key: "asin", label: "Child ASIN", value: target => target.key },
    { key: "parent_asin", label: "Parent ASIN", value: target => text(target.parentAsin) }],
  parent_asin: [{ key: "parent_asin", label: "Parent ASIN", value: target => target.key }],
};

/** The text a list search matches: key, title, SKU, Child ASIN and Parent ASIN, lower case. */
const searchTextOf = (row: ListRow) => [row.key, row.target.title, row.target.sku, row.target.asin, row.target.parentAsin,
  row.values?.title, row.values?.sku, row.values?.asin, row.values?.parent_asin]
  .map(value => text(value)).join("\n").toLocaleLowerCase();

const failureOf = (reason: unknown, fallback: string): ReadFailure => ({ message: messageOf(reason, fallback),
  forbidden: reason instanceof ProjectRequestError && [401, 403].includes(reason.status) });

/** Page the server's filtered, ordered rows until every linked key is placed or the rows end. */
async function readLinked(table: string, grain: ProjectGrain, tree: FilterTree, order: Sorts, linked: Set<string>,
  abort: AbortSignal): Promise<Pick<LinkedView, "keys" | "values">> {
  const keys: string[] = [];
  const values = new Map<string, Row>();
  const visited = new Set<string | number>();
  let cursor: string | number | null = null;
  while (true) {
    const page = await readPage(table, tree, order, cursor, abort);
    for (const row of normalizeProducts(page.rows, grain)) {
      const key = text(row[grain]);
      if (linked.has(key) && !values.has(key)) { keys.push(key); values.set(key, row); }
    }
    if (page.next_cursor === null || keys.length === linked.size) return { keys, values };
    if (page.next_cursor === cursor || visited.has(page.next_cursor)) {
      throw new Error("The next product page did not advance. Try again.");
    }
    if (cursor !== null) visited.add(cursor);
    cursor = page.next_cursor;
  }
}

function ProjectSkuList({ targets: linked, scope, canEdit, busy, active, onRemove, pdp }: {
  targets: Target[]; scope: (RowScope & { clear: () => void }) | null; canEdit: boolean; busy: boolean; active: boolean;
  onRemove: (pairs: TargetPair[]) => Promise<RemoveOutcome | null>;
  pdp?: ProjectPdp;
}) {
  const id = useId();
  const [chosen, setChosen] = useState<ProjectGrain>("sku");
  // A row scope lists only the targets that match it. Clearing it lists every linked target again.
  const targets = scope ? linked.filter(target => inRowScope(target, scope)) : linked;
  const grains = GRAINS.filter(value => targets.some(target => target.grain === value));
  const grain = grains.includes(chosen) ? chosen : grains[0] ?? "sku";
  const tabbed = grains.length > 1;
  if (scope && !targets.length) return <div className="lp-proj-skus">
    <div className="lp-proj-skus-state" role="status"><span>No linked products match this filter</span>
      <button type="button" className="lp-proj-btn" onClick={scope.clear}>Clear filter</button></div>
  </div>;
  return <div className="lp-proj-skus">
    {tabbed ? <div className="lp-proj-sku-tabs" role="tablist" aria-label="Product type">
      {grains.map((value, index) => <button type="button" key={value} role="tab" id={`${id}-tab-${value}`}
        aria-controls={`${id}-panel`} aria-selected={grain === value} tabIndex={grain === value ? 0 : -1}
        disabled={busy} onClick={() => setChosen(value)} onKeyDown={event => {
          const next = event.key === "ArrowRight" ? (index + 1) % grains.length
            : event.key === "ArrowLeft" ? (index + grains.length - 1) % grains.length
              : event.key === "Home" ? 0 : event.key === "End" ? grains.length - 1 : null;
          if (next === null) return;
          event.preventDefault(); event.stopPropagation();
          setChosen(grains[next]);
          document.getElementById(`${id}-tab-${grains[next]}`)?.focus();
        }}>{GRAIN_LABEL[value]}{" "}<span className="lp-proj-skus-tab-count">
          {number(targets.filter(target => target.grain === value).length)}</span></button>)}
    </div> : null}
    <SkuGrainList key={grain} grain={grain} panelId={`${id}-panel`} tabId={tabbed ? `${id}-tab-${grain}` : null}
      targets={targets.filter(target => target.grain === grain)} canEdit={canEdit} busy={busy} active={active}
      onRemove={onRemove} pdp={pdp} />
  </div>;
}

function SkuGrainList({ grain, panelId, tabId, targets, canEdit, busy, active, onRemove, pdp }: {
  grain: ProjectGrain; panelId: string; tabId: string | null; targets: Target[]; canEdit: boolean;
  busy: boolean; active: boolean; onRemove: (pairs: TargetPair[]) => Promise<RemoveOutcome | null>;
  pdp?: ProjectPdp;
}) {
  const table = TABLES[grain];
  const label = GRAIN_LABEL[grain];
  const plural = `${label}s`;
  const [fields, setFields] = useState<Field[] | null>(null);
  const [fieldsFailure, setFieldsFailure] = useState<ReadFailure | null>(null);
  const [fieldsAttempt, setFieldsAttempt] = useState(0);
  const [filters, setFilters] = useState<FilterTree>(EMPTY_FILTER);
  const [sorts, setSorts] = useState<Sorts>([]);
  const [group, setGroup] = useState<string | null>(null);
  const [view, setView] = useState<LinkedView | null>(null);
  const [failure, setFailure] = useState<ReadFailure & { signature: string } | null>(null);
  const [attempt, setAttempt] = useState(0);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [refused, setRefused] = useState<RemoveRefusal[]>([]);
  const [removeError, setRemoveError] = useState("");
  const [search, setSearch] = useState("");
  const submitting = useRef(false);

  const byKey = useMemo(() => new Map(targets.map(target => [target.key, target])), [targets]);
  const linkedSignature = JSON.stringify(targets.map(target => target.key));
  const tree = useMemo<FilterTree>(() => ({ ...filters, nodes: scopedNodes(filters.nodes, group) }), [filters, group]);
  const order = useMemo<Sorts>(() => group
    ? [{ colId: group, dir: "asc" }, ...sorts.filter(sort => sort.colId !== group)] : sorts, [group, sorts]);
  const filtered = filters.nodes.length > 0;
  const serverOrder = filtered || sorts.length > 0 || (group !== null && !TARGET_VALUES.has(group));
  const signature = JSON.stringify([table, tree, order, attempt]);
  const readFor = view?.linked;
  // A removal keeps the read valid. Any newly linked key needs a fresh read to find its place.
  const stale = serverOrder && (view === null || view.signature !== signature
    || targets.some(target => !readFor?.has(target.key)));
  const failed = stale && failure?.signature === signature ? failure : null;
  const loading = stale && !failed;

  useEffect(() => {
    if (!active || fields !== null) return;
    const controller = new AbortController();
    void readPage(table, EMPTY_FILTER, [], null, controller.signal, 1)
      .then(page => { if (!controller.signal.aborted) { setFields(page.fields); setFieldsFailure(null); } })
      .catch(reason => { if (!controller.signal.aborted) setFieldsFailure(failureOf(reason, "Product fields did not load.")); });
    return () => controller.abort();
  }, [active, table, fields, fieldsAttempt]);

  useEffect(() => {
    if (!stale || !active) return;
    const controller = new AbortController();
    const linked = new Set<string>(JSON.parse(linkedSignature) as string[]);
    void readLinked(table, grain, tree, order, linked, controller.signal)
      .then(answer => { if (!controller.signal.aborted) { setView({ ...answer, linked, signature }); setFailure(null); } })
      .catch(reason => {
        if (!controller.signal.aborted) setFailure({ ...failureOf(reason, `${plural} did not load.`), signature });
      });
    return () => controller.abort();
  }, [stale, active, signature, table, grain, tree, order, linkedSignature, plural]);

  let rows: ListRow[] = targets.map(target => ({ key: target.key, target, values: null }));
  if (serverOrder) {
    const placed = view && view.signature === signature ? view.keys.flatMap(key => {
      const target = byKey.get(key);
      return target ? [{ key, target, values: view.values.get(key) ?? null }] : [];
    }) : [];
    const found = new Set(placed.map(row => row.key));
    // Without a filter every linked target stays listed, even one the product table no longer holds.
    rows = filtered ? placed : [...placed, ...rows.filter(row => !found.has(row.key))];
  }
  if (loading || failed) rows = [];
  // The search narrows the rows already listed. It sends no request and keeps every row it matches.
  const term = search.trim().toLocaleLowerCase();
  if (term) rows = rows.filter(row => searchTextOf(row).includes(term));
  const groupValue = (row: ListRow) => group === null ? ""
    : row.values ? text(row.values[group]) : TARGET_VALUES.get(group)?.(row.target) ?? "";
  const buckets = new Map<string, ListRow[]>();
  for (const row of rows) {
    const value = groupValue(row);
    const bucket = buckets.get(value);
    if (bucket) bucket.push(row); else buckets.set(value, [row]);
  }
  const groups = Array.from(buckets);
  // The server orders grouped rows. A detail-only grouping orders its buckets here, blanks last.
  if (group !== null && !serverOrder) groups.sort(([a], [b]) => a === b ? 0 : !a ? 1 : !b ? -1 : a.localeCompare(b));

  const visibleKeys = rows.map(row => row.key);
  const chosenKeys = visibleKeys.filter(key => selected.has(key));
  const shownSignature = JSON.stringify(visibleKeys);
  const blocked = loading || Boolean(failed);
  // A row the search hides loses its selection, so Remove never acts on a row the user cannot see.
  useEffect(() => {
    if (!term || blocked) return;
    const shown = new Set<string>(JSON.parse(shownSignature) as string[]);
    setSelected(current => Array.from(current).every(key => shown.has(key)) ? current
      : new Set(Array.from(current).filter(key => shown.has(key))));
  }, [term, blocked, shownSignature]);
  const columns = LIST_COLUMNS[grain];
  const span = (canEdit ? 1 : 0) + 1 + columns.length + (pdp ? 2 : 0);
  const resetView = () => { setSelected(new Set()); setRefused([]); setRemoveError(""); };
  const clearView = () => { resetView(); setFilters(EMPTY_FILTER); setSorts([]); setGroup(null); setSearch(""); };
  const viewSet = filtered || sorts.length > 0 || group !== null || selected.size > 0 || search !== "";
  const toggle = (keys: string[], checked: boolean) => setSelected(current => {
    const next = new Set(current);
    for (const key of keys) { if (checked) next.add(key); else next.delete(key); }
    return next;
  });
  const boxFor = (keys: string[], name: string) => {
    const count = keys.filter(key => selected.has(key)).length;
    return <SelectBox checked={keys.length > 0 && count === keys.length} mixed={count > 0 && count < keys.length}
      disabled={busy || !keys.length} label={name} onChange={checked => toggle(keys, checked)} />;
  };

  const remove = async () => {
    if (!canEdit || busy || loading || submitting.current || !chosenKeys.length) return;
    submitting.current = true;
    setRefused([]); setRemoveError("");
    try {
      const outcome = await onRemove(chosenKeys.map(key => ({ grain, key })));
      if (!outcome) return;
      if ("error" in outcome) { setRemoveError(outcome.error); return; }
      setRefused(outcome.refused);
      setSelected(new Set(outcome.refused.flatMap(item => item.key ? [item.key] : [])));
    } finally { submitting.current = false; }
  };

  return <div className="lp-proj-skus-body">
    <div className="lp-proj-skus-controls">
      <ProductToolbar table={table} grain={grain} fields={fields ?? []} filters={filters} sorts={sorts} group={group}
        disabled={busy || !fields?.length} label={`${label} list controls`}
        onFilters={next => { resetView(); setFilters(next); }} onSorts={next => { resetView(); setSorts(next); }}
        onGroup={next => { resetView(); setGroup(next); }} />
      {fieldsFailure ? <span className="lp-proj-skus-note" role="status">
        {fieldsFailure.forbidden ? "No access to product fields" : fieldsFailure.message}
        {!fieldsFailure.forbidden ? <button type="button" className="lp-proj-btn lp-proj-btn-quiet"
          onClick={() => { setFieldsFailure(null); setFieldsAttempt(value => value + 1); }}>Retry</button> : null}
      </span> : null}
      <button type="button" className="lp-proj-skus-reset" disabled={busy || !viewSet} onClick={clearView}>
        <ArrowCounterClockwise size={16} aria-hidden="true" />Reset</button>
    </div>
    <label className="lp-proj-skus-search">
      <MagnifyingGlass size={16} aria-hidden="true" />
      <input type="search" value={search} disabled={busy} aria-label={`Search ${plural}`} placeholder={`Search ${plural}`}
        autoComplete="off" spellCheck={false} onChange={event => setSearch(event.target.value)}
        onKeyDown={event => { if (event.key === "Enter") event.preventDefault(); }} />
    </label>
    <div className="lp-proj-skus-results" id={panelId} role={tabId ? "tabpanel" : "region"}
      aria-labelledby={tabId ?? undefined} aria-label={tabId ? undefined : `Linked ${plural}`}
      aria-busy={loading || busy} tabIndex={0}>
      {loading ? <p className="lp-proj-skus-state" role="status">Loading {plural}…</p>
        : failed ? <div className="lp-proj-skus-state" role="alert">
            <span>{failed.forbidden ? "You do not have access to these products" : failed.message}</span>
            <div>{!failed.forbidden ? <button type="button" className="lp-proj-btn"
              onClick={() => setAttempt(value => value + 1)}>Retry</button> : null}
              <button type="button" className="lp-proj-btn lp-proj-btn-quiet" onClick={clearView}>Clear filters</button></div>
          </div>
          : !rows.length ? <div className="lp-proj-skus-state" role="status"><span>No {plural} match</span>
              <button type="button" className="lp-proj-btn" onClick={clearView}>Clear filters</button></div>
            : <table className="lp-proj-sku-table lp-proj-skus-table" aria-label={`Linked ${plural}`}>
                <thead><tr>
                  {canEdit ? <th scope="col" className="lp-proj-skus-check">{boxFor(visibleKeys, `Select all shown ${plural}`)}</th> : null}
                  <th scope="col">Product</th>
                  {columns.map(column => <th scope="col" key={column.key}>{column.label}</th>)}
                  {pdp ? <><th scope="col">Step</th><th scope="col"><span className="lp-proj-sku-sr">Workflow</span></th></> : null}
                </tr></thead>
                <tbody>{groups.map(([value, members]) => <Fragment key={value}>
                  {group !== null ? <tr className="lp-proj-sku-group"><th scope="rowgroup" colSpan={span}>
                    <div className="lp-proj-skus-group-head">
                      {canEdit ? boxFor(members.map(row => row.key), `Select all in ${value || "No value"}`) : null}
                      {value || "No value"}
                      <span>{number(members.length)} {members.length === 1 ? label : plural}</span>
                    </div>
                  </th></tr> : null}
                  {members.map(row => {
                    const picture = pictureSrc(text(row.target.picture) || text(row.values?.picture));
                    return <tr key={row.key} data-selected={(canEdit && selected.has(row.key)) || undefined}>
                      {canEdit ? <td className="lp-proj-skus-check">{boxFor([row.key], `Select ${label} ${row.key}`)}</td> : null}
                      <td><div className="lp-proj-sku-product">
                        {picture ? <img src={picture} alt="" loading="lazy" /> : <span className="lp-proj-sku-picture" aria-hidden="true" />}
                        <span><span>{text(row.target.title) || text(row.values?.title) || row.key}</span></span>
                      </div></td>
                      {columns.map(column => {
                        const shown = column.value(row.target) || text(row.values?.[column.key]);
                        return <td key={column.key} className="lp-proj-sku-code" title={shown || undefined}>
                          {shown || <span className="lp-proj-muted">Not set</span>}</td>;
                      })}
                      {pdp ? <PdpSkuCells pdp={pdp} target={row.target} /> : null}
                    </tr>;
                  })}
                </Fragment>)}</tbody>
              </table>}
    </div>
    {refused.length ? <div className="lp-proj-skus-refusals" role="alert">
      <p>Some {plural} were not removed</p>
      <ul>{refused.map((item, index) => <li key={`${item.key}:${index}`}>
        <strong>{item.key || "Unknown product"}</strong>: {item.reason}
      </li>)}</ul>
    </div> : null}
    {removeError ? <p className="lp-proj-error" role="alert">{removeError}</p> : null}
    <footer className="lp-proj-skus-footer">
      <span aria-live="polite">{canEdit
        ? `${number(chosenKeys.length)} of ${number(rows.length)} selected` : `${number(rows.length)} shown`}</span>
      {canEdit ? <div>
        {chosenKeys.length ? <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={busy}
          onClick={() => setSelected(new Set())}>Clear selection</button> : null}
        <button type="button" className="lp-proj-btn lp-proj-btn-danger" disabled={busy || loading || !chosenKeys.length}
          onClick={() => void remove()}>{chosenKeys.length ? `Remove ${number(chosenKeys.length)}` : "Remove"}</button>
      </div> : null}
    </footer>
  </div>;
}

function PdpSkuCells({ pdp, target }: { pdp: ProjectPdp; target: Target }) {
  const asin = target.grain === "asin" ? target.key : target.asin;
  const item = pdp.detail?.workflow.items.find(item => item.asin === asin);
  return <><td>{item ? <PdpStep item={item} /> : <span className="lp-proj-muted">Unavailable</span>}</td>
    <td><button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={!item || !pdp.open}
      onClick={() => { if (item) pdp.open?.(item); }}>Open</button></td></>;
}

export function ProjectForm({ targets, onCreated, onCancel, onForbidden }: {
  targets: Array<{ grain: ProjectGrain; key: string }>; onCreated: (project: Project) => void;
  onCancel: () => void; onForbidden: () => void;
}) {
  const [draft, setDraft] = useState<ProjectDraft>({
    name: "", status: "Planned", priority: "Medium", owner: "", ownerUsername: null,
    startOn: "", targetOn: "", completedOn: null, progress: 0, notes: "",
  });
  const formId = useId();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const submitting = useRef(false);
  const set = <K extends keyof typeof draft>(key: K, value: (typeof draft)[K]) => setDraft((prev) => ({ ...prev, [key]: value }));

  const submit = async (event: FormEvent) => {
    event.preventDefault();
    if (submitting.current) return;
    const name = draft.name.trim();
    if (!name) { setError("Name the project."); return; }
    if (!Number.isInteger(draft.progress) || draft.progress < 0 || draft.progress > 100) {
      setError("Enter a whole percent from 0 to 100."); return;
    }
    submitting.current = true;
    setBusy(true);
    try {
      const body: ProjectInput = {
        name, status: draft.status, priority: draft.priority, ownerUsername: draft.ownerUsername,
        startOn: draft.startOn || null, targetOn: draft.targetOn || null, progress: draft.progress,
        notes: draft.notes?.trim() || null, targets,
      };
      const answer = await call<{ project: Project }>("", { method: "POST", body }, "The project was not created.");
      onCreated(answer.project);
    } catch (reason) {
      setError(messageOf(reason, "The project was not created."));
      setBusy(false);
      submitting.current = false;
      if (reason instanceof ProjectRequestError && reason.status === 403) onForbidden();
    }
  };

  return <form id={formId} className="lp-proj-form" onSubmit={(event) => void submit(event)} aria-label="New project">
    <label className="lp-proj-field lp-proj-field-wide"><span>Project name</span>
      <input className="lp-proj-input" value={draft.name} onChange={(event) => set("name", event.target.value)}
        placeholder="Name your project" autoFocus required maxLength={300} disabled={busy} /></label>
    <div className="lp-proj-field"><span>Status</span>
      <StatusPicker value={draft.status} disabled={busy} onChange={value => set("status", value)} /></div>
    <label className="lp-proj-field"><span>Owner</span>
      <OwnerSelect value={draft.ownerUsername} disabled={busy} onChange={value => set("ownerUsername", value)} /></label>
    <label className="lp-proj-field"><span>Priority</span>
      <select className="lp-proj-input" value={draft.priority} disabled={busy} onChange={(event) => set("priority", event.target.value as Priority)}>
        {PROJECT_PRIORITIES.map((value) => <option key={value} value={value}>{value}</option>)}
      </select></label>
    <label className="lp-proj-field"><span>Start date</span>
      <input type="date" className="lp-proj-input" value={draft.startOn ?? ""} disabled={busy} onChange={(event) => set("startOn", event.target.value)} /></label>
    <label className="lp-proj-field"><span>Target date</span>
      <input type="date" className="lp-proj-input" value={draft.targetOn ?? ""} disabled={busy} onChange={(event) => set("targetOn", event.target.value)} /></label>
    <label className="lp-proj-field lp-proj-field-wide"><span>Description</span>
      <textarea className="lp-proj-input" rows={3} placeholder="Describe the work" value={draft.notes ?? ""} disabled={busy} onChange={(event) => set("notes", event.target.value)} /></label>
    {error ? <p className="lp-proj-error lp-proj-field-wide" role="alert">{error}</p> : null}
    <ProjectFooter><div className="lp-proj-form-actions lp-proj-field-wide">
      <button type="button" className="lp-proj-btn lp-proj-btn-quiet" disabled={busy} onClick={onCancel}>Cancel</button>
      <button type="submit" form={formId} className="lp-proj-btn lp-proj-btn-primary" disabled={busy}>{busy ? "Creating…" : "Create project"}</button>
    </div></ProjectFooter>
  </form>;
}