'use client';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { listOwners } from '@/features/owners/api.client';
import {
  cancelServiceKeyRotation,
  createServiceKey,
  deleteServiceKey,
  getServiceKey,
  getServiceKeyClientSecret,
  getServiceKeyToken,
  listServiceKeys,
  rotateServiceKey,
  rotateServiceKeyClientSecret,
  scheduleServiceKeyRotation,
  updateServiceKey,
  type CreatedServiceKey,
  type ServiceKey,
  type ServiceKeyStatus,
} from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { SuBadge, useCopy } from '../settings-ui';
import {
  dayAndRelative,
  EXPIRY_CHOICES,
  expiryFor,
  formatWhen,
  lastUpdated,
  NAME_MAX,
  orderScopes,
  OVERLAP_CHOICES,
  overlapLabel,
  STATUS_LABEL,
  STATUS_TONE,
} from './data';
import { ScheduleRotation } from './ScheduleRotation';
import { ScopeChips, ScopeDrawer, useScopeCatalog } from './ScopeDrawer';
import { ServiceKeyLogs } from './ServiceKeyLogs';
import { ServiceKeyWebhooks } from './ServiceKeyWebhooks';
import { maskSecret, useSecret } from './useSecret';

/**
 * Settings › Integrations › Service Keys (4 Nov design: settings-service-keys.php, with the 6 Nov
 * decisions, HUB-687), on the API's /service-keys: the list, create / edit (name and HubSpot
 * scopes), and a key's page: show / copy / rotate the key (now, later or scheduled), its client
 * secret, scopes, delete, its webhook, and the API call log. Where you are is in the URL, so a
 * reload or a link opens the same page: `?key=<id>` a key's page (`&tab=logs|webhooks`, `&edit=1`
 * its Edit page), `?new=1` the Create page.
 */

type View = 'list' | 'create' | 'detail';
type DetailTab = 'overview' | 'logs' | 'webhooks';
type StatusFilter = '' | ServiceKeyStatus;

interface ModalButton {
  label: string;
  primary?: boolean;
  /** Runs without closing the modal (e.g. Copy). */
  onClick?: () => void;
}
interface Modal {
  title: string;
  body: ReactNode;
  buttons: ModalButton[];
  /** False: Escape and the backdrop don't close it (the new key). */
  dismissable: boolean;
  /** The button pressed (its index), or null when closed. */
  done: (action: number | null) => void;
}
type OpenModal = (
  title: string,
  body: ReactNode,
  buttons: ModalButton[],
  dismissable?: boolean,
) => Promise<number | null>;

const svg = (d: ReactNode) => (
  <svg viewBox="0 0 24 24" aria-hidden="true">
    {d}
  </svg>
);
const ICON = {
  plus: svg(<path d="M12 5v14M5 12h14" />),
  chevron: svg(<path d="m9 18 6-6-6-6" />),
  back: svg(<path d="m15 18-6-6 6-6M9 12h11" />),
  close: svg(<path d="m6 6 12 12M18 6 6 18" />),
  trash: svg(<path d="M4 7h16M9 7V4h6v3m3 0-1 13H7L6 7m3 3v7m6-7v7" />),
};

const STATUS_FILTERS: Array<{ value: StatusFilter; label: string }> = [
  { value: '', label: 'All statuses' },
  { value: 'active', label: 'Active' },
  { value: 'expired', label: 'Expired' },
  { value: 'revoked', label: 'Revoked' },
];

const TAB_BUTTONS: Record<DetailTab, string> = {
  overview: 'View Overview',
  logs: 'View Logs',
  webhooks: 'Webhooks',
};

const KEY_409 =
  'This key was created before keys could be shown again. Rotate it to get a new key you can see here.';

const masked = (prefix: string) => `${prefix}••••••••••••••••`;
const same = (a: readonly string[], b: readonly string[]) => a.join('\n') === b.join('\n');

export function ServiceKeysView() {
  const toast = useToast();
  const copy = useCopy();
  const { catalog, error: catalogError } = useScopeCatalog();
  const [keys, setKeys] = useState<ServiceKey[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [names, setNames] = useState<Map<string, string>>(new Map());
  const [query, setQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('');
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const creating = params.get('new') === '1';
  const activeId = creating ? null : params.get('key');
  const editing = Boolean(activeId) && params.get('edit') === '1';
  const tabParam = params.get('tab');
  const detailTab: DetailTab =
    tabParam === 'logs' || tabParam === 'webhooks' ? tabParam : 'overview';
  const view: View = creating || editing ? 'create' : activeId ? 'detail' : 'list';
  const [name, setName] = useState('');
  const [expiry, setExpiry] = useState<(typeof EXPIRY_CHOICES)[number]['value']>('never');
  /** A pasted name was longer than NAME_MAX and was cut: said under the field. */
  const [nameCut, setNameCut] = useState(false);
  const [selected, setSelected] = useState<string[]>([]);
  const [formError, setFormError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [busy, setBusy] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [rotateOpen, setRotateOpen] = useState(false);
  const [scheduleOpen, setScheduleOpen] = useState(false);
  const [modal, setModal] = useState<Modal | null>(null);
  const nameRef = useRef<HTMLInputElement>(null);
  const rotateRef = useRef<HTMLDivElement>(null);

  const loadKeys = useCallback(() => {
    setLoadError(null);
    setKeys(null);
    listServiceKeys().then(setKeys, (err: unknown) => setLoadError(errorText(err)));
  }, []);

  useEffect(() => {
    loadKeys();
    listOwners({ limit: 500 }).then(
      (res) => setNames(new Map(res.data.map((o) => [o.userId, o.name]))),
      () => undefined,
    );
  }, [loadKeys]);

  const active = (keys ?? []).find((k) => k.id === activeId) ?? null;
  const revoked = active?.status === 'revoked';
  const replace = (key: ServiceKey) =>
    setKeys((cur) => (cur ?? []).map((k) => (k.id === key.id ? stripToken(key) : k)));

  /** Opens the list, the Create page, a key's page (a tab) or its Edit page, in the URL. */
  const go = (
    to: { key?: string; tab?: DetailTab; edit?: boolean; create?: boolean },
    replaceEntry = false,
  ) => {
    const q = new URLSearchParams();
    if (to.create) q.set('new', '1');
    else if (to.key) {
      q.set('key', to.key);
      if (to.edit) q.set('edit', '1');
      else if (to.tab && to.tab !== 'overview') q.set('tab', to.tab);
    }
    const search = q.toString();
    const href = search ? `${pathname}?${search}` : pathname;
    if (replaceEntry) router.replace(href);
    else router.push(href);
    setRotateOpen(false);
    setScheduleOpen(false);
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  // The Create / Edit form is filled as it opens (an Edit page reloaded: once the key is in).
  const formFor = view === 'create' ? (editing ? activeId : 'new') : null;
  const [formOf, setFormOf] = useState<string | null>(null);
  if (formFor !== formOf && !(editing && formFor !== null && !active)) {
    setFormOf(formFor);
    if (formFor !== null) {
      const from = editing ? active : null;
      setName(from?.name ?? '');
      setExpiry('never');
      setSelected(from ? from.scopes : []);
      setFormError(null);
      setNameCut(false);
    }
  }

  // A key's page: the list may be a while old, so read last used, status and the rest again.
  const detailId = view === 'detail' ? activeId : null;
  useEffect(() => {
    if (!detailId) return;
    getServiceKey(detailId).then(
      (key) => setKeys((cur) => cur && cur.map((k) => (k.id === key.id ? key : k))),
      () => undefined,
    );
  }, [detailId]);

  const openModal: OpenModal = (title, body, buttons, dismissable = true) =>
    new Promise<number | null>((resolve) =>
      setModal({
        title,
        body,
        buttons,
        dismissable,
        done: (action) => {
          setModal(null);
          resolve(action);
        },
      }),
    );

  const openCreate = (isEdit: boolean) =>
    go(isEdit && activeId ? { key: activeId, edit: true } : { create: true });
  const openDetail = (id: string, tab: DetailTab = 'overview') => go({ key: id, tab });
  /** Name or scopes changed: an error about the last try (e.g. no scope) no longer applies. */
  const formChanged = () => setFormError(null);

  /** The new key, after create or rotate. It can be shown again on the key's page. */
  const showToken = (key: CreatedServiceKey, rotated: boolean) =>
    openModal(
      rotated ? 'Service key rotated' : 'Service key created',
      <>
        <p>
          {rotated ? (
            <>
              A new key has been generated for <strong>{key.name}</strong>. Update your integrations
              with it.
            </>
          ) : (
            <>
              <strong>{key.name}</strong> has been created.
            </>
          )}{' '}
          Copy the key and store it securely. You can show it again on this key&apos;s page.
        </p>
        <div className="sk-generated-secret">
          <code>{key.token}</code>
        </div>
        {rotated ? (
          <p className="crm-mt-2">
            {key.previousKeyExpiresAt
              ? `The previous key keeps working until ${formatWhen(key.previousKeyExpiresAt)}.`
              : 'The previous key has stopped working.'}
          </p>
        ) : null}
      </>,
      [
        { label: 'Copy key', onClick: () => void copy(key.token) },
        { label: 'Done', primary: true },
      ],
      false,
    );

  const createOrSave = async () => {
    const trimmed = name.trim();
    const fail = (message: string, focusName = false) => {
      setFormError(message);
      if (focusName) nameRef.current?.focus();
    };
    if (!trimmed) return fail('Enter a name for this service key.', true);
    const duplicate = (keys ?? []).some(
      (k) =>
        k.status !== 'revoked' &&
        k.name.toLowerCase() === trimmed.toLowerCase() &&
        (!editing || k.id !== activeId),
    );
    if (duplicate) {
      return fail('A service key with this name already exists. Choose a unique name.', true);
    }
    if (!selected.length) return fail('Select at least one scope.');
    const scopes = orderScopes(selected, catalog);
    setFormError(null);
    setSaving(true);
    try {
      if (editing && active) {
        const body: { name?: string; scopes?: string[] } = {};
        if (trimmed !== active.name) body.name = trimmed;
        if (!same(scopes, orderScopes(active.scopes, catalog))) body.scopes = scopes;
        if (Object.keys(body).length) {
          replace(await updateServiceKey(active.id, body));
          toast('Service key saved', 'success');
        } else {
          toast('Nothing to save', 'info');
        }
        go({ key: active.id }, true);
        return;
      }
      const expiresAt = expiryFor(expiry);
      const created = await createServiceKey({
        name: trimmed,
        scopes,
        ...(expiresAt ? { expiresAt } : {}),
      });
      setKeys((cur) => [stripToken(created), ...(cur ?? [])]);
      go({ key: created.id }, true);
      void showToken(created, false);
    } catch (err) {
      setFormError(errorText(err));
    } finally {
      setSaving(false);
    }
  };

  const confirmDelete = () => {
    if (!active) return;
    const key = active;
    void openModal(
      'Delete this service key?',
      <p>
        <strong>{key.name}</strong> stops working from its next request
        {key.previousKeyExpiresAt ? ', and so does its previous key' : ''}. Its webhook is deleted
        too, and the key is removed from this list. This can&apos;t be undone.
      </p>,
      [{ label: 'Cancel' }, { label: 'Delete service key', primary: true }],
    ).then(async (action) => {
      if (action !== 1) return;
      setBusy(true);
      try {
        await deleteServiceKey(key.id);
        setKeys((cur) => (cur ?? []).filter((k) => k.id !== key.id));
        go({}, true);
        toast(`${key.name} deleted`, 'success');
      } catch (err) {
        toast(errorText(err), 'danger');
      } finally {
        setBusy(false);
      }
    });
  };

  const rotate = async (key: ServiceKey, overlapHours: number) => {
    setBusy(true);
    try {
      const rotated = await rotateServiceKey(key.id, overlapHours);
      replace(rotated);
      void showToken(rotated, true);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  /** later: keep the old key working for a while (up to 7 days), so its system can switch. */
  const confirmRotate = (later: boolean) => {
    if (!active || revoked) return;
    const key = active;
    // The modal is gone when its promise resolves: keep what was chosen here.
    let hours: number = OVERLAP_CHOICES[1].hours;
    void openModal(
      later ? 'Rotate and expire this token later' : 'Rotate and expire this token now?',
      later ? (
        <>
          <p>
            <strong>{key.name}</strong> gets a new key. The current key keeps working for the time
            you choose, so you can switch your integration over without downtime.
          </p>
          <label className="sk-modal-label">
            Keep the old key working for
            <select
              className="input"
              defaultValue={String(hours)}
              onChange={(e) => (hours = Number(e.target.value))}
            >
              {OVERLAP_CHOICES.map((c) => (
                <option key={c.hours} value={c.hours}>
                  {c.label}
                </option>
              ))}
            </select>
          </label>
        </>
      ) : (
        <p>
          Rotating <strong>{key.name}</strong> creates a new key and the current one stops working
          at once. Update any applications using it to avoid interruption.
        </p>
      ),
      [{ label: 'Cancel' }, { label: 'Rotate key', primary: true }],
    ).then((action) => {
      if (action !== 1) return;
      void rotate(key, later ? hours : 0);
    });
  };

  const closeSchedule = useCallback(() => setScheduleOpen(false), []);
  /** From the Schedule rotation dialog, which shows a rejection itself. */
  const scheduleRotation = async (key: ServiceKey, at: string, overlapHours: number) => {
    replace(await scheduleServiceKeyRotation(key.id, at, overlapHours));
    setScheduleOpen(false);
    toast(`Rotation scheduled for ${formatWhen(at)}`, 'success');
  };

  const cancelSchedule = async () => {
    if (!active) return;
    setBusy(true);
    try {
      replace(await cancelServiceKeyRotation(active.id));
      toast('Scheduled rotation cancelled', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const learnMore = (e: React.MouseEvent) => {
    e.preventDefault();
    void openModal(
      'About service keys',
      <p>
        Service keys let AdMedia&apos;s own systems call the CRM API, sent as{' '}
        <code>Authorization: Bearer crm_sk_…</code>. Choose only the scopes the integration needs
        and store the key securely.
      </p>,
      [{ label: 'Got it', primary: true }],
    );
  };

  // Escape closes the modal, then the rotate menu (the scope drawer closes itself); a click
  // outside the rotate menu closes it.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      if (modal) {
        if (modal.dismissable) modal.done(null);
      } else setRotateOpen(false);
    };
    const onClick = (e: MouseEvent) => {
      if (rotateRef.current && !rotateRef.current.contains(e.target as Node)) setRotateOpen(false);
    };
    document.addEventListener('keydown', onKey);
    document.addEventListener('click', onClick);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('click', onClick);
    };
  }, [modal]);
  useEffect(() => {
    document.body.classList.toggle('sk-modal-open', Boolean(modal) || drawerOpen || scheduleOpen);
    return () => document.body.classList.remove('sk-modal-open');
  }, [modal, drawerOpen, scheduleOpen]);

  const shown = useMemo(() => {
    const q = query.trim().toLowerCase();
    return (keys ?? []).filter(
      (k) =>
        (!statusFilter || k.status === statusFilter) &&
        (!q ||
          k.name.toLowerCase().includes(q) ||
          k.id.toLowerCase().includes(q) ||
          (k.description ?? '').toLowerCase().includes(q) ||
          (k.ownerLabel ?? '').toLowerCase().includes(q) ||
          k.tokenPrefix.toLowerCase().includes(q) ||
          k.scopes.some((s) => s.includes(q))),
    );
  }, [keys, query, statusFilter]);
  const activeCount = (keys ?? []).filter((k) => k.status === 'active').length;

  const createdBy = active ? (names.get(active.createdBy) ?? 'A user') : '';

  return (
    <>
      <div className="sk-view sk-list-view" hidden={view !== 'list'}>
        <header className="set-head sk-page-head">
          <div>
            <h1 className="set-head__title">Service Keys</h1>
            <p className="set-head__sub">
              Create and manage service keys that provide secure access to your CRM data and APIs.
            </p>
          </div>
          <div className="set-head__actions">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => openCreate(false)}
            >
              {ICON.plus}
              <span>Create service key</span>
            </button>
          </div>
        </header>
        <section className="sk-table-card" aria-label="Service keys">
          <div className="su-toolbar" hidden={!keys?.length}>
            <label className="settings-nav__search su-search">
              <span className="crm-visually-hidden">Search service keys</span>
              <CrmIcon name="search" className="iconSize-16" />
              <input
                type="search"
                placeholder="Search service keys"
                autoComplete="off"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
              />
            </label>
            <label className="crm-visually-hidden" htmlFor="sk-status-filter">
              Status
            </label>
            <select
              id="sk-status-filter"
              className="input"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value as StatusFilter)}
            >
              {STATUS_FILTERS.map((f) => (
                <option key={f.value} value={f.value}>
                  {f.label}
                </option>
              ))}
            </select>
            <span className="su-toolbar__end su-count">
              {activeCount.toLocaleString()} active {activeCount === 1 ? 'key' : 'keys'}
            </span>
          </div>
          <div className="sk-table-wrap" hidden={!shown.length}>
            <table className="sk-table">
              <thead>
                {/* HubSpot's Service Keys list: Name, Last Updated, Service Key ID. */}
                <tr>
                  <th scope="col">Name</th>
                  <th scope="col">Last Updated</th>
                  <th scope="col">Service Key ID</th>
                </tr>
              </thead>
              <tbody>
                {shown.map((k) => {
                  const updated = lastUpdated(k);
                  return (
                    <tr key={k.id}>
                      <td className="sk-name-cell">
                        <button
                          type="button"
                          className="sk-link sk-name"
                          title={k.name}
                          onClick={() => openDetail(k.id)}
                        >
                          {k.name}
                        </button>
                        {/* No status column on HubSpot: only a key that no longer works says so. */}
                        {k.status !== 'active' ? (
                          <>
                            {' '}
                            <SuBadge tone={STATUS_TONE[k.status]}>{STATUS_LABEL[k.status]}</SuBadge>
                          </>
                        ) : null}
                      </td>
                      {/* settings-pages.css capitalises a settings table's 2nd column. */}
                      <td
                        className="crm-text-nowrap"
                        style={{ textTransform: 'none' }}
                        title={formatWhen(updated)}
                      >
                        {dayAndRelative(updated)}
                      </td>
                      {/* QA #928: the id breaks at 1280px instead of running off the card. */}
                      <td style={{ overflowWrap: 'anywhere', minWidth: 140 }}>
                        <span className="su-mono">{k.id}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {loadError ? (
            <div className="sk-empty" role="alert">
              <strong>Couldn&apos;t load service keys</strong>
              <p>{loadError}</p>
              <button type="button" className="btn-crm btn-crm--outline" onClick={loadKeys}>
                Try again
              </button>
            </div>
          ) : keys === null ? (
            <div className="sk-empty">
              <p>Loading service keys…</p>
            </div>
          ) : !keys.length ? (
            <div className="sk-empty">
              <strong>No service keys yet</strong>
              <p>Create a service key to securely access your account through an API.</p>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                onClick={() => openCreate(false)}
              >
                {ICON.plus} Create service key
              </button>
            </div>
          ) : !shown.length ? (
            <div className="sk-empty">
              <strong>No service keys match</strong>
              <p>Try another search or status.</p>
            </div>
          ) : null}
        </section>
      </div>

      {view !== 'list' && !creating && !active ? (
        // A key's page or Edit page opened from the URL: the list is loading, or the key is gone.
        <div className="sk-view">
          <button type="button" className="sk-back" onClick={() => go({})}>
            {ICON.back}
            <span>Back to all Service Keys</span>
          </button>
          <div className="sk-empty" role={keys && !loadError ? 'alert' : undefined}>
            {loadError ? (
              <>
                <strong>Couldn&apos;t load service keys</strong>
                <p>{loadError}</p>
                <button type="button" className="btn-crm btn-crm--outline" onClick={loadKeys}>
                  Try again
                </button>
              </>
            ) : keys === null ? (
              <p>Loading service key…</p>
            ) : (
              <>
                <strong>Service key not found</strong>
                <p>It may have been deleted, or the link is wrong.</p>
              </>
            )}
          </div>
        </div>
      ) : null}

      <div className="sk-view sk-create-view" hidden={view !== 'create' || (editing && !active)}>
        <div className="sk-create-topbar">
          <button
            type="button"
            className="sk-back"
            onClick={() => go(editing && activeId ? { key: activeId } : {})}
          >
            {ICON.back}
            <span>Back</span>
          </button>
          <strong>{editing ? 'Edit Service Key' : 'Create Service Key'}</strong>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            data-sk-submit-create
            disabled={!name.trim() || saving}
            onClick={() => void createOrSave()}
          >
            {saving ? 'Saving…' : editing ? 'Save' : 'Create'}
          </button>
        </div>
        <form
          className="sk-create-form"
          onSubmit={(e) => {
            e.preventDefault();
            void createOrSave();
          }}
        >
          <p className="sk-intro">
            Use service keys to streamline access to data in your CRM account.{' '}
            <a href="#" onClick={learnMore}>
              Learn more {ICON.chevron}
            </a>
          </p>
          <div className="sk-field">
            <label htmlFor="sk-name">Name</label>
            <p className="sk-help">
              This name will appear in some CRM tools like logs and other material. It must be
              unique to this account.
            </p>
            <input
              ref={nameRef}
              id="sk-name"
              name="name"
              type="text"
              maxLength={NAME_MAX}
              autoComplete="off"
              required
              placeholder="Enter a unique service key name"
              aria-describedby="sk-name-count"
              value={name}
              onPaste={(e) => {
                // maxLength cuts a longer paste without a word: say so.
                const el = e.currentTarget;
                const kept = el.value.length - ((el.selectionEnd ?? 0) - (el.selectionStart ?? 0));
                setNameCut(kept + e.clipboardData.getData('text').length > NAME_MAX);
              }}
              onChange={(e) => {
                setName(e.target.value);
                if (e.target.value.length < NAME_MAX) setNameCut(false);
                formChanged();
              }}
            />
            <div
              id="sk-name-count"
              className={nameCut ? 'sk-counter sk-counter--error' : 'sk-counter'}
              aria-live="polite"
            >
              {nameCut
                ? `Names can be up to ${NAME_MAX} characters; the pasted name was cut to fit.`
                : `${NAME_MAX - name.length} characters remaining`}
            </div>
          </div>
          {editing ? null : (
            <div className="sk-field">
              <label htmlFor="sk-expiry">Expiration</label>
              <p className="sk-help">
                The key stops working after this time. Pick &quot;Never expire&quot; for keys you
                rotate yourself.
              </p>
              <select
                id="sk-expiry"
                className="input"
                value={expiry}
                onChange={(e) => {
                  setExpiry(e.target.value as typeof expiry);
                  formChanged();
                }}
              >
                {EXPIRY_CHOICES.map((c) => (
                  <option key={c.value} value={c.value}>
                    {c.label}
                  </option>
                ))}
              </select>
            </div>
          )}
          <section className="sk-scope-section">
            <div className="sk-scope-intro">
              <h2>Scopes</h2>
              <p className="sk-help">
                Scopes determine what your service key can access and do in CRM. It&apos;s strongly
                encouraged to require as few scopes as possible for your needed functionality.
              </p>
            </div>
            <div className="sk-selected-head">
              <h3>Selected scopes</h3>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={() => setDrawerOpen(true)}
              >
                {ICON.plus} Add new scope
              </button>
            </div>
            <div className="sk-selected-scopes">
              <ScopeChips
                scopes={selected}
                catalog={catalog}
                onRemove={(s) => {
                  setSelected((cur) => cur.filter((x) => x !== s));
                  formChanged();
                }}
              />
            </div>
          </section>
          <div className="sk-form-error" role="alert" hidden={!formError}>
            {formError}
          </div>
        </form>
      </div>

      <div className="sk-view sk-detail-view" hidden={view !== 'detail' || !active}>
        <header className="sk-detail-head">
          <button type="button" className="sk-back" onClick={() => go({})}>
            {ICON.back}
            <span>Back to all Service Keys</span>
          </button>
          <div className="sk-detail-heading">
            <div className="sk-detail-title">
              {/* QA #933: no second, empty h1 on the list (this view is hidden there). */}
              {active ? (
                <h1>
                  {/* A long name ends in "…"; the whole name is in the tooltip. */}
                  <span className="sk-title-name" title={active.name}>
                    {active.name}
                  </span>
                  <SuBadge tone={STATUS_TONE[active.status]}>{STATUS_LABEL[active.status]}</SuBadge>
                </h1>
              ) : null}
              <p className="sk-help">
                {active?.description || 'Manage this service key, its scopes, and access.'}
              </p>
            </div>
            <div className="sk-detail-actions">
              {(['overview', 'logs', 'webhooks'] as const)
                .filter((t) => t !== detailTab)
                .map((t) => (
                  <button
                    key={t}
                    type="button"
                    className="btn-crm btn-crm--outline"
                    onClick={() => active && openDetail(active.id, t)}
                  >
                    {TAB_BUTTONS[t]}
                  </button>
                ))}
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                disabled={revoked || busy}
                title={revoked ? 'Revoked keys can’t be edited' : undefined}
                onClick={() => openCreate(true)}
              >
                Edit
              </button>
            </div>
          </div>
        </header>

        {active && detailTab === 'logs' ? <ServiceKeyLogs keyId={active.id} /> : null}

        {active && detailTab === 'webhooks' ? (
          <ServiceKeyWebhooks key={active.id} serviceKey={active} />
        ) : null}

        {active && detailTab === 'overview' ? (
          <>
            <KeyCredentials
              // A rotation gives a new key: read it again.
              key={`${active.id}-${active.rotatedAt ?? ''}`}
              serviceKey={active}
              openModal={openModal}
              revoked={revoked}
              rotateSlot={
                <div className="sk-rotate-wrap" ref={rotateRef}>
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline"
                    disabled={revoked || busy}
                    title={revoked ? 'Revoked keys can’t be rotated' : undefined}
                    onClick={() => setRotateOpen((v) => !v)}
                  >
                    {busy ? 'Working…' : 'Rotate'} {ICON.chevron}
                  </button>
                  <div className="sk-rotate-menu" hidden={!rotateOpen || revoked}>
                    <button
                      type="button"
                      onClick={() => {
                        setRotateOpen(false);
                        confirmRotate(false);
                      }}
                    >
                      Rotate and expire this token now
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setRotateOpen(false);
                        confirmRotate(true);
                      }}
                    >
                      Rotate and expire this token later
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setRotateOpen(false);
                        setScheduleOpen(true);
                      }}
                    >
                      Schedule rotation
                    </button>
                  </div>
                </div>
              }
              scheduleSlot={
                active.rotateAt ? (
                  <span className="sk-muted">
                    Rotation scheduled for <strong>{formatWhen(active.rotateAt)}</strong>
                    {active.rotateOverlapHours
                      ? `; the old key then keeps working ${overlapLabel(active.rotateOverlapHours)}`
                      : '; the old key then stops at once'}
                    .{' '}
                    <button
                      type="button"
                      className="sk-text-btn"
                      disabled={busy}
                      onClick={() => void cancelSchedule()}
                    >
                      Cancel
                    </button>
                  </span>
                ) : null
              }
            />

            <section className="sk-detail-card">
              <div className="sk-detail-card-heading">
                <h2>Details</h2>
              </div>
              <dl className="kv">
                <dt>Status</dt>
                <dd>
                  {STATUS_LABEL[active.status]}
                  {active.revokedAt
                    ? ` on ${formatWhen(active.revokedAt)}${
                        active.revokedBy ? ` by ${names.get(active.revokedBy) ?? 'a user'}` : ''
                      }`
                    : ''}
                </dd>
                <dt>Created</dt>
                <dd>
                  {formatWhen(active.createdAt)} by {createdBy}
                </dd>
                <dt>Last used</dt>
                <dd>
                  {active.lastUsedAt
                    ? `${formatWhen(active.lastUsedAt)}${active.lastUsedIp ? ` from ${active.lastUsedIp}` : ''}`
                    : 'Never'}
                </dd>
                <dt>Last rotated</dt>
                <dd>{formatWhen(active.rotatedAt)}</dd>
                {/* Set on keys made before HUB-687; the form doesn't ask for them for now. */}
                {active.expiresAt ? (
                  <>
                    <dt>Expires</dt>
                    <dd>{formatWhen(active.expiresAt)}</dd>
                  </>
                ) : null}
                {active.ipAllowlist.length ? (
                  <>
                    <dt>IP allow-list</dt>
                    <dd>{active.ipAllowlist.join(', ')}</dd>
                  </>
                ) : null}
              </dl>
            </section>

            <section className="sk-detail-card">
              <div className="sk-detail-card-heading">
                <h2>Scopes</h2>
                <span className="sk-count">
                  {active.scopes.length} {active.scopes.length === 1 ? 'scope' : 'scopes'}
                </span>
              </div>
              <div className="sk-detail-scopes">
                <ScopeChips scopes={active.scopes} catalog={catalog} />
              </div>
            </section>

            <section className="sk-danger-zone">
              <h2>Delete this Service Key</h2>
              <p className="crm-mb-2">
                Deleting <strong>{active.name}</strong> stops it working from its next request and
                deletes its webhook. Deleting a service key is permanent and can&apos;t be undone.
              </p>
              <button
                type="button"
                className="btn-crm btn-crm--outline sk-danger-btn"
                disabled={busy}
                onClick={confirmDelete}
              >
                {ICON.trash} Delete
              </button>
            </section>
          </>
        ) : null}
      </div>

      {scheduleOpen && active && !revoked && view === 'detail' ? (
        <ScheduleRotation
          serviceKey={active}
          onSchedule={(at, hours) => scheduleRotation(active, at, hours)}
          onClose={closeSchedule}
        />
      ) : null}

      {drawerOpen ? (
        <ScopeDrawer
          catalog={catalog}
          catalogError={catalogError}
          selected={selected}
          onApply={(next) => {
            setSelected(next);
            setDrawerOpen(false);
            formChanged();
          }}
          onClose={() => setDrawerOpen(false)}
        />
      ) : null}

      {/* Shared theme modal */}
      <div
        className="sk-modal-backdrop"
        hidden={!modal}
        onClick={(e) => {
          if (e.target === e.currentTarget && modal?.dismissable) modal.done(null);
        }}
      >
        {modal ? (
          <section
            className="sk-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="sk-modal-title"
          >
            <header className="sk-modal-head">
              <h2 id="sk-modal-title">{modal.title}</h2>
              <button
                type="button"
                className="sk-icon-btn"
                aria-label="Close"
                onClick={() => modal.done(null)}
              >
                {ICON.close}
              </button>
            </header>
            <div className="sk-modal-body">{modal.body}</div>
            <footer className="sk-modal-foot">
              {modal.buttons.map((b, i) => (
                <button
                  key={b.label}
                  type="button"
                  className={b.primary ? 'btn-crm btn-crm--primary' : 'btn-crm btn-crm--outline'}
                  onClick={() => (b.onClick ? b.onClick() : modal.done(i))}
                >
                  {b.label}
                </button>
              ))}
            </footer>
          </section>
        ) : null}
      </div>
    </>
  );
}

/**
 * The key and its client secret, read from the API only when shown or copied. Keys made before
 * HUB-687 can't be shown (409): the note says to rotate.
 */
function KeyCredentials({
  serviceKey,
  openModal,
  revoked,
  rotateSlot,
  scheduleSlot,
}: {
  serviceKey: ServiceKey;
  openModal: OpenModal;
  revoked: boolean;
  rotateSlot: ReactNode;
  scheduleSlot: ReactNode;
}) {
  const toast = useToast();
  const { id } = serviceKey;
  const loadToken = useCallback(async () => (await getServiceKeyToken(id)).token, [id]);
  const loadSecret = useCallback(
    async () => (await getServiceKeyClientSecret(id)).clientSecret,
    [id],
  );
  const token = useSecret(loadToken, KEY_409);
  const secret = useSecret(loadSecret, KEY_409);
  const [rotating, setRotating] = useState(false);
  const oldKeyUntil =
    serviceKey.previousKeyExpiresAt && Date.parse(serviceKey.previousKeyExpiresAt) > Date.now()
      ? serviceKey.previousKeyExpiresAt
      : null;

  const rotateSecret = () =>
    void openModal(
      'Rotate client secret?',
      <p>
        <strong>{serviceKey.name}</strong> gets a new client secret at once. Webhook events are
        signed with the new one from now on: update your receiver, or it will reject them.
      </p>,
      [{ label: 'Cancel' }, { label: 'Rotate secret', primary: true }],
    ).then(async (action) => {
      if (action !== 1) return;
      setRotating(true);
      try {
        secret.replace((await rotateServiceKeyClientSecret(id)).clientSecret);
        toast('Client secret rotated', 'success');
      } catch (err) {
        toast(errorText(err), 'danger');
      } finally {
        setRotating(false);
      }
    });

  return (
    <>
      <section className="sk-detail-card">
        <div className="sk-secret-head">
          <div>
            <h2>Service Key</h2>
            <p>Used to make API calls.</p>
          </div>
          <div className="sk-secret-value">
            <code>{token.shown && token.value ? token.value : masked(serviceKey.tokenPrefix)}</code>
            <div className="sk-secret-buttons">
              <button
                type="button"
                className="sk-text-btn"
                disabled={token.loading}
                onClick={() => void token.toggle()}
              >
                {token.shown ? 'Hide key' : 'Show key'}
              </button>
              <button
                type="button"
                className="sk-text-btn"
                disabled={token.loading}
                onClick={() => void token.copy()}
              >
                Copy
              </button>
            </div>
            {token.note ? <span className="sk-muted">{token.note}</span> : null}
            {oldKeyUntil ? (
              <span className="sk-muted">
                The previous key keeps working until {formatWhen(oldKeyUntil)}.
              </span>
            ) : null}
            {scheduleSlot}
          </div>
          {rotateSlot}
        </div>
      </section>

      <section className="sk-detail-card">
        <div className="sk-secret-head">
          <div>
            <h2>Client secret</h2>
            <p>Signs this key&apos;s webhook events (X-CRM-Signature).</p>
          </div>
          <div className="sk-secret-value">
            <code>
              {secret.shown && secret.value
                ? secret.value
                : maskSecret('00000000-0000-0000-0000-000000000000')}
            </code>
            <div className="sk-secret-buttons">
              <button
                type="button"
                className="sk-text-btn"
                disabled={secret.loading}
                onClick={() => void secret.toggle()}
              >
                {secret.shown ? 'Hide secret' : 'Show secret'}
              </button>
              <button
                type="button"
                className="sk-text-btn"
                disabled={secret.loading}
                onClick={() => void secret.copy()}
              >
                Copy
              </button>
            </div>
          </div>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            disabled={rotating || revoked}
            onClick={rotateSecret}
          >
            {rotating ? 'Working…' : 'Rotate'}
          </button>
        </div>
      </section>
    </>
  );
}

/** Keeps the key out of the list state. */
function stripToken(key: ServiceKey | CreatedServiceKey): ServiceKey {
  if (!('token' in key)) return key;
  const rest: Partial<CreatedServiceKey> = { ...key };
  delete rest.token;
  return rest as ServiceKey;
}
