'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  getConnection,
  getPrivateAppUsage,
  getWebhook,
  listPrivateAppRequests,
  listWebhookSubscriptions,
  WEBHOOK_EVENT_LABELS,
  type ApiRequest,
  type ApiUsage,
  type ConnectionDetail,
  type Webhook,
  type WebhookOwner,
  type WebhookSubscription,
} from '@/features/integrations/api.client';
import {
  deletePrivateApp,
  getPrivateAppClientSecret,
  getPrivateAppToken,
  rotatePrivateAppClientSecret,
  rotatePrivateAppToken,
  type CreatedPrivateApp,
  type PrivateApp,
} from '@/features/private-apps/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { OVERLAP_CHOICES, orderScopes, overlapLabel, scopeLabel } from '../service-keys/data';
import { useScopeCatalog } from '../service-keys/ScopeDrawer';
import { maskSecret, useSecret } from '../service-keys/useSecret';
import { ApiCallsLog } from './ApiCallsLog';
import { ago, buildChart, plural, when } from './data';
import { DeliveriesLog } from './DeliveriesLog';
import { SecurityLog } from './SecurityLog';
import { ICON, LaModal, S, useConfirm } from './ui';
import { objectLabel, useObjectChoices } from './WebhookEditor';

/**
 * One legacy (private) app (6 Nov design: app-sync-details.php): Overview, Auth (token and
 * client secret with Show / Copy / Rotate, scopes, delete), Logs and the app's webhook.
 */

export type Tab = 'overview' | 'auth' | 'logs' | 'webhooks';
type LogTab = 'api' | 'webhooks' | 'security';

const DAY_MS = 86_400_000;
const TOKEN_409 =
  'This token was created before tokens could be shown again. Rotate it to get a new token you can see here.';

/** The last 7 days of requests (at most 2,000), for the Overview chart and recent errors. */
async function loadWeek(id: string): Promise<{ rows: ApiRequest[]; capped: boolean }> {
  const since = Date.now() - 7 * DAY_MS;
  const rows: ApiRequest[] = [];
  let cursor: string | undefined;
  for (let page = 0; page < 4; page++) {
    const res = await listPrivateAppRequests(id, { limit: 500, cursor });
    rows.push(...res.data);
    cursor = res.nextCursor ?? undefined;
    const last = res.data[res.data.length - 1];
    if (!cursor || !last || Date.parse(last.createdAt) < since) {
      cursor = undefined;
      break;
    }
  }
  return { rows: rows.filter((r) => Date.parse(r.createdAt) >= since), capped: Boolean(cursor) };
}

/** Keeps the token out of the list state. */
export function withoutToken(app: PrivateApp | CreatedPrivateApp): PrivateApp {
  if (!('token' in app)) return app;
  const rest: Partial<CreatedPrivateApp> = { ...app };
  delete rest.token;
  return rest as PrivateApp;
}

export function AppDetail({
  app,
  initialTab = 'overview',
  onBack,
  onEdit,
  onChange,
  onDeleted,
}: {
  app: PrivateApp;
  initialTab?: Tab;
  onBack: () => void;
  /** Opens the Edit app page (on its Webhooks tab for "Edit webhooks"). */
  onEdit: (tab?: 'basic' | 'scopes' | 'webhooks') => void;
  onChange: (app: PrivateApp) => void;
  onDeleted: (id: string) => void;
}) {
  const toast = useToast();
  const [ask, confirmElement] = useConfirm();
  const { catalog } = useScopeCatalog();
  const objects = useObjectChoices();
  const [tab, setTab] = useState<Tab>(initialTab);
  const [logTab, setLogTab] = useState<LogTab>('api');
  const [connection, setConnection] = useState<ConnectionDetail | null>(null);
  const [connectionError, setConnectionError] = useState<string | null>(null);
  const [usage, setUsage] = useState<ApiUsage | null>(null);
  const [week, setWeek] = useState<{ rows: ApiRequest[]; capped: boolean } | null>(null);
  const [weekError, setWeekError] = useState<string | null>(null);
  const [hook, setHook] = useState<Webhook | null | undefined>(undefined);
  const [subs, setSubs] = useState<WebhookSubscription[]>([]);
  const [hookError, setHookError] = useState<string | null>(null);
  const [historyVersion, setHistoryVersion] = useState(0);
  const [rotateOpen, setRotateOpen] = useState(false);
  const [overlap, setOverlap] = useState<number>(OVERLAP_CHOICES[1].hours);
  const [busy, setBusy] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleteName, setDeleteName] = useState('');
  const [scopeSearch, setScopeSearch] = useState('');

  const revoked = Boolean(app.revokedAt);
  const owner = useMemo<WebhookOwner>(() => ({ kind: 'private_app', id: app.id }), [app.id]);
  const loadToken = useCallback(async () => (await getPrivateAppToken(app.id)).token, [app.id]);
  const loadSecret = useCallback(
    async () => (await getPrivateAppClientSecret(app.id)).clientSecret,
    [app.id],
  );
  const token = useSecret(loadToken, TOKEN_409);
  const secret = useSecret(loadSecret, TOKEN_409);

  useEffect(() => {
    getPrivateAppUsage(app.id).then(setUsage, () => undefined);
    loadWeek(app.id).then(setWeek, (err: unknown) => setWeekError(errorText(err)));
    getWebhook(owner).then(
      async (h) => {
        setHook(h);
        if (h) setSubs(await listWebhookSubscriptions(owner));
      },
      (err: unknown) => setHookError(errorText(err)),
    );
  }, [app.id, owner]);
  useEffect(() => {
    getConnection(`private_app:${app.id}`).then(setConnection, (err: unknown) =>
      setConnectionError(errorText(err)),
    );
  }, [app.id, historyVersion]);

  // A click outside the rotate popover closes it.
  useEffect(() => {
    if (!rotateOpen) return;
    const onClick = (e: MouseEvent) => {
      if (!(e.target as Element | null)?.closest('.asd-rotate-dropdown')) setRotateOpen(false);
    };
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setRotateOpen(false);
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [rotateOpen]);

  const chart = useMemo(() => buildChart(week?.rows ?? []), [week]);
  const recentErrors = (week?.rows ?? []).filter((r) => r.statusCode >= 400).slice(0, 6);
  const activity = connection?.activity ?? [];
  const lastChanged = [app.createdAt, app.rotatedAt, app.revokedAt, activity[0]?.createdAt]
    .filter((d): d is string => Boolean(d))
    .sort()
    .pop();
  const oldTokenUntil =
    app.previousTokenExpiresAt && Date.parse(app.previousTokenExpiresAt) > Date.now()
      ? app.previousTokenExpiresAt
      : null;

  const rotate = async (overlapHours: number) => {
    setRotateOpen(false);
    const later = overlapHours > 0;
    const a = await ask(
      later ? 'Rotate and expire this token later?' : 'Rotate and expire this token now?',
      <p>
        {later
          ? `${app.name} gets a new access token. The current one keeps working for ${overlapLabel(overlapHours)}, so you can update your integrations without downtime.`
          : `${app.name} gets a new access token and the current one stops working at once. Update any integrations using it to avoid interruption.`}
      </p>,
      [{ label: 'Cancel' }, { label: 'Rotate token', primary: true }],
    );
    if (a !== 1) return;
    setBusy(true);
    try {
      const rotated = await rotatePrivateAppToken(app.id, overlapHours);
      onChange(withoutToken(rotated));
      token.replace(rotated.token);
      setHistoryVersion((n) => n + 1);
      toast(
        later
          ? `Token rotated. The old one works until ${when(rotated.previousTokenExpiresAt)}.`
          : 'Token rotated. Update it in your integrations.',
        'success',
      );
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const rotateSecret = async () => {
    const a = await ask(
      'Rotate client secret?',
      <p>
        <b>{app.name}</b> 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 }],
    );
    if (a !== 1) return;
    setBusy(true);
    try {
      secret.replace((await rotatePrivateAppClientSecret(app.id)).clientSecret);
      setHistoryVersion((n) => n + 1);
      toast('Client secret rotated', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const remove = async () => {
    setBusy(true);
    try {
      await deletePrivateApp(app.id);
      setDeleteOpen(false);
      toast(`${app.name} deleted`, 'success');
      onDeleted(app.id);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const scopes = orderScopes(app.scopes, catalog);
  const q = scopeSearch.trim().toLowerCase();
  const shownScopes = scopes.filter(
    (s) => !q || s.toLowerCase().includes(q) || scopeLabel(s, catalog).toLowerCase().includes(q),
  );

  return (
    <>
      <header className="la-detail-head">
        <button type="button" className="la-back" onClick={onBack}>
          {ICON.back} Back to all apps
        </button>
        <div className="la-title-row">
          <div>
            <h1>
              {app.name}{' '}
              <span
                className={cn('badge', revoked ? 'badge--danger' : 'badge--success')}
                style={{ verticalAlign: 'middle' }}
              >
                {revoked ? 'Revoked' : 'Active'}
              </span>
            </h1>
            <p>{app.description || 'No description'}</p>
          </div>
          <div>
            <button type="button" className="btn-crm btn-crm--outline" onClick={() => onEdit()}>
              Edit app
            </button>
            <small>
              Last changed <b>{ago(lastChanged)}</b>
            </small>
          </div>
        </div>
      </header>
      <nav className="la-tabs" role="tablist">
        {(['overview', 'auth', 'logs', 'webhooks'] as const).map((t) => (
          <button
            key={t}
            type="button"
            role="tab"
            className={cn(tab === t && 'is-active')}
            aria-selected={tab === t}
            onClick={() => setTab(t)}
          >
            {t === 'auth' ? 'Auth' : t.charAt(0).toUpperCase() + t.slice(1)}
          </button>
        ))}
      </nav>
      <div className="la-support">
        <b>Legacy token</b>
        <span>
          This app signs in with a private-app token. For new integrations, create a service key.
        </span>
        <Link href="/settings/service-keys">Go to Service Keys {ICON.ext}</Link>
      </div>

      <section className="la-panel" hidden={tab !== 'overview'}>
        <p className="la-kicker">
          Overview of activity for the last 7 days
          {week?.capped ? ' (latest 2,000 calls)' : ''}
        </p>
        <div className="la-overview-grid">
          <article className="la-card la-chart-card">
            <h2>API calls</h2>
            <p>Number of API Calls</p>
            {weekError ? (
              <p className="field__help">{weekError}</p>
            ) : (
              <div className="la-chart" aria-busy={week === null}>
                <div className="la-y">
                  {chart.ticks.map((t) => (
                    <span key={t}>{Math.round(t)}</span>
                  ))}
                </div>
                <svg viewBox="0 0 760 180" preserveAspectRatio="none">
                  <path className="la-grid-lines" d="M0 10H760M0 62H760M0 114H760M0 166H760" />
                  <path className="la-area" d={chart.okArea} />
                  <path className="la-line" d={chart.okLine} />
                  <path
                    className="la-line"
                    d={chart.errLine}
                    style={{ stroke: 'var(--danger,#d92d20)', strokeDasharray: '5 4' }}
                  />
                </svg>
                <div className="la-x">
                  {chart.days.map((d) => (
                    <span key={d.label} title={`${d.ok} succeeded, ${d.err} errors`}>
                      {d.label}
                    </span>
                  ))}
                </div>
              </div>
            )}
            <div className="la-legend">
              <i />
              Succeeded
              <i style={{ marginLeft: 14, background: 'var(--danger,#d92d20)' }} />
              Errors
            </div>
          </article>
          <article className="la-card la-error-card">
            <h2>API CALL RECENT ERRORS</h2>
            {recentErrors.length ? (
              <table className="la-log-table" style={{ minWidth: 0 }}>
                <tbody>
                  {recentErrors.map((r) => (
                    <tr key={r.id}>
                      <td style={{ padding: '10px 6px' }}>
                        <span className="badge badge--danger">{r.statusCode}</span>
                      </td>
                      <td style={{ padding: '10px 6px', textTransform: 'none' }}>
                        <span className="su-mono">
                          {r.method} {r.route}
                        </span>
                        <small style={S.sub}>{when(r.createdAt)}</small>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="la-mini-empty">
                {ICON.empty}
                <b>{week === null && !weekError ? 'Loading…' : 'Nothing to show.'}</b>
                <p>{app.name} hasn&apos;t had any errors in the last 7 days.</p>
              </div>
            )}
          </article>
        </div>
        <article className="la-card" style={{ marginTop: 28 }}>
          <h2>Details</h2>
          <dl
            style={{
              display: 'grid',
              gridTemplateColumns: 'minmax(140px, 220px) 1fr',
              gap: '12px 24px',
              margin: 0,
              fontSize: 14,
            }}
          >
            <dt>Status</dt>
            <dd style={{ margin: 0 }}>{revoked ? `Revoked ${when(app.revokedAt)}` : 'Active'}</dd>
            <dt>Type</dt>
            <dd style={{ margin: 0 }}>Private (access token)</dd>
            <dt>Token</dt>
            <dd style={{ margin: 0 }}>
              <span className="su-mono">{app.tokenPrefix}…</span>
            </dd>
            <dt>Scopes</dt>
            <dd style={{ margin: 0 }}>
              <span className="su-mono">{scopes.join(', ')}</span>
            </dd>
            <dt>Created</dt>
            <dd style={{ margin: 0 }}>
              {when(app.createdAt)}
              {connection?.installedBy ? ` by ${connection.installedBy.name}` : ''}
            </dd>
            <dt>Last used</dt>
            <dd style={{ margin: 0 }}>{when(app.lastUsedAt)}</dd>
            <dt>Last 24 hours</dt>
            <dd style={{ margin: 0 }}>
              {usage
                ? `${plural(usage.calls24h, 'call')} · ${plural(usage.errors24h, 'error')} · ${usage.rateLimited24h.toLocaleString()} rate limited`
                : '…'}
            </dd>
          </dl>
        </article>
      </section>

      <section className="la-panel" hidden={tab !== 'auth'}>
        <div className="la-auth-note">
          {ICON.info} These credentials provide API access to your CRM account. Keep them safe and
          secure.
        </div>

        <div className="card asd-card">
          <div className="asd-card-head">
            <div>
              <h4>Access token</h4>
              <p>
                Used to make API calls: send it as <code>Authorization: Bearer &lt;token&gt;</code>.
              </p>
            </div>
            <div className="asd-rotate-dropdown">
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                aria-expanded={rotateOpen}
                disabled={revoked || busy}
                title={revoked ? 'Revoked apps can’t be rotated' : undefined}
                onClick={() => setRotateOpen((v) => !v)}
              >
                Rotate
                <svg viewBox="0 0 24 24" aria-hidden="true">
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </button>
              <div className="asd-rotate-popover" hidden={!rotateOpen}>
                <h5>Rotate access token</h5>
                <p>
                  Rotating will create a new token and let you keep the old one for up to 7 days.
                </p>
                <div>
                  <label>
                    Keep the old token working for
                    <select
                      className="input"
                      value={overlap}
                      onChange={(e) => setOverlap(Number(e.target.value))}
                    >
                      {OVERLAP_CHOICES.map((c) => (
                        <option key={c.hours} value={c.hours}>
                          {c.label}
                        </option>
                      ))}
                    </select>
                  </label>
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline btn-crm--sm"
                    onClick={() => void rotate(overlap)}
                  >
                    Rotate and expire this token later
                  </button>
                  <button
                    type="button"
                    className="btn-crm btn-crm--danger btn-crm--sm"
                    onClick={() => void rotate(0)}
                  >
                    Rotate and expire this token now
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div className="asd-auth-value-row">
            <span className="asd-mono" data-masked={!token.shown}>
              {token.shown && token.value
                ? token.value
                : `${app.tokenPrefix}••••-••••-••••-••••-••••••••••••`}
            </span>
            <div className="asd-auth-actions">
              <button
                type="button"
                className="asd-action-link"
                disabled={token.loading || revoked}
                onClick={() => void token.toggle()}
              >
                {token.shown ? 'Hide token' : 'Show token'}
              </button>
              <span className="asd-action-divider">|</span>
              <button
                type="button"
                className="asd-action-link"
                disabled={token.loading || revoked}
                onClick={() => void token.copy()}
              >
                Copy
              </button>
            </div>
          </div>
          {token.note ? <p className="asd-note">{token.note}</p> : null}
          {revoked ? (
            <p className="asd-note">This app was revoked {when(app.revokedAt)}.</p>
          ) : oldTokenUntil ? (
            <p className="asd-note">
              The previous token keeps working until {when(oldTokenUntil)}.
            </p>
          ) : null}
        </div>

        <div className="card asd-card">
          <div className="asd-card-head">
            <div>
              <h4>Client secret</h4>
              <p>
                Used for signature validation: this app&apos;s webhook events are signed with it (
                <code>X-CRM-Signature</code>).
              </p>
            </div>
          </div>
          <div className="asd-auth-value-row">
            <span className="asd-mono" data-masked={!secret.shown}>
              {secret.shown && secret.value
                ? secret.value
                : maskSecret('00000000-0000-0000-0000-000000000000')}
            </span>
            <div className="asd-auth-actions">
              <button
                type="button"
                className="asd-action-link"
                disabled={secret.loading}
                onClick={() => void secret.toggle()}
              >
                {secret.shown ? 'Hide secret' : 'Show secret'}
              </button>
              <span className="asd-action-divider">|</span>
              <button
                type="button"
                className="asd-action-link"
                disabled={secret.loading}
                onClick={() => void secret.copy()}
              >
                Copy
              </button>
              <span className="asd-action-divider">|</span>
              <button
                type="button"
                className="asd-action-link"
                disabled={busy || revoked}
                onClick={() => void rotateSecret()}
              >
                Rotate
              </button>
            </div>
          </div>
        </div>

        <div className="card asd-card">
          <div className="asd-card-head">
            <div>
              <h4>Scopes</h4>
              <p>
                Permissions this app has been granted.{' '}
                <button type="button" className="asd-action-link" onClick={() => onEdit('scopes')}>
                  Edit scopes
                </button>
              </p>
            </div>
            <div style={{ width: 240, maxWidth: '100%' }}>
              <label className="lp-search lp-search--pill lp-search--sm">
                <span className="la-sr-only">Search scopes</span>
                <input
                  type="search"
                  placeholder="Search scopes"
                  value={scopeSearch}
                  onChange={(e) => setScopeSearch(e.target.value)}
                />
              </label>
            </div>
          </div>
          <div className="asd-scopes-wrap">
            <div className="asd-scopes-grid" data-la-scopes>
              {shownScopes.map((s) => (
                <span key={s} className="asd-scope-badge" title={scopeLabel(s, catalog)}>
                  {s}
                </span>
              ))}
              {!shownScopes.length ? (
                <span className="asd-note">No scopes match your search.</span>
              ) : null}
            </div>
          </div>
        </div>

        <div className="card asd-card">
          <div className="asd-card-head">
            <div>
              <h4>Token history</h4>
              <p>Who created, rotated or changed this app&apos;s token.</p>
            </div>
          </div>
          <SecurityLog activity={connection ? activity : null} error={connectionError} compact />
        </div>

        <div className="card asd-card asd-card--danger">
          <div className="asd-card-head">
            <div>
              <h4>Delete this app</h4>
              <p>
                Delete {app.name}. This will delete its access token and its webhook, and remove the
                app from your account.
              </p>
            </div>
          </div>
          <button
            type="button"
            className="btn-crm btn-crm--danger"
            disabled={busy}
            onClick={() => {
              setDeleteName('');
              setDeleteOpen(true);
            }}
          >
            Delete this app
          </button>
        </div>
      </section>

      <section className="la-panel" hidden={tab !== 'logs'}>
        <nav className="la-log-tabs">
          {(['api', 'webhooks', 'security'] as const).map((t) => (
            <button
              key={t}
              type="button"
              role="tab"
              className={cn(logTab === t && 'is-active')}
              aria-selected={logTab === t}
              onClick={() => setLogTab(t)}
            >
              {t === 'api' ? 'API calls' : t === 'webhooks' ? 'Webhooks' : 'Security'}
            </button>
          ))}
        </nav>
        <div className="la-log-panel" hidden={logTab !== 'api'}>
          <ApiCallsLog appId={app.id} usage={usage} />
        </div>
        <div className="la-log-panel" hidden={logTab !== 'webhooks'}>
          <DeliveriesLog owner={owner} hasWebhook={hook === undefined ? null : Boolean(hook)} />
        </div>
        <div className="la-log-panel" hidden={logTab !== 'security'}>
          <SecurityLog activity={connection ? activity : null} error={connectionError} />
        </div>
      </section>

      <section className="la-panel" hidden={tab !== 'webhooks'}>
        {hookError ? (
          <div className="asd-empty-state">
            <h3 className="asd-empty-title">Couldn&apos;t load the webhook</h3>
            <p className="asd-empty-desc">{hookError}</p>
          </div>
        ) : hook === undefined ? (
          <div className="asd-empty-state">
            <p className="asd-empty-desc">Loading webhook…</p>
          </div>
        ) : !hook || !subs.length ? (
          <div className="asd-empty-state">
            <svg className="asd-empty-icon" viewBox="0 0 24 24" aria-hidden="true">
              <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
            </svg>
            <h3 className="asd-empty-title">Create a subscription to get started</h3>
            <p className="asd-empty-desc">
              {hook
                ? `Events go to ${hook.targetUrl}, but nothing is subscribed yet.`
                : 'Webhook subscriptions allow your app to respond in real time to events happening in CRM.'}
            </p>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => onEdit('webhooks')}
            >
              Edit webhooks
            </button>
          </div>
        ) : (
          <article className="la-card">
            <div
              className="la-log-search-row"
              style={{ justifyContent: 'space-between', marginTop: 0 }}
            >
              <div>
                <h2 style={{ margin: '0 0 4px' }}>
                  Webhook{' '}
                  <span
                    className={cn(
                      'badge',
                      hook.status === 'active'
                        ? 'badge--success'
                        : hook.status === 'failing'
                          ? 'badge--warning'
                          : hook.pausedReason === 'failing'
                            ? 'badge--danger'
                            : '',
                    )}
                  >
                    {hook.status === 'paused'
                      ? hook.pausedReason === 'failing'
                        ? 'Paused after failures'
                        : 'Paused'
                      : hook.status === 'failing'
                        ? 'Failing'
                        : 'Active'}
                  </span>
                </h2>
                <span className="su-mono" style={S.keep}>
                  {hook.targetUrl}
                </span>
                <small style={S.sub}>
                  {hook.maxEventsPerMinute
                    ? `At most ${hook.maxEventsPerMinute.toLocaleString()} events a minute`
                    : 'No event throttling'}{' '}
                  · last success {ago(hook.lastSuccessAt)}
                  {hook.lastError ? ` · last error: ${hook.lastError}` : ''}
                </small>
              </div>
              <div className="su-row-actions">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  onClick={() => {
                    setLogTab('webhooks');
                    setTab('logs');
                  }}
                >
                  Deliveries
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  onClick={() => onEdit('webhooks')}
                >
                  Edit webhooks
                </button>
              </div>
            </div>
            <div className="la-log-table-wrap" style={{ marginTop: 16 }}>
              <table className="la-log-table">
                <thead>
                  <tr>
                    <th>Object type</th>
                    <th>Event type</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  {subs.map((s) => (
                    <tr key={s.id}>
                      <td>{objectLabel(s.objectType, objects)}</td>
                      <td style={S.keep}>
                        {WEBHOOK_EVENT_LABELS[s.eventType] ?? s.eventType}
                        <small style={S.sub} className="su-mono">
                          {s.eventType}
                          {s.propertyFilter.length ? ` · ${s.propertyFilter.join(', ')}` : ''}
                        </small>
                      </td>
                      <td>
                        <span className={cn('badge', s.active && 'badge--success')}>
                          {s.active ? 'Active' : 'Paused'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </article>
        )}
      </section>

      {/* Delete app (design: #modalDeleteApp): type the name to confirm. */}
      <LaModal open={deleteOpen} title="Delete app?" onClose={() => !busy && setDeleteOpen(false)}>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            if (deleteName.trim() === app.name.trim()) void remove();
          }}
        >
          <div className="la-modal-body">
            <p style={{ margin: '0 0 14px' }}>
              Are you sure you want to delete <strong>{app.name}</strong>? This action cannot be
              undone. Its access token will immediately stop working, its webhook is removed, and
              all active integrations using it will fail.
            </p>
            <label className="la-form-field">
              <span>
                Type the app name <code>{app.name}</code> to confirm:
              </span>
              <input
                autoComplete="off"
                placeholder={app.name}
                value={deleteName}
                onChange={(e) => setDeleteName(e.target.value)}
              />
            </label>
          </div>
          <footer className="la-modal-foot">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              disabled={busy}
              onClick={() => setDeleteOpen(false)}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="btn-crm btn-crm--danger"
              disabled={busy || deleteName.trim() !== app.name.trim()}
            >
              {busy ? 'Deleting…' : 'Delete app'}
            </button>
          </footer>
        </form>
      </LaModal>

      {confirmElement}
    </>
  );
}
