File size: 38,560 Bytes
f462120
8cbc29f
8729c1d
8cbc29f
8729c1d
 
 
f462120
3fac176
f462120
 
 
8cbc29f
 
 
 
 
f462120
8cbc29f
f462120
8cbc29f
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
f462120
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
8cbc29f
8133df9
 
 
 
 
07a68d0
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
8cbc29f
 
 
 
 
8873406
8cbc29f
 
 
8133df9
8cbc29f
8873406
 
8cbc29f
 
 
 
 
8133df9
 
 
 
8cbc29f
8873406
 
 
 
 
8cbc29f
 
 
8873406
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
8cbc29f
 
8873406
8cbc29f
8133df9
 
 
 
 
 
 
 
 
 
07a68d0
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
8cbc29f
 
 
8873406
8cbc29f
 
8133df9
 
8cbc29f
 
 
 
 
 
 
 
 
8133df9
8cbc29f
8873406
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
8133df9
 
8cbc29f
8873406
8cbc29f
 
 
 
8133df9
 
 
 
 
 
 
 
8cbc29f
07a68d0
8873406
07a68d0
 
8873406
07a68d0
8cbc29f
 
 
07a68d0
8133df9
 
07a68d0
8cbc29f
07a68d0
 
 
 
8873406
07a68d0
 
8cbc29f
8873406
 
 
 
 
8cbc29f
 
 
8133df9
 
 
 
 
 
 
 
8cbc29f
 
8873406
 
 
8133df9
8873406
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
8873406
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
8873406
07a68d0
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
8cbc29f
 
8873406
 
8133df9
 
 
8cbc29f
 
8873406
 
 
8133df9
07a68d0
8873406
 
07a68d0
8cbc29f
 
 
 
 
 
 
 
8133df9
 
 
 
8cbc29f
 
 
 
8873406
 
8cbc29f
8873406
 
 
 
8cbc29f
 
f462120
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
8873406
 
 
 
f462120
8873406
 
8cbc29f
 
 
 
8873406
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
8873406
f462120
 
8873406
8cbc29f
8873406
 
 
 
 
 
8cbc29f
8873406
 
 
8cbc29f
 
 
f462120
8cbc29f
8873406
8cbc29f
 
 
 
 
8873406
8cbc29f
 
 
 
 
8873406
 
 
 
8cbc29f
 
 
 
 
 
 
 
8873406
 
 
 
 
 
 
 
 
 
8cbc29f
8873406
 
8cbc29f
 
8133df9
8cbc29f
 
 
 
8873406
 
 
 
 
8729c1d
 
 
 
 
 
8873406
 
 
 
 
 
 
f462120
8873406
8cbc29f
 
f462120
8cbc29f
 
 
8133df9
8cbc29f
 
 
 
 
f462120
8133df9
8cbc29f
 
 
 
 
8873406
 
8cbc29f
 
 
 
 
 
 
f462120
3fac176
f462120
 
 
 
 
 
 
8133df9
8cbc29f
8133df9
f462120
8cbc29f
f462120
 
 
 
 
 
8cbc29f
 
 
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
import { useCallback, useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import { CaretDown, CaretUp, FunnelSimple, Star } from "@phosphor-icons/react";
import { API_V1, CREDENTIALS } from "../../apiContract";
import { AppFrame } from "../../customer-grid/seam";
import { FilterBuilderPanel, Popover } from "../../filter-kit";
import type { Field, FilterTree } from "../../filter-kit";
import { AppTabs } from "../AppTabs";
import { AppRail } from "../AppRail";
import { AppFrameMarks } from "../templateMarks";
import { LineChart } from "../../viz/kit";
import Dashboard from "./Dashboard";
import "../../styles/sdlc78/competitor-watch.css";

// S78-T17 (C4, R20): the Competitor watch App. Reads and writes go through the competitor watch
// routes with the App id, so the server applies may_read and may_edit to this App record.

/** Alert statuses share the API's order. */
export const COMPETITOR_WATCH_STATUSES = [
  "Open", "Repriced", "Ads changed", "Listing improved", "Watching", "Ignore", "Reported to Amazon",
] as const;

const ALERT_STATUS_FIELD: Field = {
  key: "status", label: "Status", type: "select", source: "overlay",
  options: [...COMPETITOR_WATCH_STATUSES],
};
const ALERT_TRIGGER_FIELD: Field = {
  key: "trigger", label: "Alert type", type: "select", source: "overlay",
  options: ["Sellers on my ASINs"],
};

function AlertFilter({ field, value, onChange }: {
  field: Field; value: string; onChange: (value: string) => void;
}) {
  const displayValue = field.key === "trigger" && value === "own_asin_seller" ? "Sellers on my ASINs" : value;
  const asTree = (value: string): FilterTree => ({ conj: "and",
    nodes: value ? [{ colId: field.key, op: "eq", value }] : [],
  });
  const [draft, setDraft] = useState(() => asTree(displayValue));
  const [problem, setProblem] = useState("");
  useEffect(() => {
    setDraft({ conj: "and", nodes: displayValue ? [{ colId: field.key, op: "eq", value: displayValue }] : [] });
    setProblem("");
  }, [field.key, displayValue]);
  const apply = (next: FilterTree) => {
    setDraft(next);
    if (!next.nodes.length) { setProblem(""); onChange(""); return; }
    const node = next.nodes[0];
    // The endpoint accepts one exact value. Never reduce a richer tree to its first condition.
    if (next.nodes.length !== 1 || "children" in node || node.colId !== field.key || node.rhs
        || node.window || node.dateWindow || node.valueRef || node.value2Ref || node.value2
        || !["eq", "isAnyOf"].includes(node.op)
        || (node.op === "isAnyOf" && node.values?.length !== 1)) {
      setProblem("Choose one value with is or is any of.");
      return;
    }
    const chosen = node.op === "isAnyOf" ? node.values![0] : node.value;
    if (!chosen || !field.options?.includes(chosen)) {
      setProblem("Choose one value to apply the filter.");
      return;
    }
    setProblem("");
    onChange(field.key === "trigger" ? "own_asin_seller" : chosen);
  };
  return <div className="cw-field cw-term-field" role="group" aria-label={field.label}>
    <span className="cw-field-label">{field.label}</span>
    <Popover label="Filter" icon={<FunnelSimple size={16} />} tone="filter" wide active={!!value}>
      {() => <>
        <FilterBuilderPanel fields={[field]} filters={draft} onChange={apply} database={null} />
        {problem && <p className="cw-error" role="alert">{problem}</p>}
      </>}
    </Popover>
  </div>;
}


export interface CompetitorWatchApplication {
  id: string;
  name: string;
  templateMark?: string;
  templateConnector?: string;
  capabilities?: Record<string, boolean>;
}

interface Week { start: string; end: string }

interface RankedRow {
  rank: number;
  asin: string;
  title?: string;
  ours: boolean;
  clickShare: number | null;
  conversionShare: number | null;
  previousRank: number | null;
  previousClickShare: number | null;
  previousConversionShare: number | null;
  cause?: string;
}

interface TrendSeries {
  asin: string;
  ours: boolean;
  points: { start: string; clickShare: number | null }[];
}

interface TermScreen {
  canEdit: boolean;
  termsReady: boolean;
  terms: string[];
  termLabels: Record<string, string>;
  termRows: { term: string; termLabel: string; datedWeeks: number | null; starred: boolean; type: string }[];
  trackingReady: boolean;
  trackingCause: string;
  termTotal: number | null;
  termOffset: number;
  termLimit: number;
  term: string | null;
  week: Week | null;
  previousWeek: Week | null;
  comparisonReady: boolean;
  comparisonMessage: string;
  top3: RankedRow[];
  trend: TrendSeries[];
  problems: string[];
}

interface Alert {
  id: string;
  term: string;
  termLabel: string;
  asin: string;
  trigger: string;
  owner: string;
  status: string;
  due: string;
  createdAt: string;
  cause?: string;
}

interface Check { term: string; termLabel: string; asin: string; trigger: string; cause: string }

interface RowPage { total: number; offset: number; limit: number }
interface AlertScreen { canEdit: boolean; alerts: Alert[]; checks: Check[]; alertPage: RowPage; checkPage: RowPage }

type Load<T> = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T };

const text = (value: unknown) => (typeof value === "string" ? value : "");
const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);
const decodedTerm = (key: string) => {
  try { return decodeURIComponent(key.replace(/\+/g, " ")).trim().replace(/\s+/g, " "); }
  catch { return key.replace(/\+/g, " "); }
};

class ScreenReadError extends Error {
  readonly screen: unknown;
  constructor(message: string, screen: unknown) { super(message); this.screen = screen; }
}

async function readJson(response: Response, fallback: string): Promise<unknown> {
  const body: unknown = await response.json().catch(() => null);
  if (response.ok) return body;
  type Refusal = { message?: unknown; details?: { screen?: unknown } };
  const envelope = body as { error?: Refusal; detail?: { error?: Refusal } } | null;
  const error = envelope?.error ?? envelope?.detail?.error;
  throw new ScreenReadError(text(error?.message) || fallback, error?.details?.screen);
}

function parseWeek(raw: unknown): Week | null {
  const row = raw as { start?: unknown; end?: unknown } | null;
  return row && text(row.start) && text(row.end) ? { start: text(row.start), end: text(row.end) } : null;
}

function parseTermScreen(raw: unknown): TermScreen {
  const body = (raw ?? {}) as Record<string, unknown>;
  const rows = Array.isArray(body.top3) ? body.top3 : [];
  const trend = Array.isArray(body.trend) ? body.trend : [];
  const labels = (body.termLabels ?? {}) as Record<string, unknown>;
  const flags = (body.termFlags ?? {}) as Record<string, { starred?: boolean }>;
  const termRows = Array.isArray(body.termRows) ? body.termRows : [];
  return {
    canEdit: body.canEdit === true,
    termsReady: body.termsReady !== false,
    terms: Array.isArray(body.terms) ? body.terms.map(text).filter(Boolean) : [],
    termLabels: Object.fromEntries(Object.entries(labels).map(([key, label]) => [key, text(label)])),
    termRows: (Array.isArray(body.terms) ? body.terms : []).map((key) => {
      const row = (termRows.find((item) => item?.term === key) ?? {}) as Record<string, unknown>;
      return { term: text(key), termLabel: text(row.termLabel) || text(labels[text(key)]) || decodedTerm(text(key)),
        datedWeeks: num(row.datedWeeks), starred: row.starred === true || flags[text(key)]?.starred === true,
        type: text(row.type) || (flags[text(key)]?.starred ? "Starred" : "Watched") };
    }),
    trackingReady: body.trackingReady === true,
    trackingCause: text(body.trackingCause),
    termTotal: body.termTotal === null ? null : num(body.termTotal) ?? 0,
    termOffset: num(body.termOffset) ?? 0,
    termLimit: num(body.termLimit) ?? 50,
    term: text(body.term) || null,
    week: parseWeek(body.week),
    previousWeek: parseWeek(body.previousWeek),
    comparisonReady: body.comparisonReady === true,
    comparisonMessage: text(body.comparisonMessage),
    top3: rows.map((item) => {
      const row = (item ?? {}) as Record<string, unknown>;
      return {
        rank: num(row.rank) ?? 0,
        asin: text(row.asin),
        title: text(row.title) || undefined,
        ours: row.ours === true,
        clickShare: num(row.clickShare),
        conversionShare: num(row.conversionShare),
        previousRank: num(row.previousRank),
        previousClickShare: num(row.previousClickShare),
        previousConversionShare: num(row.previousConversionShare),
        cause: text(row.cause) || undefined,
      };
    }).filter((row) => row.asin),
    trend: trend.map((item) => {
      const series = (item ?? {}) as Record<string, unknown>;
      const points = Array.isArray(series.points) ? series.points : [];
      return {
        asin: text(series.asin),
        ours: series.ours === true,
        points: points.map((point) => {
          const row = (point ?? {}) as Record<string, unknown>;
          return { start: text(row.start), clickShare: num(row.clickShare) };
        }).filter((point) => point.start),
      };
    }).filter((series) => series.asin),
    problems: Array.isArray(body.problems) ? body.problems.map(text).filter(Boolean) : [],
  };
}

function parseAlerts(raw: unknown): AlertScreen {
  const body = (raw ?? {}) as Record<string, unknown>;
  const rows = Array.isArray(body.alerts) ? body.alerts : [];
  const checks = Array.isArray(body.checks) ? body.checks : [];
  const page = (raw: unknown): RowPage => {
    const row = (raw ?? {}) as Record<string, unknown>;
    return { total: num(row.total) ?? 0, offset: num(row.offset) ?? 0, limit: num(row.limit) ?? 50 };
  };
  return {
    canEdit: body.canEdit === true,
    alerts: rows.map((item) => parseAlert(item)).filter((row): row is Alert => row !== null),
    alertPage: page(body.alertPage), checkPage: page(body.checkPage),
    checks: checks.map((item) => {
      const row = (item ?? {}) as Record<string, unknown>;
      return { term: text(row.term), termLabel: text(row.termLabel) || decodedTerm(text(row.term)),
        asin: text(row.asin), trigger: text(row.trigger), cause: text(row.cause) };
    }).filter((row) => row.cause),
  };
}

function parseAlert(item: unknown): Alert | null {
  const row = (item ?? {}) as Record<string, unknown>;
  const id = text(row.id);
  if (!id) return null;
  return {
    id, term: text(row.term), termLabel: text(row.termLabel) || decodedTerm(text(row.term)), asin: text(row.asin), trigger: text(row.trigger),
    owner: text(row.owner), status: text(row.status), due: text(row.due),
    createdAt: text(row.createdAt),
    cause: text(row.cause) || undefined,
  };
}

const shortDate = (iso: string) => {
  const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso);
  return Number.isNaN(date.getTime()) ? iso
    : date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
};
const weekLabel = (week: Week) => `${shortDate(week.start)} to ${shortDate(week.end)}`;
const pct = (value: number | null) => (value === null ? "Not held" : `${value.toFixed(1)}%`);

/** The change chip copy: "New", "Up 1", "Down 2", "Same" for rank; "+1.2 pts" for a share. */
export function rankChange(rank: number, previous: number | null): { label: string; tone: "new" | "up" | "down" | "flat" } {
  if (previous === null) return { label: "New", tone: "new" };
  if (previous > rank) return { label: `Up ${previous - rank}`, tone: "up" };
  if (previous < rank) return { label: `Down ${rank - previous}`, tone: "down" };
  return { label: "Same", tone: "flat" };
}

export function shareChange(value: number | null, previous: number | null): { label: string; tone: "up" | "down" | "flat" } | null {
  if (value === null || previous === null) return null;
  const delta = Math.round((value - previous) * 10) / 10;
  if (delta > 0) return { label: `+${delta.toFixed(1)} pts`, tone: "up" };
  if (delta < 0) return { label: `-${Math.abs(delta).toFixed(1)} pts`, tone: "down" };
  return { label: "0.0 pts", tone: "flat" };
}

function ChangeChip({ change }: { change: { label: string; tone: string } | null }) {
  if (!change) return null;
  return <span className={`cw-chip is-${change.tone}`}>{change.label}</span>;
}

function TrendChart({ trend }: { trend: TrendSeries[] }) {
  const weeks = new Set(trend.flatMap((series) => series.points.map((point) => point.start)));
  if (!trend.length) return null;
  if (weeks.size < 2) return <p className="cw-note" role="status">The trend shows after two weeks.</p>;
  return <LineChart label="Click share by week" unit="percent"
    series={[...trend.filter((row) => row.ours), ...trend.filter((row) => !row.ours)].map((row) => ({
      id: row.asin, label: row.ours ? row.asin + " (You)" : row.asin,
      points: [...row.points].sort((a, b) => a.start.localeCompare(b.start))
        .map((point) => ({ x: point.start, y: point.clickShare })),
    }))} />;
}

function RankedTable({ rows, compare }: { rows: RankedRow[]; compare: boolean }) {
  // Before a second week is held there is nothing to compare, so no chip shows.
  return <table className="cw-table cw-ranked">
    <thead>
      <tr><th scope="col">Rank</th><th scope="col">ASIN</th><th scope="col" className="is-num">Click share</th>
        <th scope="col" className="is-num">Conversion share</th></tr>
    </thead>
    <tbody>
      {rows.map((row) => <tr key={row.asin} className={row.ours ? "is-ours" : undefined}>
        <td data-label="Rank"><span className="cw-rank">{row.rank}</span>
          <ChangeChip change={compare ? rankChange(row.rank, row.previousRank) : null} /></td>
        <td data-label="ASIN">
          <span className="cw-asin">{row.asin}</span>
          {row.ours && <span className="cw-you">You</span>}
          {row.title && <span className="cw-title">{row.title}</span>}
          {row.cause && <span className="cw-cause">{row.cause}</span>}
        </td>
        <td data-label="Click share" className="is-num">{pct(row.clickShare)}
          <ChangeChip change={compare ? shareChange(row.clickShare, row.previousClickShare) : null} /></td>
        <td data-label="Conversion share" className="is-num">{pct(row.conversionShare)}
          <ChangeChip change={compare ? shareChange(row.conversionShare, row.previousConversionShare) : null} /></td>
      </tr>)}
    </tbody>
  </table>;
}

function useAppQuery(appId: string) {
  return useCallback((path: string, params: Record<string, string> = {}) => {
    const query = new URLSearchParams({ app: appId, ...params });
    return `${API_V1}/competitor-watch${path}?${query.toString()}`;
  }, [appId]);
}

function TermsView({ appId, canEditApp }: { appId: string; canEditApp: boolean }) {
  const url = useAppQuery(appId);
  const [term, setTerm] = useState("");
  const displayedTerm = useRef("");
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("");
  const [offset, setOffset] = useState(0);
  const [tracked, setTracked] = useState(false);
  const [termOrder, setTermOrder] = useState<"asc" | "desc" | "">("");
  const [state, setState] = useState<Load<TermScreen>>({ phase: "loading" });
  const [screen, setScreen] = useState<TermScreen | null>(null);
  const [attempt, setAttempt] = useState(0);
  const [draft, setDraft] = useState("");
  const [termError, setTermError] = useState("");
  const [busy, setBusy] = useState(false);
  const [savingStar, setSavingStar] = useState("");
  const [starMessage, setStarMessage] = useState("");
  const starRequest = useRef<AbortController | null>(null);
  const starFocus = useRef("");
  const termsList = useRef<HTMLTableElement>(null);
  const trackedControl = useRef<HTMLButtonElement>(null);

  useEffect(() => () => { starRequest.current?.abort(); }, []);

  useEffect(() => {
    if (search === query) return;
    const timer = setTimeout(() => { setQuery(search); setOffset(0); }, 200);
    return () => clearTimeout(timer);
  }, [search, query]);

  useEffect(() => {
    const controller = new AbortController();
    setState({ phase: "loading" });
    const requestedTerm = term || displayedTerm.current;
    void fetch(url("/screen", { ...(requestedTerm ? { term: requestedTerm } : {}), q: query, offset: String(offset), limit: "50",
      tracked: String(tracked), ...(termOrder ? { termOrder } : {}) }),
      { credentials: CREDENTIALS, signal: controller.signal })
      .then((response) => readJson(response, "The competitor watch could not be loaded."))
      .then((body) => {
        if (controller.signal.aborted) return;
        const value = parseTermScreen(body);
        displayedTerm.current = value.term ?? "";
        setScreen(value);
        setState({ phase: "ready", value });
      })
      .catch((reason: unknown) => {
        if (controller.signal.aborted) return;
        const diagnostic = reason instanceof ScreenReadError && reason.screen ? parseTermScreen(reason.screen) : null;
        if (diagnostic) displayedTerm.current = diagnostic.term ?? "";
        setScreen(diagnostic);
        setState({ phase: "error",
          message: reason instanceof Error ? reason.message : "The competitor watch could not be loaded." });
      });
    return () => controller.abort();
  }, [url, term, query, offset, attempt, tracked, termOrder]);

  useEffect(() => {
    if (!starFocus.current || state.phase === "loading") return;
    const buttons = Array.from(termsList.current?.querySelectorAll<HTMLButtonElement>("button[data-star-term]") ?? []);
    (buttons.find((button) => button.dataset.starTerm === starFocus.current) ?? buttons[0] ?? trackedControl.current)?.focus();
    starFocus.current = "";
  }, [screen, state.phase]);

  const canEdit = canEditApp && screen?.canEdit === true;
  const loading = state.phase === "loading";
  const selected = loading ? term || screen?.term || "" : screen?.term ?? "";
  const previousUnavailable = !screen?.termsReady || screen.termOffset === 0;
  const nextUnavailable = !screen?.termsReady || screen.termTotal === null || screen.termOffset + screen.terms.length >= screen.termTotal;
  const diagnosticError = state.phase === "error" && screen?.problems.includes(state.message);
  const termLabel = (key: string) => screen?.termLabels[key] || decodedTerm(key);

  const saveStar = async (key: string, starred: boolean, button: HTMLButtonElement) => {
    if (!canEdit || loading || savingStar) return;
    const controller = new AbortController();
    starRequest.current = controller;
    setSavingStar(key);
    setStarMessage("");
    setTermError("");
    try {
      const response = await fetch(url("/terms/star"), {
        method: "PATCH", credentials: CREDENTIALS, signal: controller.signal,
        headers: { "Content-Type": "application/json" }, body: JSON.stringify({ term: key, starred }),
      });
      await readJson(response, "The star was not saved.");
      if (controller.signal.aborted) return;
      if (document.activeElement === button) starFocus.current = key;
      setStarMessage(`${starred ? "Starred" : "Unstarred"} ${termLabel(key)}`);
      setAttempt((count) => count + 1);
    } catch (reason) {
      if (!controller.signal.aborted) setTermError(reason instanceof Error ? reason.message : "The star was not saved.");
    } finally {
      if (!controller.signal.aborted) setSavingStar("");
    }
  };

  const movePage = (direction: -1 | 1) => {
    if (!screen || loading || (direction < 0 ? previousUnavailable : nextUnavailable)) return;
    setOffset(Math.max(0, screen.termOffset + direction * screen.termLimit));
    setState({ phase: "loading" });
  };

  const editTerms = async (action: "add" | "remove", value: string) => {
    setBusy(true);
    setTermError("");
    try {
      const response = await fetch(url(action === "add" ? "/terms" : "/terms/remove"), {
        method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ terms: [value] }),
      });
      await readJson(response, action === "add" ? "The term was not added." : "The term was not removed.");
      setDraft("");
      if (action === "add") setTerm(value.trim().toLowerCase());
      else { setTerm(""); displayedTerm.current = ""; }
      setAttempt((count) => count + 1);
    } catch (reason) {
      setTermError(reason instanceof Error ? reason.message : "The term was not saved.");
    } finally {
      setBusy(false);
    }
  };
  const submit = (event: FormEvent) => {
    event.preventDefault();
    if (draft.trim()) void editTerms("add", draft.trim());
  };

  return <div className="cw-view" data-proof="competitor-terms">
    <div className="cw-section" style={{ flexDirection: "row", flexWrap: "wrap", alignItems: "center", gap: "16px" }}>
      <div className="cw-section" style={{ gap: "0", flex: "1 1 280px" }}>
        <h2 className="cw-heading">{screen?.termsReady === false || screen?.termTotal === null ? "Terms unavailable" : screen ? `${screen.termTotal.toLocaleString()} terms` : "Terms"}</h2>
        <span className="cw-period">{screen?.week
          ? `${weekLabel(screen.week)}${screen.previousWeek ? ` compared to ${weekLabel(screen.previousWeek)}` : ""}`
          : loading ? "Loading weeks" : "No dated weeks held"}</span>
      </div>
      <label className="cw-field cw-search-field">
        <span className="cw-field-label">Find terms</span>
        <input className="cw-input" type="search" value={search}
          onChange={(event) => setSearch(event.target.value)} placeholder="Search watched terms" />
      </label>
      <button className="cw-button is-quiet" type="button" aria-pressed={tracked} ref={trackedControl}
        onClick={() => { setTracked((value) => !value); setOffset(0); }}>Tracked</button>
    </div>
    <table className="cw-table" ref={termsList} aria-label="Terms" aria-busy={loading}>
      <thead><tr>
        <th scope="col" aria-label="Star" style={{ width: "40px", background: "var(--lp-surface-2)" }} />
        <th scope="col" aria-sort={termOrder === "asc" ? "ascending" : termOrder === "desc" ? "descending" : "none"}
          style={{ background: "var(--lp-surface-2)" }}>
          <button className="cw-button is-quiet" type="button" style={{ padding: "0" }}
            aria-label={termOrder === "asc" ? "Sort terms descending" : "Sort terms ascending"}
            onClick={() => { setTermOrder((value) => value === "asc" ? "desc" : "asc"); setOffset(0); }}>
            Term {termOrder === "desc" ? <CaretDown size={12} aria-hidden="true" /> : <CaretUp size={12} aria-hidden="true" />}
          </button>
        </th>
        <th scope="col" style={{ width: "160px", background: "var(--lp-surface-2)" }}>Status</th><th scope="col" style={{ width: "160px", background: "var(--lp-surface-2)" }}>Type</th>
      </tr></thead>
      <tbody>{screen?.termRows.map((row) => <tr key={row.term} aria-selected={selected === row.term}>
        <td data-label="Star" style={{ verticalAlign: "middle" }}>
          <button className="cw-button is-quiet" type="button" data-star-term={row.term}
            style={{ padding: "0 8px" }}
            aria-label={`${row.starred ? "Unstar" : "Star"} ${row.termLabel}`} aria-pressed={row.starred}
            disabled={!canEdit} aria-disabled={loading || !!savingStar || !canEdit}
            onClick={(event) => void saveStar(row.term, !row.starred, event.currentTarget)}>
            <Star size={16} weight={row.starred ? "fill" : "regular"} aria-hidden="true" />
          </button>
        </td>
        <td data-label="Term" style={{ verticalAlign: "middle" }}><button type="button" className="cw-link"
          onClick={() => { setTerm(row.term); setState({ phase: "loading" }); }}>{row.termLabel}</button></td>
        <td data-label="Status" style={{ verticalAlign: "middle" }}><span className={`cw-chip is-${row.datedWeeks === null ? "flat" : row.datedWeeks >= 2 ? "up" : "new"}`}
          style={{ marginLeft: "0", borderRadius: "var(--lp-r-pill)", padding: "4px 8px",
            ...(row.datedWeeks !== null && row.datedWeeks < 2
              ? { background: "var(--lp-yellow-tint)", color: "var(--lp-yellow-deep)" } : {}) }}>
          {row.datedWeeks === null ? "Not checked" : row.datedWeeks >= 2 ? "Ready" : "Building"}</span></td>
        <td data-label="Type" style={{ verticalAlign: "middle" }}>{row.type}</td>
      </tr>)}</tbody>
    </table>
    <div className="cw-filters" role="group" aria-label="Term and week">
      <label className="cw-field cw-term-field">
        <span className="cw-field-label">Search term</span>
        <select className="cw-select" value={selected} disabled={!screen || !screen.terms.length}
          aria-busy={loading}
          onChange={(event) => { setTerm(event.target.value); setState({ phase: "loading" }); }}>
          {!screen?.terms.length && <option value="">{!screen && loading ? "Loading terms" : screen?.termsReady === false || screen?.termTotal === null ? "Terms unavailable" : query || tracked ? "No matching terms" : "No watched terms"}</option>}
          {selected && !screen?.terms.includes(selected) && <option value={selected}>{termLabel(selected)}</option>}
          {screen?.terms.map((option) => <option key={option} value={option}>{termLabel(option)}</option>)}
        </select>
      </label>
      <div className="cw-pager" aria-label="Term pages" aria-busy={loading}>
        <button className="cw-button is-quiet" type="button" aria-disabled={loading || previousUnavailable}
          onClick={() => movePage(-1)}>Previous</button>
        <span className="cw-period cw-page-count" role="status">{loading ? "Loading terms" : screen?.termsReady === false || screen?.termTotal === null ? "Terms unavailable" : screen ? `${screen.termTotal ? screen.termOffset + 1 : 0} to ${screen.termOffset + screen.terms.length} of ${screen.termTotal.toLocaleString()}` : "No terms loaded"}</span>
        <button className="cw-button is-quiet" type="button"
          aria-disabled={loading || nextUnavailable}
          onClick={() => movePage(1)}>Next</button>
      </div>
      {canEdit && <form className="cw-term-form" onSubmit={submit}>
        <input className="cw-input" value={draft} onChange={(event) => setDraft(event.target.value)}
          placeholder="Add a term" aria-label="Add a search term" disabled={busy} />
        <button type="submit" className="cw-button" disabled={busy || !draft.trim()}>Add</button>
        {selected && <button type="button" className="cw-button is-quiet" disabled={busy}
          onClick={() => void editTerms("remove", selected)}>Remove term</button>}
      </form>}
    </div>
    {starMessage && <p className="cw-note" role="status">{starMessage}</p>}
    {screen && !screen.trackingReady && screen.trackingCause && !screen.problems.includes(screen.trackingCause)
      && screen.trackingCause !== (state.phase === "error" ? state.message : "")
      && <p className="cw-cause-line" role="status">{screen.trackingCause}</p>}
    {termError && <p className="cw-error" role="alert">{termError}</p>}
    {state.phase === "loading" && <div className="cw-skeleton-rows" aria-busy="true" aria-label="Loading">
      <div className="cw-skeleton" /><div className="cw-skeleton" /><div className="cw-skeleton" />
    </div>}
    {state.phase === "error" && <p className={diagnosticError ? "cw-cause-line" : "cw-error"}
      role={diagnosticError ? "status" : "alert"}>{state.message}{" "}
      <button type="button" className="cw-link" onClick={() => setAttempt((count) => count + 1)}>Retry</button></p>}
    {screen && state.phase !== "loading" && screen.problems.filter((problem, index, problems) =>
      problem !== (state.phase === "error" ? state.message : "") && problems.indexOf(problem) === index).map((problem) =>
      <p key={problem} className="cw-cause-line" role="status">{problem}</p>)}
    {screen && state.phase === "ready" && <>
      {!screen.comparisonReady && <p className="cw-note" role="status">
        {screen.comparisonMessage || "Comparison starts after the second weekly pull."}</p>}
      <div className="cw-view">
        {screen.term && screen.top3.length > 0 && <section className="cw-section" aria-label="Top 3 this week">
          <h2 className="cw-heading">Top 3 this week</h2>
          <RankedTable rows={screen.top3} compare={screen.comparisonReady} />
        </section>}
        {screen.term && screen.top3.length === 0 && <p className="cw-note" role="status">No top 3 is held for this term yet.</p>}
        {screen.trend.length > 0 && <section className="cw-section" aria-label="Trend">
          <h2 className="cw-heading">Trend</h2>
          <TrendChart trend={screen.trend} />
        </section>}
      </div>
    </>}
  </div>;
}

function RowPager({ label, page, count, loading, move }: {
  label: string; page?: RowPage; count: number; loading: boolean; move: (offset: number) => void;
}) {
  const previousUnavailable = !page || page.offset === 0;
  const nextUnavailable = !page || page.offset + count >= page.total;
  return <div className="cw-pager" aria-label={label} aria-busy={loading}>
    <button className="cw-button is-quiet" type="button" aria-disabled={loading || previousUnavailable}
      onClick={() => { if (!loading && !previousUnavailable && page) move(Math.max(0, page.offset - page.limit)); }}>Previous</button>
    <span className="cw-period cw-page-count" role="status">{loading ? "Loading" : page
      ? `${page.total ? page.offset + 1 : 0} to ${page.offset + count} of ${page.total.toLocaleString()}` : "No rows loaded"}</span>
    <button className="cw-button is-quiet" type="button" aria-disabled={loading || nextUnavailable}
      onClick={() => { if (!loading && !nextUnavailable && page) move(page.offset + page.limit); }}>Next</button>
  </div>;
}

function AlertsView({ appId, canEditApp }: { appId: string; canEditApp: boolean }) {
  const url = useAppQuery(appId);
  const [state, setState] = useState<Load<AlertScreen>>({ phase: "loading" });
  const [screen, setScreen] = useState<AlertScreen | null>(null);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("");
  const [status, setFilterStatus] = useState("");
  const [trigger, setTrigger] = useState("");
  const [offset, setOffset] = useState(0);
  const [checkOffset, setCheckOffset] = useState(0);
  const [attempt, setAttempt] = useState(0);
  const [saving, setSaving] = useState("");
  const [rowError, setRowError] = useState<{ id: string; message: string } | null>(null);
  const alive = useRef(true);
  useEffect(() => {
    alive.current = true;
    return () => { alive.current = false; };
  }, []);

  useEffect(() => {
    if (search === query) return;
    const timer = setTimeout(() => { setQuery(search); setOffset(0); setCheckOffset(0); }, 200);
    return () => clearTimeout(timer);
  }, [search, query]);

  useEffect(() => {
    const controller = new AbortController();
    setState({ phase: "loading" });
    void fetch(url("/alerts", { q: query, offset: String(offset), limit: "50",
      check_offset: String(checkOffset), check_limit: "50", ...(status ? { status } : {}),
      ...(trigger ? { trigger } : {}) }),
      { credentials: CREDENTIALS, signal: controller.signal })
      .then((response) => readJson(response, "Alerts could not be loaded."))
      .then((body) => {
        if (controller.signal.aborted) return;
        const value = parseAlerts(body);
        setScreen(value);
        setState({ phase: "ready", value });
      })
      .catch((reason: unknown) => {
        if (controller.signal.aborted) return;
        setScreen(null);
        setState({ phase: "error",
          message: reason instanceof Error ? reason.message : "Alerts could not be loaded." });
      });
    return () => controller.abort();
  }, [url, attempt, query, status, trigger, offset, checkOffset]);

  const setStatus = async (alert: Alert, nextStatus: string) => {
    setSaving(alert.id);
    setRowError(null);
    try {
      const response = await fetch(url(`/alerts/${encodeURIComponent(alert.id)}`), {
        method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: nextStatus }),
      });
      // The route answers with the saved alert itself.
      const body = await readJson(response, "The status was not saved.") as { alert?: unknown } | null;
      const saved = parseAlert(body?.alert ?? body);
      if (!alive.current) return;
      setScreen((current) => current ? { ...current,
        alerts: current.alerts.map((row) => row.id === alert.id ? (saved ?? { ...row, status: nextStatus }) : row),
      } : current);
      if (status) setAttempt((count) => count + 1);
    } catch (reason) {
      if (alive.current) setRowError({ id: alert.id,
        message: reason instanceof Error ? reason.message : "The status was not saved." });
    } finally {
      if (alive.current) setSaving("");
    }
  };

  const loading = state.phase === "loading";
  const alerts = screen?.alerts ?? [];
  const checks = screen?.checks ?? [];
  const canEdit = canEditApp && screen?.canEdit === true;
  const move = (offset: number, checks = false) => {
    if (loading) return;
    if (checks) setCheckOffset(offset); else setOffset(offset);
    setState({ phase: "loading" });
  };
  const notChecked = <section className="cw-section" aria-label="Not checked">
    <h2 className="cw-heading">Not checked</h2>
    <RowPager label="Check pages" page={screen?.checkPage} count={checks.length} loading={loading}
      move={(offset) => move(offset, true)} />
    <ul className="cw-checks">
      {checks.map((check, index) => <li key={`${check.term}:${check.asin}:${check.trigger}:${index}`}>
        <span className="cw-check-what">{[check.termLabel, check.asin, check.trigger].filter(Boolean).join(", ")}</span>
        <span className="cw-cause">{check.cause}</span>
      </li>)}
    </ul>
  </section>;
  return <div className="cw-view">
    <div className="cw-filters" role="group" aria-label="Alert filters">
      <label className="cw-field cw-search-field"><span className="cw-field-label">Find alerts</span>
        <input className="cw-input" type="search" value={search} placeholder="Search alerts and checks"
          onChange={(event) => setSearch(event.target.value)} /></label>
      <AlertFilter field={ALERT_STATUS_FIELD} value={status} onChange={(value) => {
        setFilterStatus(value); setOffset(0);
      }} />
      <AlertFilter field={ALERT_TRIGGER_FIELD} value={trigger} onChange={(value) => {
        setTrigger(value); setOffset(0); setCheckOffset(0);
      }} />
      <RowPager label="Alert pages" page={screen?.alertPage} count={alerts.length} loading={loading}
        move={(offset) => move(offset)} />
    </div>
    {state.phase === "error" && <p className="cw-error" role="alert">{state.message}{" "}
      <button type="button" className="cw-link" onClick={() => setAttempt((count) => count + 1)}>Retry</button></p>}
    {!screen && loading && <div className="cw-skeleton-rows" aria-busy="true" aria-label="Loading">
      <div className="cw-skeleton" /><div className="cw-skeleton" /><div className="cw-skeleton" /></div>}
    {screen && !alerts.length && <p className="cw-note" role="status">{query || status || trigger ? "No matching alerts." : "No alerts yet."}</p>}
    <table className="cw-table cw-alerts" aria-busy={loading} style={{ tableLayout: "fixed", width: "100%" }}>
    <thead>
      <tr><th scope="col">Term</th><th scope="col">ASIN</th><th scope="col">Trigger</th><th scope="col">Owner</th>
        <th scope="col" style={{ width: "224px" }}>Status</th><th scope="col">Detected</th><th scope="col">Due</th></tr>
    </thead>
    <tbody>
      {alerts.map((alert) => <tr key={alert.id}>
        <td data-label="Term">{alert.termLabel || "Own ASIN"}</td>
        <td data-label="ASIN"><span className="cw-asin">{alert.asin}</span></td>
        <td data-label="Trigger">{alert.trigger}
          {alert.cause && <span className="cw-cause">{alert.cause}</span>}</td>
        <td data-label="Owner">{alert.owner}</td>
        <td data-label="Status">
          {canEdit ? <select className="cw-select" style={{ width: "100%" }} value={alert.status} disabled={loading || saving === alert.id}
            aria-label={`Status for ${alert.asin} on ${alert.termLabel}`}
            onChange={(event) => void setStatus(alert, event.target.value)}>
            {COMPETITOR_WATCH_STATUSES.map((status) => <option key={status} value={status}>{status}</option>)}
          </select> : <span className="cw-status">{alert.status}</span>}
          {rowError?.id === alert.id && <span className="cw-cause" role="alert">{rowError.message}</span>}
        </td>
        <td data-label="Detected" className="is-num">{alert.createdAt
          ? <time dateTime={alert.createdAt}>{shortDate(alert.createdAt)}</time> : "Not recorded"}</td>
        <td data-label="Due" className="is-num">{alert.due ? shortDate(alert.due) : "Not set"}</td>
      </tr>)}
    </tbody>
  </table>{notChecked}</div>;
}

export default function CompetitorWatchView({ application }: { application: CompetitorWatchApplication }) {
  return <div className="cg-app-frame-catalog" data-app-view="competitor-watch">
    <AppFrame appName={application.name} rail={<AppRail appId={application.id} />}
      actions={<AppFrameMarks mark={application.templateMark} connector={application.templateConnector} />}>
      <CompetitorWatchBody key={application.id} application={application} />
    </AppFrame>
  </div>;
}

function CompetitorWatchBody({ application }: { application: CompetitorWatchApplication }) {
  const [tab, setTab] = useState<"dashboard" | "terms" | "alerts">("terms");
  const canEditApp = application.capabilities?.edit === true;
  const tabs = [{ id: "terms", label: "Terms" }, { id: "dashboard", label: "Dashboard" },
    { id: "alerts", label: "Alerts" }];
  return <div className="cw-app">
    <AppTabs tabs={tabs} value={tab} ariaLabel="Competitor watch"
      onChange={(id: string) => { if (id === "dashboard" || id === "terms" || id === "alerts") setTab(id); }} />
      <div className="cw-body" role="tabpanel" aria-label={tabs.find((item) => item.id === tab)?.label}>
        {tab === "dashboard" && <Dashboard appId={application.id} />}
        {tab === "terms" && <TermsView appId={application.id} canEditApp={canEditApp} />}
        {tab === "alerts" && <AlertsView appId={application.id} canEditApp={canEditApp} />}
      </div>
  </div>;
}