File size: 28,134 Bytes
f462120
 
8133df9
 
f462120
8133df9
f462120
 
 
 
 
 
 
 
 
 
 
 
8729c1d
f462120
 
8133df9
f462120
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
f462120
8729c1d
 
 
 
 
 
f462120
 
 
 
 
 
 
8729c1d
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
f462120
 
 
8729c1d
 
f462120
8729c1d
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
f462120
 
 
 
8729c1d
f462120
 
 
 
 
 
 
 
 
8133df9
f462120
 
 
 
 
 
 
 
 
 
8133df9
 
f462120
 
 
 
 
 
 
 
 
 
 
8133df9
 
f462120
 
8133df9
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
f462120
 
 
 
 
 
 
 
 
 
 
 
8133df9
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
f462120
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
f462120
 
 
 
 
 
 
 
 
 
 
8729c1d
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
8133df9
f462120
 
 
 
 
 
 
8133df9
 
 
 
f462120
8133df9
f462120
 
 
 
 
 
 
 
8133df9
f462120
 
 
 
 
 
 
 
8133df9
 
 
 
8729c1d
8133df9
 
 
 
8729c1d
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
8133df9
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
f462120
8133df9
 
 
 
 
 
 
 
f462120
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useCallback, useEffect, useId, useRef, useState } from "react";
import type { FormEvent } from "react";
import { flushSync } from "react-dom";
import { CaretRight } from "@phosphor-icons/react";
import { Busy } from "../ui/Busy";
import { TOAST_EVENT } from "../apiContract";
import { connectorSetupRoute } from "./permsModel";
import {
  getNotificationDestinations,
  getNotificationSlackChannels,
  saveNotificationDestinations,
} from "./settingsApi";
import type {
  NotificationDestination,
  NotificationDestinationPick,
  NotificationDestinationsPayload,
  NotificationReadiness,
  NotificationSlackChannel,
  NotificationWebhookDestination,
} from "./settingsApi";
import "../styles/sdlc81/notify-destinations.css";
import "./channels/channels.css";

type Picks = Record<string, NotificationDestinationPick>;
type Editor = { server: NotificationDestinationsPayload | null; drafts: Picks };
type Reason = { reason: string; message: string };
type SourcedReason = Reason & { source: "current" | "lastAttempt" };

function category(kind: string): string {
  if (kind === "account_health_new_items" || kind === "amazon_operator_weekly") return "Account";
  if (kind === "restock_digest") return "Inventory";
  if (kind === "fixture") return "Testing";
  return "Workspace";
}

function channelLabel(channel: NotificationSlackChannel | undefined, channelId: string): string {
  return channel?.channelName
    ? (channel.channelName.startsWith("#") ? channel.channelName : `#${channel.channelName}`)
    : channel?.label || channelId;
}

function deliveryState(row: NotificationDestination, destination: string, selected: boolean, pending: boolean,
  reasons: SourcedReason[]): string {
  if (!selected) return "Off";
  if (pending) return "Save to check delivery";
  if (reasons.some((reason) => reason.source === "current")) return "Unavailable";
  if (row.delivery[destination]?.state === "refused") return "Last attempt refused";
  if (row.delivery[destination]?.state === "sent") return "Last attempt sent";
  return "No delivery yet";
}

// An older server row or draft can omit in-app and webhooks. Absent reads as off.
function inAppPicked(pick: Partial<NotificationDestinationPick> | undefined): boolean {
  return pick?.inApp === true;
}

function savedWebhooks(pick: Partial<NotificationDestinationPick> | undefined): string[] {
  return pick && Array.isArray(pick.webhooks) ? pick.webhooks : [];
}

function picks(row: NotificationDestinationPick): NotificationDestinationPick {
  return {
    slackChannels: [...row.slackChannels],
    email: row.email?.trim() || null,
    inApp: inAppPicked(row),
    webhooks: [...savedWebhooks(row)],
  };
}

function sameChannels(a: readonly string[], b: readonly string[]): boolean {
  return JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
}

function samePicks(a: NotificationDestinationPick, b: NotificationDestinationPick): boolean {
  return sameChannels(a.slackChannels, b.slackChannels) && (a.email?.trim() || null) === (b.email?.trim() || null)
    && inAppPicked(a) === inAppPicked(b) && sameChannels(savedWebhooks(a), savedWebhooks(b));
}

function refreshEditor(previous: Editor, server: NotificationDestinationsPayload, saved: Picks): Editor {
  const drafts = { ...previous.drafts };
  for (const row of server.destinations) {
    const draft = drafts[row.kind];
    const baseline = previous.server?.destinations.find((item) => item.kind === row.kind);
    // Refresh clean or acknowledged drafts. Every other edit belongs to the user.
    if (!draft || (baseline && samePicks(draft, baseline)) || (saved[row.kind] && samePicks(draft, saved[row.kind]))) {
      drafts[row.kind] = picks(row);
    }
  }
  return { server, drafts };
}

function reasonText(reason: string | null, message: string, email: boolean, channel = "Slack"): string {
  if (reason === "not_configured") return "Slack is not connected.";
  if (reason === "email_not_configured") return "Email is not available for this workspace.";
  if (reason === "email_configuration_invalid") return "Email setup needs attention.";
  if (reason === "in_app_unavailable") return "In-app is unavailable for this workspace.";
  if (reason === "webhook_not_configured") return "Webhook is not set up.";
  if (!message || /smtp|AIOS_[A-Z0-9_]+/i.test(message)) {
    return email ? "Email delivery is unavailable." : `${channel} delivery is unavailable.`;
  }
  return message.replace(/[\u2013\u2014]/g, ", ");
}

function destinationReasons(
  row: NotificationDestination,
  destination: string,
  readiness: NotificationReadiness | undefined,
  extra?: Reason,
): SourcedReason[] {
  const reasons: SourcedReason[] = [];
  if (extra) reasons.push({ ...extra, source: "current" });
  if (readiness?.available === false) {
    const reason = readiness.reason || "unavailable";
    if (!reasons.some((item) => item.reason === reason)) reasons.push({ reason, message: readiness.message, source: "current" });
  }
  const delivery = row.delivery[destination];
  if (delivery?.state === "refused") {
    const reason = delivery.reason || "delivery_failed";
    if (!reasons.some((item) => item.reason === reason)) reasons.push({ reason, message: delivery.message || "", source: "lastAttempt" });
  }
  return reasons;
}

function DestinationReasons({ id, reasons, email = false, channel }: {
  id: string; reasons: SourcedReason[]; email?: boolean; channel?: string;
}) {
  return (
    <div id={id} className="notify-destination-reasons">
      {reasons.map((item) => (
        <p key={item.reason} className="notify-destination-reason" data-reason={item.reason}>
          {item.source === "lastAttempt" ? "Last attempt: " : ""}{reasonText(item.reason, item.message, email, channel)}
        </p>
      ))}
    </div>
  );
}

export function NotifyDestinations({ onConnect }: { onConnect?: () => void } = {}) {
  const id = useId();
  const [editor, setEditor] = useState<Editor>({ server: null, drafts: {} });
  const [collapsedCategories, setCollapsedCategories] = useState<Record<string, boolean>>({});
  const [channels, setChannels] = useState<NotificationSlackChannel[]>([]);
  const [slackConfigured, setSlackConfigured] = useState<boolean | null>(null);
  const [loading, setLoading] = useState(true);
  const [channelsLoading, setChannelsLoading] = useState(true);
  const [readError, setReadError] = useState("");
  const [channelsError, setChannelsError] = useState("");
  const [writeErrors, setWriteErrors] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const [needsRefresh, setNeedsRefresh] = useState(false);
  const [feedback, setFeedback] = useState("");
  const [noPermission, setNoPermission] = useState(false);
  const emailDrafts = useRef<Record<string, string>>({});
  const scope = useRef<AbortController | null>(null);
  const flight = useRef(false);
  const saved = useRef<Picks>({});

  const refresh = useCallback(async (signal: AbortSignal) => {
    setLoading(true);
    setReadError("");
    const result = await getNotificationDestinations(signal);
    if (signal.aborted) return false;
    setLoading(false);
    if (result.ok === false) {
      setNoPermission(result.status === 401 || result.status === 403);
      setReadError("Notifications could not be loaded.");
      return false;
    }
    setNoPermission(false);
    const acknowledged = saved.current;
    setEditor((previous) => refreshEditor(previous, result.data, acknowledged));
    saved.current = {};
    setNeedsRefresh(false);
    return true;
  }, []);

  const loadChannels = useCallback(async (signal: AbortSignal) => {
    setChannelsLoading(true);
    setChannelsError("");
    const options = new Map<string, NotificationSlackChannel>();
    let after = "";
    while (!signal.aborted) {
      const result = await getNotificationSlackChannels(after, signal);
      if (signal.aborted) return;
      if (result.ok === false) {
        setChannelsError(result.status === 403 ? "You do not have permission to view Slack channels." : "Slack channels could not be loaded.");
        setChannelsLoading(false);
        return;
      }
      const page = result.data;
      for (const channel of page.channels) options.set(channel.channel, channel);
      if (!page.configured || !page.nextCursor) {
        setSlackConfigured(page.configured);
        setChannels(page.configured ? [...options.values()] : []);
        setChannelsLoading(false);
        return;
      }
      if (page.nextCursor <= after) {
        setChannelsError("Slack channels could not be loaded.");
        setChannelsLoading(false);
        return;
      }
      after = page.nextCursor;
    }
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    scope.current = controller;
    void refresh(controller.signal);
    void loadChannels(controller.signal);
    return () => {
      controller.abort();
      scope.current = null;
    };
  }, [loadChannels, refresh]);

  const kinds = editor.server?.destinations ?? [];
  const changed = kinds.filter((row) => editor.drafts[row.kind] && !samePicks(row, editor.drafts[row.kind]));
  const groups = new Map<string, NotificationDestination[]>();
  for (const row of kinds) {
    const name = category(row.kind);
    groups.set(name, [...(groups.get(name) ?? []), row]);
  }
  const options = new Map(channels.map((channel) => [channel.channel, channel]));
  // Saved destinations remain removable when their connection or discovery is unavailable.
  const channelIds = [...new Set([
    ...(slackConfigured === true ? options.keys() : []),
    ...kinds.flatMap((row) => [...row.slackChannels, ...(editor.drafts[row.kind]?.slackChannels ?? [])]),
  ])];
  const showEmail = !!editor.server && (editor.server.email.available
    || editor.server.email.reason !== "email_not_configured"
    || kinds.some((row) => row.email !== null || editor.drafts[row.kind]?.email != null));
  const inApp = editor.server?.inApp;
  const inAppDestination = inApp?.destination || "in-app:";
  // A saved in-app pick or webhook id stays removable, the same rule the Slack ids follow.
  const showInApp = !!editor.server && (inApp?.configured === true
    || kinds.some((row) => inAppPicked(row) || inAppPicked(editor.drafts[row.kind])));
  const webhookOptions = new Map<string, NotificationWebhookDestination>(
    (editor.server?.webhooks?.destinations ?? []).map((hook) => [hook.id, hook]));
  const webhookIds = [...new Set([
    ...webhookOptions.keys(),
    ...kinds.flatMap((row) => [...savedWebhooks(row), ...savedWebhooks(editor.drafts[row.kind])]),
  ])];
  const columnCount = 1 + Number(showInApp) + Number(showEmail) + channelIds.length + webhookIds.length;

  function edit(kind: string, patch: Partial<NotificationDestinationPick>) {
    setEditor((previous) => ({
      ...previous,
      drafts: { ...previous.drafts, [kind]: { ...previous.drafts[kind], ...patch } },
    }));
    setWriteErrors((previous) => {
      const next = { ...previous };
      delete next[kind];
      return next;
    });
    setFeedback("");
  }

  async function save(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const signal = scope.current?.signal;
    if (!signal || signal.aborted || flight.current || loading || noPermission || needsRefresh || !changed.length) return;
    flight.current = true;
    setSaving(true);
    setFeedback("");
    setWriteErrors({});
    let failed = false;
    try {
      for (const row of changed) {
        const draft = picks(editor.drafts[row.kind]);
        const patch: Partial<NotificationDestinationPick> = {};
        if (!sameChannels(row.slackChannels, draft.slackChannels)) patch.slackChannels = draft.slackChannels;
        if (row.email !== draft.email) patch.email = draft.email;
        if (inAppPicked(row) !== draft.inApp) patch.inApp = draft.inApp;
        if (!sameChannels(savedWebhooks(row), draft.webhooks)) patch.webhooks = draft.webhooks;
        const result = await saveNotificationDestinations(row.kind, patch, signal);
        if (signal.aborted) return;
        if (result.ok === false) {
          setWriteErrors({ [row.kind]: result.message });
          failed = true;
          break;
        }
        // The write response has no projection. Only a fresh GET can replace server state.
        saved.current[row.kind] = draft;
        setNeedsRefresh(true);
      }
      if (Object.keys(saved.current).length) {
        const refreshed = await refresh(signal);
        if (!signal.aborted) {
          setFeedback(refreshed ? "" : "Saved picks need a status refresh.");
          if (refreshed && !failed) window.dispatchEvent(new CustomEvent(TOAST_EVENT, {
            detail: { text: "Notification preferences saved", tone: "info" },
          }));
        }
      }
    } finally {
      if (!signal.aborted) {
        flight.current = false;
        setSaving(false);
      }
    }
  }

  return (
    <div className="set-pane notify-destinations" aria-busy={loading || saving}>
      <h3 className="set-title set-h">Notifications</h3>
      {noPermission ? <p className="notify-empty" role="status">You do not have permission to view notifications</p> : readError ? (
        <div className="notify-error" role="alert">
          <p>{readError}</p>
          <button type="button" className="set-secondary notify-retry" disabled={loading || saving}
            onClick={() => { if (scope.current) void refresh(scope.current.signal); }}>Retry</button>
        </div>
      ) : null}
      {!editor.server && loading ? (
        <div className="set-skeleton notify-matrix-skeleton" role="status" aria-label="Loading notifications">
          {Array.from({ length: 6 }, (_, index) => <div className="notify-skeleton-row" key={index} aria-hidden="true">
            <span className="set-skeleton-line" /><span className="set-skeleton-line" /><span className="set-skeleton-line" />
          </div>)}
        </div>
      ) : editor.server && !noPermission ? (
        <form className="notify-form" onSubmit={(event) => void save(event)}>
          <div className="notify-slack-status">
            {slackConfigured === false ? (
              <p className="notify-slack-connect">Slack is not connected. <a href={connectorSetupRoute("slack")} onClick={onConnect}>Connect</a></p>
            ) : channelsLoading ? (
              <div className="set-skeleton notify-channel-loading" role="status" aria-label="Loading Slack channels">
                <span className="set-skeleton-line" aria-hidden="true" />
              </div>
            ) : !channelsError && slackConfigured === true && channels.length === 0 ? <p>No Slack channels available</p> : null}
            {channelsError ? (
              <div className="notify-error" role="alert">
                <p>{channelsError}</p>
                <button type="button" className="set-secondary notify-channels-retry" disabled={channelsLoading || saving}
                  onClick={() => { if (scope.current) void loadChannels(scope.current.signal); }}>Retry</button>
              </div>
            ) : null}
          </div>
          <div className="notify-matrix-scroll" role="region" aria-label="Notification preferences" tabIndex={0}>
            <table className="set-table notify-matrix" aria-label="Notification preferences by channel">
              <thead><tr>
                <th scope="col">Notification type</th>
                {showInApp ? <th scope="col" className="notify-channel-heading">In-app</th> : null}
                {showEmail ? <th scope="col" className="notify-channel-heading">Email</th> : null}
                {channelIds.map((channelId) => <th scope="col" className="notify-channel-heading" key={channelId}>
                  Slack<span className="notify-channel-name">{channelLabel(options.get(channelId), channelId)}</span>
                </th>)}
                {webhookIds.map((hookId) => <th scope="col" className="notify-channel-heading" key={`webhook:${hookId}`}>
                  Webhook<span className="notify-channel-name">{webhookOptions.get(hookId)?.label || hookId}</span>
                </th>)}
              </tr></thead>
              {[...groups].map(([name, rows]) => <tbody key={name} onInvalidCapture={() => {
                // Reveal invalid drafts before native form validation moves focus.
                if (collapsedCategories[name]) flushSync(() => setCollapsedCategories((previous) => ({ ...previous, [name]: false })));
              }}>
                <tr className="notify-category"><th scope="rowgroup" colSpan={columnCount}>
                  <button type="button" className="notify-category-toggle"
                    aria-expanded={!collapsedCategories[name]}
                    aria-controls={rows.map((row) => `${id}-${row.kind}-row`).join(" ")}
                    onClick={() => setCollapsedCategories((previous) => ({ ...previous, [name]: !previous[name] }))}>
                    <CaretRight size={16} className="notify-category-caret" aria-hidden="true" />
                    {name}
                  </button>
                </th></tr>
                {rows.map((row) => {
                  const draft = editor.drafts[row.kind] ?? picks(row);
                  const kindId = `${id}-${row.kind}`;
                  const emailDestination = `email:${draft.email?.trim() || ""}`;
                  const emailReadiness = row.readiness[emailDestination] ?? editor.server?.email;
                  const emailReasons = destinationReasons(row, emailDestination, emailReadiness);
                  const emailState = deliveryState(row, emailDestination, draft.email !== null,
                    draft.email !== row.email, emailReasons);
                  const inAppSelected = inAppPicked(draft);
                  const inAppReasons = destinationReasons(row, inAppDestination, row.readiness[inAppDestination] ?? inApp);
                  const inAppState = deliveryState(row, inAppDestination, inAppSelected, !inAppPicked(row), inAppReasons);
                  const draftWebhooks = savedWebhooks(draft);
                  return (
                    <tr key={row.kind} id={`${kindId}-row`} data-kind={row.kind} hidden={!!collapsedCategories[name]}>
                      <th scope="row" id={`${kindId}-title`} className="notify-event">
                        {row.label}
                        {writeErrors[row.kind] ? <p className="notify-write-error" role="alert">{writeErrors[row.kind]}</p> : null}
                      </th>
                      {showInApp ? <td className="notify-matrix-cell" data-destination={inAppDestination}>
                        <div className="notify-cell-content">
                          <label className="notify-choice">
                            <input type="checkbox" className="notify-channel-pick" checked={inAppSelected}
                              disabled={saving || loading || needsRefresh || (!inAppSelected && inApp?.available !== true)}
                              aria-label={`${row.label}: in-app`}
                              aria-describedby={`${kindId}-in-app-state${inAppReasons.length ? ` ${kindId}-in-app-reason` : ""}`}
                              onChange={(event) => edit(row.kind, { inApp: event.target.checked })} />
                          </label>
                          <span id={`${kindId}-in-app-state`} className="notify-delivery-state"
                            data-state={inAppState === "Last attempt sent" ? "sent" : undefined}>{inAppState}</span>
                          <DestinationReasons id={`${kindId}-in-app-reason`} reasons={inAppReasons} channel="In-app" />
                        </div>
                      </td> : null}
                      {showEmail ? <td className="notify-matrix-cell" data-destination={emailDestination}>
                        <div className="notify-cell-content">
                          <label className="notify-choice">
                            <input type="checkbox" className="notify-channel-pick" checked={draft.email !== null}
                              disabled={saving || loading || needsRefresh || (draft.email === null && !editor.server?.email.available)}
                              aria-label={`${row.label}: email`}
                              aria-describedby={`${kindId}-email-state${emailReasons.length ? ` ${kindId}-email-reason` : ""}`}
                              onChange={(event) => {
                                if (draft.email) emailDrafts.current[row.kind] = draft.email;
                                edit(row.kind, { email: event.target.checked ? emailDrafts.current[row.kind] || row.email || "" : null });
                              }} />
                          </label>
                          {draft.email !== null ? <input id={`${kindId}-email`} className="notify-email" type="email"
                            aria-label={`${row.label}: email address`} placeholder="Email address" autoComplete="email" required
                            maxLength={254} value={draft.email} disabled={saving || loading || needsRefresh}
                            aria-describedby={`${kindId}-email-state${emailReasons.length ? ` ${kindId}-email-reason` : ""}`}
                            onChange={(event) => edit(row.kind, { email: event.target.value })} /> : null}
                          <span id={`${kindId}-email-state`} className="notify-delivery-state"
                            data-state={emailState === "Last attempt sent" ? "sent" : undefined}>
                            {draft.email === "" ? "Enter an email address" : emailState}
                          </span>
                          <DestinationReasons id={`${kindId}-email-reason`} reasons={emailReasons} email />
                        </div>
                      </td> : null}
                      {channelIds.map((channelId) => {
                        const option = options.get(channelId);
                        const selected = draft.slackChannels.includes(channelId);
                        const unavailable = slackConfigured !== true || !option?.active;
                        const destination = `slack:${channelId}`;
                        let extra: Reason | undefined;
                        if (slackConfigured === false) extra = { reason: "not_configured", message: "" };
                        else if (option?.active === false) extra = { reason: "channel_inactive", message: "This channel is inactive." };
                        else if (!option) extra = channelsLoading || channelsError
                          ? { reason: "channel_unchecked", message: "Channel availability could not be checked." }
                          : { reason: "channel_unavailable", message: "This channel is no longer available." };
                        const reasons = destinationReasons(row, destination, row.readiness[destination], extra);
                        const reasonId = `${kindId}-${channelId}-reason`;
                        const label = channelLabel(option, channelId);
                        const state = deliveryState(row, destination, selected, !row.slackChannels.includes(channelId), reasons);
                        return (
                          <td key={channelId} className="notify-matrix-cell">
                            <ul className="notify-channel-list">
                              <li className="notify-channel notify-cell-content" data-destination={destination}>
                                <label className="notify-choice">
                                  <input type="checkbox" className="notify-channel-pick" value={channelId}
                                    checked={selected} disabled={saving || loading || needsRefresh || (!selected && unavailable)}
                                    aria-label={`${row.label}: Slack ${label}`}
                                    aria-describedby={`${kindId}-${channelId}-state${reasons.length ? ` ${reasonId}` : ""}`}
                                    onChange={(event) => edit(row.kind, {
                                      slackChannels: event.target.checked
                                        ? [...draft.slackChannels, channelId]
                                        : draft.slackChannels.filter((value) => value !== channelId),
                                    })} />
                                </label>
                                <span id={`${kindId}-${channelId}-state`} className="notify-delivery-state"
                                  data-state={state === "Last attempt sent" ? "sent" : undefined}>{state}</span>
                                <DestinationReasons id={reasonId} reasons={reasons} />
                              </li>
                            </ul>
                          </td>
                        );
                      })}
                      {webhookIds.map((hookId) => {
                        const hook = webhookOptions.get(hookId);
                        const selected = draftWebhooks.includes(hookId);
                        const destination = `webhook:${hookId}`;
                        const readiness = row.readiness[destination]
                          ?? hook ?? { available: false, reason: "webhook_not_configured", message: "" };
                        const reasons = destinationReasons(row, destination, readiness);
                        const cellId = `${kindId}-webhook-${hookId}`;
                        const label = hook?.label || hookId;
                        const state = deliveryState(row, destination, selected, !savedWebhooks(row).includes(hookId), reasons);
                        return (
                          <td key={destination} className="notify-matrix-cell" data-destination={destination}>
                            <div className="notify-cell-content">
                              <label className="notify-choice">
                                <input type="checkbox" className="notify-channel-pick" value={hookId}
                                  checked={selected} disabled={saving || loading || needsRefresh || (!selected && !hook)}
                                  aria-label={`${row.label}: webhook ${label}`}
                                  aria-describedby={`${cellId}-state${reasons.length ? ` ${cellId}-reason` : ""}`}
                                  onChange={(event) => edit(row.kind, {
                                    webhooks: event.target.checked
                                      ? [...draftWebhooks, hookId]
                                      : draftWebhooks.filter((value) => value !== hookId),
                                  })} />
                              </label>
                              <span id={`${cellId}-state`} className="notify-delivery-state"
                                data-state={state === "Last attempt sent" ? "sent" : undefined}>{state}</span>
                              <DestinationReasons id={`${cellId}-reason`} reasons={reasons} channel="Webhook" />
                            </div>
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>)}
              {kinds.length === 0 ? <tbody><tr><td colSpan={columnCount} className="notify-empty">No notifications available</td></tr></tbody> : null}
            </table>
          </div>
          {columnCount === 1 && kinds.length > 0 && !channelsLoading && !channelsError
            ? <p className="notify-empty" role="status">No notification channels connected</p> : null}
          <div className="set-actions notify-actions">
            <button type="submit" className="set-primary notify-save"
              disabled={saving || loading || needsRefresh || changed.length === 0}>
              <Busy busy={saving} idle={Object.keys(writeErrors).length ? "Retry save" : "Save"} doing="Saving" />
            </button>
            <p className="notify-save-status" role="status">{feedback || (loading ? "Refreshing destinations" : "")}</p>
          </div>
        </form>
      ) : null}
    </div>
  );
}

export default NotifyDestinations;