import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { EditorStore } from '../store/editorStore';
import type { CBNode, CbRevision, CbRevisionWithData, PageData } from '../types';

// ─────────────────────────────────────────────────────────────────────────────
// Change-diff types
// ─────────────────────────────────────────────────────────────────────────────

type ChangeKind = 'added' | 'deleted' | 'content' | 'style' | 'settings' | 'visibility';

interface NodeChange {
  kind:     ChangeKind;
  nodeId:   string;
  nodeType: string;
  summary:  string;
  detail?:  string;
}

// ─────────────────────────────────────────────────────────────────────────────
// Diff utility
// ─────────────────────────────────────────────────────────────────────────────

const NODE_NAMES: Record<string, string> = {
  section: 'Section', container: 'Container', column: 'Column',
  heading: 'Heading', text: 'Text', image: 'Image', button: 'Button',
  spacer: 'Spacer', divider: 'Divider', icon: 'Icon', video: 'Video',
  maps: 'Map', html: 'HTML', shortcode: 'Shortcode', logo: 'Logo',
  form: 'Form', alert: 'Alert', counter: 'Counter', progress: 'Progress',
  testimonial: 'Testimonial', accordion: 'Accordion',
};
const cap = (s: string) => NODE_NAMES[s] ?? (s.charAt(0).toUpperCase() + s.slice(1));

function flattenNodes(sections: CBNode[]): Map<string, CBNode> {
  const map = new Map<string, CBNode>();
  function walk(nodes: CBNode[]) {
    for (const n of nodes) { map.set(n.id, n); if (n.children?.length) walk(n.children); }
  }
  walk(sections);
  return map;
}

function nodeText(node: CBNode): string {
  const c = node.content as Record<string, unknown> | undefined;
  if (!c) return '';
  const raw = String(c.text ?? c.html ?? c.shortcode ?? '').replace(/<[^>]*>/g, '').trim();
  return raw.slice(0, 55) + (raw.length > 55 ? '…' : '');
}

const STYLE_NAMES: Record<string, string> = {
  fontSize: 'font size', fontWeight: 'font weight', fontFamily: 'font family',
  color: 'color', backgroundColor: 'background', textAlign: 'text align',
  lineHeight: 'line height', letterSpacing: 'letter spacing',
  marginTop: 'margin-top', marginBottom: 'margin-bottom',
  marginLeft: 'margin-left', marginRight: 'margin-right',
  paddingTop: 'padding-top', paddingBottom: 'padding-bottom',
  paddingLeft: 'padding-left', paddingRight: 'padding-right',
  borderRadius: 'border radius', border: 'border', boxShadow: 'shadow',
  opacity: 'opacity', width: 'width', height: 'height', gap: 'gap',
  display: 'display', flexDirection: 'direction',
};

function changedKeys(
  a: Record<string, unknown> | undefined,
  b: Record<string, unknown> | undefined,
): string[] {
  const all = new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})]);
  return [...all].filter(k => JSON.stringify((a ?? {})[k]) !== JSON.stringify((b ?? {})[k]));
}

function diffPageData(prev: PageData, next: PageData): NodeChange[] {
  const oldNodes = flattenNodes(prev.sections ?? []);
  const newNodes = flattenNodes(next.sections ?? []);
  const changes: NodeChange[] = [];

  // Added
  for (const [id, node] of newNodes) {
    if (!oldNodes.has(id)) {
      const txt = nodeText(node);
      changes.push({ kind: 'added', nodeId: id, nodeType: node.type,
        summary: `${cap(node.type)} added`, detail: txt || undefined });
    }
  }

  // Deleted
  for (const [id, node] of oldNodes) {
    if (!newNodes.has(id)) {
      const txt = nodeText(node);
      changes.push({ kind: 'deleted', nodeId: id, nodeType: node.type,
        summary: `${cap(node.type)} removed`, detail: txt || undefined });
    }
  }

  // Modified
  for (const [id, newNode] of newNodes) {
    const oldNode = oldNodes.get(id);
    if (!oldNode) continue;

    // Content
    if (JSON.stringify(oldNode.content) !== JSON.stringify(newNode.content)) {
      const oldTxt = nodeText(oldNode);
      const newTxt = nodeText(newNode);
      const detail = oldTxt && newTxt && oldTxt !== newTxt
        ? `"${oldTxt}" → "${newTxt}"`
        : (newTxt || oldTxt || undefined);
      changes.push({ kind: 'content', nodeId: id, nodeType: newNode.type,
        summary: `${cap(newNode.type)} text changed`, detail });
    }

    // Styles (all breakpoints)
    const allKeys = [
      ...changedKeys(oldNode.styles         as Record<string, unknown>, newNode.styles         as Record<string, unknown>),
      ...changedKeys(oldNode.tabletStyles   as Record<string, unknown>, newNode.tabletStyles   as Record<string, unknown>),
      ...changedKeys(oldNode.mobileStyles   as Record<string, unknown>, newNode.mobileStyles   as Record<string, unknown>),
    ];
    const uniqKeys = [...new Set(allKeys)];
    if (uniqKeys.length) {
      const friendly = uniqKeys.slice(0, 4).map(k => STYLE_NAMES[k] ?? k).join(', ');
      const more     = uniqKeys.length > 4 ? ` +${uniqKeys.length - 4} more` : '';
      changes.push({ kind: 'style', nodeId: id, nodeType: newNode.type,
        summary: `${cap(newNode.type)} style changed`, detail: friendly + more });
    }

    // Settings
    if (JSON.stringify(oldNode.settings) !== JSON.stringify(newNode.settings))
      changes.push({ kind: 'settings', nodeId: id, nodeType: newNode.type, summary: `${cap(newNode.type)} settings changed` });

    // Visibility
    if (JSON.stringify(oldNode.hideOn) !== JSON.stringify(newNode.hideOn))
      changes.push({ kind: 'visibility', nodeId: id, nodeType: newNode.type, summary: `${cap(newNode.type)} visibility changed` });
  }

  return changes;
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────

function formatDate(iso: string): string {
  const d = new Date(iso.replace(' ', 'T') + 'Z');
  return d.toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' });
}

function formatTime(iso: string): string {
  const d = new Date(iso.replace(' ', 'T') + 'Z');
  return d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
}

function dayBucket(iso: string): string {
  const d     = new Date(iso.replace(' ', 'T') + 'Z');
  const today = new Date();
  const diff  = Math.floor((today.setHours(0,0,0,0) - d.setHours(0,0,0,0)) / 86_400_000);
  if (diff === 0) return 'Today';
  if (diff === 1) return 'Yesterday';
  if (diff <= 7)  return 'This Week';
  if (diff <= 30) return 'This Month';
  return 'Older';
}

function groupRevisions(revisions: CbRevision[]): { bucket: string; items: CbRevision[] }[] {
  const order = ['Today', 'Yesterday', 'This Week', 'This Month', 'Older'];
  const map   = new Map<string, CbRevision[]>();
  for (const r of revisions) {
    const b = dayBucket(r.created_at);
    if (!map.has(b)) map.set(b, []);
    map.get(b)!.push(r);
  }
  return order.filter(b => map.has(b)).map(b => ({ bucket: b, items: map.get(b)! }));
}

// Map label text to a quick visual hint
type HintKind = 'added' | 'deleted' | 'style' | 'moved' | 'settings';

function labelHint(label: string): HintKind | null {
  const l = label.toLowerCase();
  if (/\b(add|paste|duplicate|insert|load template|template)\b/.test(l)) return 'added';
  if (/\b(delete|remov)\b/.test(l))                                       return 'deleted';
  if (/\bstyle\b/.test(l))                                                return 'style';
  if (/\b(move|reorder)\b/.test(l))                                       return 'moved';
  if (/\b(column|layout|setting|column)\b/.test(l))                      return 'settings';
  return null;
}

// Per-kind display metadata
const KIND_META: Record<ChangeKind, { label: string; icon: string }> = {
  added:      { label: 'Added',              icon: '+' },
  deleted:    { label: 'Removed',            icon: '−' },
  content:    { label: 'Content Changed',    icon: '✎' },
  style:      { label: 'Style Changed',      icon: '~' },
  settings:   { label: 'Settings Changed',   icon: '⚙' },
  visibility: { label: 'Visibility Changed', icon: '◑' },
};

const HINT_LABELS: Record<HintKind, string> = {
  added: '+', deleted: '−', style: '~', moved: '↕', settings: '⚙',
};

// ─────────────────────────────────────────────────────────────────────────────
// Tiny icons
// ─────────────────────────────────────────────────────────────────────────────

const SpinnerIcon = () => (
  <svg className="jalpi-rev-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
    <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
  </svg>
);

// ─────────────────────────────────────────────────────────────────────────────
// Props
// ─────────────────────────────────────────────────────────────────────────────

interface Props {
  store: EditorStore;
  api: {
    listRevisions:   ()                                                                 => Promise<CbRevision[]>;
    getRevision:     (id: number)                                                       => Promise<CbRevisionWithData>;
    createRevision:  (data: PageData, label?: string, isSnapshot?: boolean)             => Promise<{ id?: number; skipped?: boolean }>;
    restoreRevision: (id: number)                                                       => Promise<{ restored: boolean; data: PageData }>;
    deleteRevision:  (id: number)                                                       => Promise<{ deleted: boolean }>;
  };
  onClose:  () => void;
  onToast:  (msg: string) => void;
}

// ─────────────────────────────────────────────────────────────────────────────
// Component
// ─────────────────────────────────────────────────────────────────────────────

const MAX_VISIBLE = 14;
const EMPTY_PAGE: PageData = { version: '1', sections: [] };

export function RevisionPanel({ store, api, onClose, onToast }: Props) {
  const [revisions,      setRevisions]      = useState<CbRevision[]>([]);
  const [loading,        setLoading]        = useState(true);
  const [selectedId,     setSelectedId]     = useState<number | null>(null);
  const [diffLoading,    setDiffLoading]    = useState(false);
  const [changes,        setChanges]        = useState<NodeChange[]>([]);
  const [revData,        setRevData]        = useState<PageData | null>(null);
  const [showAll,        setShowAll]        = useState(false);
  const [snapshotLabel,  setSnapshotLabel]  = useState('');
  const [showSnapshot,   setShowSnapshot]   = useState(false);
  const [savingSnap,     setSavingSnap]     = useState(false);
  const [restoring,      setRestoring]      = useState(false);
  const [deleting,       setDeleting]       = useState(false);

  const inputRef = useRef<HTMLInputElement>(null);

  // ── Load ──────────────────────────────────────────────────────────────────

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setRevisions(await api.listRevisions());
    } catch {
      onToast('Failed to load revisions');
    } finally {
      setLoading(false);
    }
  }, [api, onToast]);

  useEffect(() => { load(); }, []);

  useEffect(() => {
    const h = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);

  useEffect(() => {
    if (showSnapshot) setTimeout(() => inputRef.current?.focus(), 50);
  }, [showSnapshot]);

  // ── Select + diff ─────────────────────────────────────────────────────────

  const handleSelect = useCallback(async (id: number) => {
    if (id === selectedId) return;
    setSelectedId(id);
    setChanges([]);
    setRevData(null);
    setShowAll(false);
    setDiffLoading(true);

    try {
      // revisions array is newest-first; the "previous" (older) revision
      // is one index higher in the array.
      const idx    = revisions.findIndex(r => r.id === id);
      const prevId = revisions[idx + 1]?.id ?? null;

      const [rev, prevData] = await Promise.all([
        api.getRevision(id),
        prevId
          ? api.getRevision(prevId).then(r => r.data)
          : Promise.resolve<PageData | null>(null),
      ]);

      setRevData(rev.data);
      setChanges(diffPageData(prevData ?? EMPTY_PAGE, rev.data));
    } catch {
      onToast('Failed to load revision data');
    } finally {
      setDiffLoading(false);
    }
  }, [api, revisions, selectedId, onToast]);

  // ── Restore ───────────────────────────────────────────────────────────────

  const handleRestore = useCallback(async () => {
    if (!selectedId) return;
    setRestoring(true);
    try {
      const res = await api.restoreRevision(selectedId);
      store.loadPageData(res.data);
      onToast('Revision restored');
      onClose();
    } catch {
      onToast('Failed to restore revision');
    } finally {
      setRestoring(false);
    }
  }, [api, store, selectedId, onToast, onClose]);

  // ── Delete ────────────────────────────────────────────────────────────────

  const handleDelete = useCallback(async () => {
    if (!selectedId || !window.confirm('Delete this revision? This cannot be undone.')) return;
    setDeleting(true);
    try {
      await api.deleteRevision(selectedId);
      setRevisions(prev => prev.filter(r => r.id !== selectedId));
      setSelectedId(null);
      setChanges([]);
      setRevData(null);
      onToast('Revision deleted');
    } catch {
      onToast('Failed to delete revision');
    } finally {
      setDeleting(false);
    }
  }, [api, selectedId, onToast]);

  // ── Snapshot ──────────────────────────────────────────────────────────────

  const handleSnapshot = useCallback(async () => {
    setSavingSnap(true);
    try {
      await api.createRevision(store.state.pageData, snapshotLabel || 'Manual Snapshot', true);
      setSnapshotLabel('');
      setShowSnapshot(false);
      onToast('Snapshot saved');
      load();
    } catch {
      onToast('Failed to save snapshot');
    } finally {
      setSavingSnap(false);
    }
  }, [api, store, snapshotLabel, onToast, load]);

  // ── Derived ───────────────────────────────────────────────────────────────

  const groups  = groupRevisions(revisions);
  const selRev  = revisions.find(r => r.id === selectedId) ?? null;

  const counts = useMemo(() => {
    const c: Partial<Record<ChangeKind, number>> = {};
    for (const ch of changes) c[ch.kind] = (c[ch.kind] ?? 0) + 1;
    return c;
  }, [changes]);

  const visible = showAll ? changes : changes.slice(0, MAX_VISIBLE);
  const hidden  = changes.length - MAX_VISIBLE;

  const curSections = store.state.pageData.sections.length;

  // ─────────────────────────────────────────────────────────────────────────
  // Render
  // ─────────────────────────────────────────────────────────────────────────

  return (
    <div className="jalpi-rev-backdrop" onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="jalpi-rev-modal" role="dialog" aria-label="Revision Timeline">

        {/* ── Header ── */}
        <div className="jalpi-rev-header">
          <div className="jalpi-rev-header__left">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1a1a1a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
            </svg>
            <h2 className="jalpi-rev-header__title">Revision Timeline</h2>
            <span className="jalpi-rev-header__hint">{revisions.length} revision{revisions.length !== 1 ? 's' : ''}</span>
          </div>
          <div className="jalpi-rev-header__actions">
            <button className="jalpi-btn jalpi-btn--secondary jalpi-rev-snap-btn" onClick={() => setShowSnapshot(v => !v)}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                <path d="m12 17.27 4.15 2.51-.64-4.49 3.53-3.26-4.63-.55L12 7l-2.41 4.48-4.63.55 3.53 3.26-.64 4.49L12 17.27z"/>
              </svg>
              Snapshot
            </button>
            <button className="jalpi-rev-close" onClick={onClose} aria-label="Close">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
            </button>
          </div>
        </div>

        {/* ── Snapshot bar ── */}
        {showSnapshot && (
          <div className="jalpi-rev-snapshot-bar">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="#f59e0b" style={{ flexShrink: 0 }}>
              <path d="m12 17.27 4.15 2.51-.64-4.49 3.53-3.26-4.63-.55L12 7l-2.41 4.48-4.63.55 3.53 3.26-.64 4.49L12 17.27z"/>
            </svg>
            <input
              ref={inputRef}
              type="text"
              className="jalpi-rev-snapshot-input"
              placeholder="Name this snapshot…"
              value={snapshotLabel}
              onChange={e => setSnapshotLabel(e.target.value)}
              onKeyDown={e => {
                if (e.key === 'Enter')  handleSnapshot();
                if (e.key === 'Escape') setShowSnapshot(false);
              }}
            />
            <button className="jalpi-btn jalpi-btn--primary" onClick={handleSnapshot} disabled={savingSnap}>
              {savingSnap ? 'Saving…' : 'Save Snapshot'}
            </button>
            <button className="jalpi-btn jalpi-btn--ghost" onClick={() => setShowSnapshot(false)}>Cancel</button>
          </div>
        )}

        {/* ── Body ── */}
        <div className="jalpi-rev-body">

          {/* Left: timeline list */}
          <div className="jalpi-rev-list jalpi-tl-mode">
            {loading && (
              <div className="jalpi-rev-list__empty">
                <SpinnerIcon /> Loading…
              </div>
            )}

            {!loading && revisions.length === 0 && (
              <div className="jalpi-rev-list__empty">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#ccc" strokeWidth="1.5">
                  <circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>
                </svg>
                <p>No revisions yet</p>
                <p style={{ fontSize: '11px', color: '#bbb' }}>Saves every 60 s automatically</p>
              </div>
            )}

            {!loading && groups.map(group => (
              <div key={group.bucket} className="jalpi-rev-group">
                <div className="jalpi-rev-group__label">{group.bucket}</div>
                {group.items.map(rev => {
                  const hint  = labelHint(rev.label);
                  const isSel = rev.id === selectedId;
                  return (
                    <div
                      key={rev.id}
                      className={['jalpi-rev-item', isSel ? 'is-selected' : '', rev.is_snapshot ? 'is-snapshot' : ''].filter(Boolean).join(' ')}
                      onClick={() => handleSelect(rev.id)}
                    >
                      {/* Timeline dot */}
                      <div className={[
                        'jalpi-tl-dot',
                        rev.is_snapshot ? 'jalpi-tl-dot--snap' : '',
                        isSel           ? 'jalpi-tl-dot--sel'  : '',
                      ].filter(Boolean).join(' ')}>
                        {rev.is_snapshot && (
                          <svg width="7" height="7" viewBox="0 0 24 24" fill="currentColor">
                            <path d="m12 17.27 4.15 2.51-.64-4.49 3.53-3.26-4.63-.55L12 7l-2.41 4.48-4.63.55 3.53 3.26-.64 4.49L12 17.27z"/>
                          </svg>
                        )}
                      </div>

                      <div className="jalpi-rev-item__info">
                        <div className="jalpi-tl-label-row">
                          <span className="jalpi-rev-item__label">{rev.label || 'Auto-save'}</span>
                          {hint && (
                            <span className={`jalpi-rev-hint jalpi-rev-hint--${hint}`}
                                  title={hint}>
                              {HINT_LABELS[hint]}
                            </span>
                          )}
                        </div>
                        <span className="jalpi-rev-item__meta">
                          {formatTime(rev.created_at)} · {rev.user_name}
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>

          {/* Right: diff detail */}
          <div className="jalpi-rev-detail">

            {/* Empty state */}
            {!selRev && (
              <div className="jalpi-rev-detail__empty">
                <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ddd" strokeWidth="1.2">
                  <circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>
                </svg>
                <p>Select a revision to inspect changes</p>
              </div>
            )}

            {selRev && (
              <>
                {/* Revision meta card */}
                <div className="jalpi-rev-detail__card">
                  <div className="jalpi-rev-detail__badge">
                    {selRev.is_snapshot
                      ? <span className="jalpi-rev-badge jalpi-rev-badge--snap">⭐ Snapshot</span>
                      : <span className="jalpi-rev-badge jalpi-rev-badge--auto">Auto-save</span>
                    }
                  </div>
                  <h3 className="jalpi-rev-detail__name">{selRev.label || 'Auto-save'}</h3>
                  <div className="jalpi-rev-detail__row">
                    <span>When</span><span>{formatDate(selRev.created_at)}</span>
                  </div>
                  <div className="jalpi-rev-detail__row">
                    <span>Author</span><span>{selRev.user_name}</span>
                  </div>
                  {revData && (
                    <div className="jalpi-rev-detail__row">
                      <span>Structure</span>
                      <span>{revData.sections.length} section{revData.sections.length !== 1 ? 's' : ''} · {flattenNodes(revData.sections).size} node{flattenNodes(revData.sections).size !== 1 ? 's' : ''}</span>
                    </div>
                  )}
                </div>

                {/* Change diff */}
                <div className="jalpi-rev-diff-wrap">
                  <div className="jalpi-rev-diff-head">
                    <span className="jalpi-rev-diff-title">Changes from previous revision</span>
                    {diffLoading && <SpinnerIcon />}
                  </div>

                  {!diffLoading && changes.length === 0 && (
                    <div className="jalpi-rev-diff-none">
                      {revData ? 'No changes detected vs. previous revision' : 'Comparing…'}
                    </div>
                  )}

                  {!diffLoading && changes.length > 0 && (
                    <>
                      {/* Summary chips */}
                      <div className="jalpi-rev-diff-summary">
                        {(Object.keys(KIND_META) as ChangeKind[]).map(kind => {
                          const count = counts[kind] ?? 0;
                          if (!count) return null;
                          return (
                            <span key={kind} className={`jalpi-rev-diff-chip jalpi-rev-diff-chip--${kind}`}>
                              {KIND_META[kind].icon} {count} {kind}
                            </span>
                          );
                        })}
                      </div>

                      {/* Grouped change list */}
                      {(Object.keys(KIND_META) as ChangeKind[]).map(kind => {
                        const items = visible.filter(c => c.kind === kind);
                        if (!items.length) return null;
                        return (
                          <div key={kind} className="jalpi-rev-diff-section">
                            <div className={`jalpi-rev-diff-section__head jalpi-rev-diff-section__head--${kind}`}>
                              <span>{KIND_META[kind].icon}</span>
                              {KIND_META[kind].label}
                            </div>
                            {items.map((ch, i) => (
                              <div key={`${ch.nodeId}-${i}`} className="jalpi-rev-diff-item">
                                <span className={`jalpi-rev-diff-item__dot jalpi-rev-diff-item__dot--${ch.kind}`} />
                                <div className="jalpi-rev-diff-item__info">
                                  <span className="jalpi-rev-diff-item__node">{cap(ch.nodeType)}</span>
                                  {ch.detail && (
                                    <span className="jalpi-rev-diff-item__detail">{ch.detail}</span>
                                  )}
                                </div>
                              </div>
                            ))}
                          </div>
                        );
                      })}

                      {hidden > 0 && !showAll && (
                        <button className="jalpi-rev-diff-more" onClick={() => setShowAll(true)}>
                          Show {hidden} more change{hidden !== 1 ? 's' : ''}…
                        </button>
                      )}
                    </>
                  )}
                </div>

                {/* Actions */}
                <div className="jalpi-rev-detail__actions">
                  <button
                    className="jalpi-btn jalpi-btn--primary"
                    onClick={handleRestore}
                    disabled={restoring}
                    style={{ width: '100%', justifyContent: 'center' }}
                  >
                    {restoring ? <><SpinnerIcon /> Restoring…</> : 'Restore This Revision'}
                  </button>
                  {!selRev.is_snapshot && (
                    <button
                      className="jalpi-btn jalpi-btn--ghost jalpi-rev-delete-btn"
                      onClick={handleDelete}
                      disabled={deleting}
                      style={{ width: '100%', justifyContent: 'center' }}
                    >
                      {deleting ? 'Deleting…' : 'Delete Revision'}
                    </button>
                  )}
                </div>

                {/* Footer */}
                <div className="jalpi-rev-current-stats">
                  <span>Current page</span>
                  <span>{curSections} section{curSections !== 1 ? 's' : ''} · {flattenNodes(store.state.pageData.sections).size} nodes</span>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
