import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { MGMT_BASE } from '../auth/authConfig';

// ── Icon helpers ──────────────────────────────────────────────────────────────
const Icon = ({ d, size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
        stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
        <path d={d} />
    </svg>
);
const IcPlus    = () => <Icon d="M12 5v14M5 12h14" />;
const IcEdit    = () => <Icon d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />;
const IcTrash   = () => <Icon d="M3 6h18M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6M10 11v6M14 11v6M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />;
const IcRefresh = () => <Icon d="M23 4v6h-6M1 20v-6h6M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />;
const IcX       = () => <Icon d="M18 6L6 18M6 6l12 12" size={12} />;

// ── Module colour map ─────────────────────────────────────────────────────────
const MODULE_COLORS = {
    admin:   { bg: '#eff6ff', border: '#bfdbfe', text: '#1d4ed8' },
    client:  { bg: '#f0fdf4', border: '#bbf7d0', text: '#15803d' },
    service: { bg: '#fdf4ff', border: '#e9d5ff', text: '#7e22ce' },
};
const defaultModuleColor = { bg: '#f8fafc', border: '#e2e8f0', text: '#475569' };
const moduleColor = (mod) => MODULE_COLORS[mod] || defaultModuleColor;

// ── Styled help-key chip ──────────────────────────────────────────────────────
function HelpKey({ helpKey }) {
    const parts = helpKey.split('.');
    const mod   = parts[0] || '';
    const col   = moduleColor(mod);
    return (
        <span style={{ display: 'inline-flex', alignItems: 'center', fontFamily: 'monospace', fontSize: 12 }}>
            <span style={{
                padding: '2px 7px', borderRadius: '4px 0 0 4px',
                background: col.bg, border: `1px solid ${col.border}`,
                color: col.text, fontWeight: 700, fontSize: 11,
                borderRight: 'none',
            }}>{mod}</span>
            {parts.slice(1).map((seg, i) => {
                const isLast = i === parts.slice(1).length - 1;
                return (
                    <span key={i} style={{
                        padding: '2px 0',
                        borderTop: '1px solid #e2e8f0', borderBottom: '1px solid #e2e8f0',
                        borderRight: isLast ? '1px solid #e2e8f0' : 'none',
                        borderRadius: isLast ? '0 4px 4px 0' : 0,
                        background: '#fff', color: isLast ? '#0f172a' : '#64748b',
                        fontWeight: isLast ? 600 : 400,
                    }}>
                        <span style={{ color: '#cbd5e1', padding: '0 3px 0 4px' }}>.</span>{seg}
                    </span>
                );
            })}
        </span>
    );
}

// ── Status dot ────────────────────────────────────────────────────────────────
function StatusDot({ active }) {
    return (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{
                width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
                background: active ? '#22c55e' : '#d1d5db',
            }} />
            <span style={{ fontSize: 12, color: active ? '#15803d' : '#9ca3af', fontWeight: 500 }}>
                {active ? 'Active' : 'Inactive'}
            </span>
        </span>
    );
}

// ── Icon button ───────────────────────────────────────────────────────────────
function IconBtn({ onClick, disabled, title, danger, children }) {
    const [hover, setHover] = useState(false);
    return (
        <button onClick={onClick} disabled={disabled} title={title}
            onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
            style={{
                display: 'inline-flex', alignItems: 'center', gap: 4,
                padding: '5px 10px', borderRadius: 5, border: '1px solid',
                fontSize: 12, fontWeight: 500, cursor: disabled ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit', transition: 'all 0.12s', opacity: disabled ? 0.45 : 1,
                background: danger ? (hover ? '#fef2f2' : '#fff') : (hover ? '#eff6ff' : '#fff'),
                borderColor: danger ? (hover ? '#fca5a5' : '#e2e8f0') : (hover ? '#bfdbfe' : '#e2e8f0'),
                color: danger ? (hover ? '#dc2626' : '#94a3b8') : (hover ? '#2563eb' : '#64748b'),
            }}>
            {children}
        </button>
    );
}

export default function HelpPanel() {
    const { getAccessToken } = useAuth();

    const apiCall = useCallback(async (path, method = 'GET', body = null) => {
        const token = await getAccessToken();
        if (!token) return { ok: false, error: 'Not authenticated' };
        const opts = { method, headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } };
        if (body) opts.body = JSON.stringify(body);
        try {
            const res  = await fetch(`${MGMT_BASE}${path}`, opts);
            const text = await res.text();
            try { return JSON.parse(text); } catch { return { ok: false, error: text }; }
        } catch (e) { return { ok: false, error: e.message }; }
    }, [getAccessToken]);

    const [items,        setItems]        = useState([]);
    const [loading,      setLoading]      = useState(true);
    const [error,        setError]        = useState(null);
    const [toast,        setToast]        = useState(null);
    const [showInactive, setShowInactive] = useState(false);
    const [filterModule,  setFilterModule]  = useState('');
    const [filterSection, setFilterSection] = useState('');
    const [editKey,       setEditKey]       = useState(null);
    const [form,          setForm]          = useState({ helpKey: '', title: '', body: '', isActive: true });
    const [saving,        setSaving]        = useState(false);
    const [deleting,      setDeleting]      = useState(null);
    const [confirmDelete, setConfirmDelete] = useState(null);
    const bodyRef = useRef(null);

    const showToast = useCallback((msg, type = 'success') => {
        setToast({ msg, type });
        setTimeout(() => setToast(null), 3000);
    }, []);

    const loadItems = useCallback(async () => {
        setLoading(true); setError(null);
        try {
            const res = await apiCall('/api/admin/help/list', 'POST', { includeInactive: showInactive });
            if (res.ok) setItems(res.items || []);
            else setError(res.error || 'Failed to load help content');
        } catch { setError('Network error loading help content'); }
        finally { setLoading(false); }
    }, [apiCall, showInactive]);

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

    const { modules, sections } = useMemo(() => {
        const mods = new Set(), secs = new Set();
        items.forEach(({ helpKey }) => {
            const p = helpKey.split('.');
            if (p[0]) mods.add(p[0]);
            if (p[1]) secs.add(p[1]);
        });
        return { modules: [...mods].sort(), sections: [...secs].sort() };
    }, [items]);

    const handleModuleChange = (val) => { setFilterModule(val); setFilterSection(''); };

    const availableSections = useMemo(() => {
        if (!filterModule) return sections;
        const secs = new Set();
        items.forEach(({ helpKey }) => {
            const p = helpKey.split('.');
            if (p[0] === filterModule && p[1]) secs.add(p[1]);
        });
        return [...secs].sort();
    }, [items, filterModule, sections]);

    const visibleItems = useMemo(() => items.filter(({ helpKey }) => {
        const p = helpKey.split('.');
        if (filterModule  && p[0] !== filterModule)  return false;
        if (filterSection && p[1] !== filterSection) return false;
        return true;
    }), [items, filterModule, filterSection]);

    const hasFilter = filterModule || filterSection;

    const startEdit  = (item) => { setEditKey(item.helpKey); setForm({ helpKey: item.helpKey, title: item.title, body: item.body, isActive: item.isActive }); };
    const startNew   = ()     => { setEditKey('new'); setForm({ helpKey: '', title: '', body: '', isActive: true }); };
    const cancelEdit = ()     => { setEditKey(null);  setForm({ helpKey: '', title: '', body: '', isActive: true }); };

    const handleSave = async () => {
        if (!form.helpKey.trim()) return showToast('Help key is required', 'error');
        if (!form.title.trim())   return showToast('Title is required', 'error');
        if (!form.body.trim())    return showToast('Body content is required', 'error');
        setSaving(true);
        try {
            const res = await apiCall('/api/admin/help', 'POST', {
                helpKey: form.helpKey.trim().toLowerCase(), title: form.title.trim(),
                body: form.body.trim(), isActive: form.isActive,
            });
            if (res.ok) { showToast(`Saved "${form.helpKey}"`); cancelEdit(); loadItems(); }
            else showToast(res.error || 'Save failed', 'error');
        } catch { showToast('Network error saving', 'error'); }
        finally { setSaving(false); }
    };

    const handleDelete = async (helpKey) => {
        setDeleting(helpKey);
        try {
            const res = await apiCall(`/api/admin/help/${encodeURIComponent(helpKey)}`, 'DELETE');
            if (res.ok) { showToast(`Deleted "${helpKey}"`); setConfirmDelete(null); loadItems(); }
            else showToast(res.error || 'Delete failed', 'error');
        } catch { showToast('Network error deleting', 'error'); }
        finally { setDeleting(null); }
    };

    const KEY_SUGGESTIONS = [
        'client.wizard.objective', 'client.wizard.audience', 'client.wizard.budget',
        'client.wizard.channels', 'client.wizard.creative', 'client.wizard.review',
        'admin.campaigns.status', 'admin.campaigns.pacing', 'admin.clients.approval', 'admin.clients.status',
    ];
    const unusedSuggestions = KEY_SUGGESTIONS.filter(k => !items.find(i => i.helpKey === k));

    const activeCount   = items.filter(i => i.isActive).length;
    const inactiveCount = items.length - activeCount;

    const fmtDate = (d) => {
        if (!d) return '—';
        return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
    };

    // ── Shared styles ─────────────────────────────────────────────────────────
    const inputStyle = {
        width: '100%', padding: '7px 11px', border: '1px solid #e2e8f0',
        borderRadius: 6, fontSize: 13, fontFamily: 'inherit',
        outline: 'none', boxSizing: 'border-box', color: '#1e293b',
    };
    const labelStyle = {
        display: 'block', fontSize: 11, fontWeight: 700, color: '#64748b',
        textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 5,
    };

    return (
        <div style={{ maxWidth: 960 }}>

            {/* ── Toast ─────────────────────────────────────────────────── */}
            {toast && (
                <div style={{
                    position: 'fixed', bottom: 24, right: 24, zIndex: 1000,
                    background: toast.type === 'error' ? '#dc2626' : '#16a34a',
                    color: '#fff', padding: '10px 18px', borderRadius: 8,
                    fontSize: 13, fontWeight: 500, boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
                }}>
                    {toast.msg}
                </div>
            )}

            {/* ── Header ────────────────────────────────────────────────── */}
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 20 }}>
                <div>
                    <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: '#1e293b' }}>Help Content</h3>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 4 }}>
                        <span style={{ fontSize: 13, color: '#64748b' }}>
                            {hasFilter ? `${visibleItems.length} of ${items.length} entries` : `${items.length} entries`}
                        </span>
                        {!loading && items.length > 0 && (<>
                            <span style={{ color: '#e2e8f0' }}>·</span>
                            <span style={{ fontSize: 12, color: '#22c55e', fontWeight: 500 }}>{activeCount} active</span>
                            {inactiveCount > 0 && (<>
                                <span style={{ color: '#e2e8f0' }}>·</span>
                                <span style={{ fontSize: 12, color: '#94a3b8' }}>{inactiveCount} inactive</span>
                            </>)}
                        </>)}
                    </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <label style={{
                        display: 'flex', alignItems: 'center', gap: 6,
                        fontSize: 13, color: '#64748b', cursor: 'pointer', userSelect: 'none',
                    }}>
                        <input type="checkbox" checked={showInactive}
                            onChange={e => setShowInactive(e.target.checked)} />
                        Show inactive
                    </label>
                    <button onClick={loadItems} disabled={loading} title="Refresh"
                        style={{
                            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                            width: 32, height: 32, borderRadius: 6, border: '1px solid #e2e8f0',
                            background: '#fff', cursor: 'pointer', color: '#64748b', flexShrink: 0,
                        }}>
                        <IcRefresh />
                    </button>
                    <button onClick={startNew}
                        style={{
                            display: 'inline-flex', alignItems: 'center', gap: 6,
                            padding: '7px 14px', borderRadius: 6, border: 'none',
                            background: '#2563eb', color: '#fff',
                            fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
                        }}>
                        <IcPlus /> New Entry
                    </button>
                </div>
            </div>

            {/* ── Filter pills ──────────────────────────────────────────── */}
            {!loading && modules.length > 0 && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
                    {/* Module label + pills */}
                    <span style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Module</span>
                    {['', ...modules].map(m => {
                        const active = filterModule === m;
                        const col    = m ? moduleColor(m) : defaultModuleColor;
                        return (
                            <button key={m || '__all'} onClick={() => handleModuleChange(m)}
                                style={{
                                    padding: '4px 12px', borderRadius: 20, border: '1px solid',
                                    fontSize: 12, fontWeight: active ? 600 : 400,
                                    cursor: 'pointer', fontFamily: 'inherit', transition: 'all 0.12s',
                                    background: active ? col.bg : '#fff',
                                    borderColor: active ? col.border : '#e2e8f0',
                                    color: active ? col.text : '#64748b',
                                }}>
                                {m || 'All'}
                            </button>
                        );
                    })}

                    {/* Section pills */}
                    {filterModule && availableSections.length > 0 && (<>
                        <span style={{ width: 1, height: 16, background: '#e2e8f0', flexShrink: 0 }} />
                        <span style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Section</span>
                        {availableSections.map(s => {
                            const active = filterSection === s;
                            return (
                                <button key={s} onClick={() => setFilterSection(active ? '' : s)}
                                    style={{
                                        padding: '3px 10px', borderRadius: 20, border: '1px solid',
                                        fontSize: 11, fontWeight: active ? 600 : 400, fontFamily: 'monospace',
                                        cursor: 'pointer', transition: 'all 0.12s',
                                        background: active ? '#0f172a' : '#fff',
                                        borderColor: active ? '#0f172a' : '#e2e8f0',
                                        color: active ? '#fff' : '#64748b',
                                    }}>
                                    {s}
                                </button>
                            );
                        })}
                    </>)}

                    {hasFilter && (
                        <button onClick={() => { setFilterModule(''); setFilterSection(''); }}
                            style={{
                                display: 'inline-flex', alignItems: 'center', gap: 4,
                                padding: '3px 9px', borderRadius: 20,
                                border: '1px solid #e2e8f0', background: '#f8fafc',
                                fontSize: 11, color: '#64748b', cursor: 'pointer', fontFamily: 'inherit',
                            }}>
                            <IcX /> Clear
                        </button>
                    )}
                </div>
            )}

            {/* ── Edit / new form ───────────────────────────────────────── */}
            {editKey && (
                <div style={{
                    background: '#fff', border: '1px solid #bfdbfe', borderRadius: 10,
                    padding: 20, marginBottom: 20, boxShadow: '0 0 0 3px rgba(59,130,246,0.06)',
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
                        <div style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>
                            {editKey === 'new' ? '✦ New Help Entry' : `Editing: ${editKey}`}
                        </div>
                        <button onClick={cancelEdit}
                            style={{
                                padding: '5px 12px', borderRadius: 6, border: '1px solid #e2e8f0',
                                background: '#fff', fontSize: 12, color: '#64748b',
                                cursor: 'pointer', fontFamily: 'inherit',
                            }}>
                            Cancel
                        </button>
                    </div>

                    {/* Help key */}
                    <div style={{ marginBottom: 14 }}>
                        <label style={labelStyle}>
                            Help Key <span style={{ color: '#94a3b8', fontWeight: 400, textTransform: 'none', letterSpacing: 0 }}>— lowercase, dot-separated</span>
                        </label>
                        {editKey === 'new' ? (
                            <div>
                                <input style={inputStyle} placeholder="e.g. client.wizard.budget"
                                    value={form.helpKey}
                                    onChange={e => setForm(f => ({ ...f, helpKey: e.target.value.toLowerCase() }))} />
                                {unusedSuggestions.length > 0 && (
                                    <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 5, marginTop: 7 }}>
                                        <span style={{ fontSize: 11, color: '#94a3b8' }}>Suggested:</span>
                                        {unusedSuggestions.slice(0, 5).map(k => (
                                            <button key={k} onClick={() => setForm(f => ({ ...f, helpKey: k }))}
                                                style={{
                                                    padding: '2px 8px', borderRadius: 4, border: '1px solid #bfdbfe',
                                                    background: '#eff6ff', color: '#2563eb', fontSize: 11,
                                                    fontFamily: 'monospace', cursor: 'pointer',
                                                }}>
                                                {k}
                                            </button>
                                        ))}
                                    </div>
                                )}
                            </div>
                        ) : (
                            <div style={{
                                padding: '7px 11px', background: '#f8fafc', border: '1px solid #e2e8f0',
                                borderRadius: 6, fontFamily: 'monospace', fontSize: 13, color: '#475569',
                            }}>
                                {form.helpKey}
                            </div>
                        )}
                    </div>

                    {/* Title + Active toggle */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 14, alignItems: 'end', marginBottom: 14 }}>
                        <div>
                            <label style={labelStyle}>Title</label>
                            <input style={inputStyle} placeholder="Modal heading shown to users"
                                value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} />
                        </div>
                        <label style={{
                            display: 'flex', alignItems: 'center', gap: 6, paddingBottom: 8,
                            fontSize: 13, color: '#475569', cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap',
                        }}>
                            <input type="checkbox" checked={form.isActive}
                                onChange={e => setForm(f => ({ ...f, isActive: e.target.checked }))} />
                            Active
                        </label>
                    </div>

                    {/* Body */}
                    <div style={{ marginBottom: 16 }}>
                        <label style={labelStyle}>
                            Body
                            <span style={{ color: '#94a3b8', fontWeight: 400, textTransform: 'none', letterSpacing: 0, marginLeft: 6 }}>
                                — &lt;p&gt; &lt;ul&gt; &lt;li&gt; &lt;strong&gt; &lt;h4&gt; render in popup
                            </span>
                        </label>
                        <textarea ref={bodyRef} style={{
                            ...inputStyle, resize: 'vertical', minHeight: 160,
                            fontFamily: "'SF Mono','Menlo','Monaco','Consolas',monospace",
                            fontSize: 12, lineHeight: 1.6,
                        }}
                            placeholder="<p>Your help text here…</p>" value={form.body}
                            onChange={e => setForm(f => ({ ...f, body: e.target.value }))} rows={8} />
                    </div>

                    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                        <button onClick={handleSave} disabled={saving}
                            style={{
                                padding: '7px 20px', borderRadius: 6, border: 'none',
                                background: saving ? '#93c5fd' : '#2563eb', color: '#fff',
                                fontSize: 13, fontWeight: 500, cursor: saving ? 'not-allowed' : 'pointer',
                                fontFamily: 'inherit',
                            }}>
                            {saving ? 'Saving…' : 'Save Entry'}
                        </button>
                    </div>
                </div>
            )}

            {/* ── Loading / error / empty ───────────────────────────────── */}
            {loading && (
                <div style={{ padding: '40px 0', textAlign: 'center', color: '#94a3b8', fontSize: 13 }}>
                    Loading help content…
                </div>
            )}
            {error && !loading && (
                <div style={{
                    padding: '12px 16px', background: '#fef2f2', border: '1px solid #fecaca',
                    borderRadius: 8, color: '#dc2626', fontSize: 13, marginBottom: 16,
                }}>
                    {error}
                </div>
            )}
            {!loading && !error && items.length === 0 && (
                <div style={{ textAlign: 'center', padding: '60px 20px', color: '#94a3b8' }}>
                    <div style={{ fontSize: 32, marginBottom: 12 }}>📝</div>
                    <div style={{ fontWeight: 600, color: '#475569', marginBottom: 6 }}>No help entries yet</div>
                    <div style={{ fontSize: 13 }}>Click <strong>New Entry</strong> to create the first one.</div>
                </div>
            )}

            {/* ── Table ─────────────────────────────────────────────────── */}
            {!loading && items.length > 0 && (
                <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 10, overflow: 'hidden' }}>
                    {visibleItems.length === 0 ? (
                        <div style={{ padding: '32px 20px', textAlign: 'center', color: '#94a3b8', fontSize: 13 }}>
                            No entries match the current filter.
                        </div>
                    ) : (
                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                            <thead>
                                <tr style={{ background: '#f8fafc', borderBottom: '1px solid #e5e7eb' }}>
                                    {[
                                        { label: 'Help Key',  width: '38%' },
                                        { label: 'Title',     width: null  },
                                        { label: 'Status',    width: 90   },
                                        { label: 'Updated',   width: 80   },
                                        { label: '',          width: 106  },
                                    ].map(({ label, width }) => (
                                        <th key={label} style={{
                                            padding: '10px 16px', textAlign: 'left',
                                            fontSize: 11, fontWeight: 700, color: '#94a3b8',
                                            letterSpacing: '0.05em', textTransform: 'uppercase',
                                            width: width || undefined,
                                        }}>
                                            {label}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {visibleItems.map((item, idx) => (
                                    <tr key={item.helpKey} style={{
                                        borderBottom: idx < visibleItems.length - 1 ? '1px solid #f1f5f9' : 'none',
                                        opacity: !item.isActive ? 0.5 : 1,
                                        background: editKey === item.helpKey ? '#f8fbff' : 'transparent',
                                    }}>
                                        <td style={{ padding: '11px 16px' }}>
                                            <HelpKey helpKey={item.helpKey} />
                                        </td>
                                        <td style={{ padding: '11px 16px', fontSize: 13, color: '#374151' }}>
                                            {item.title}
                                        </td>
                                        <td style={{ padding: '11px 16px' }}>
                                            <StatusDot active={item.isActive} />
                                        </td>
                                        <td style={{ padding: '11px 16px', fontSize: 12, color: '#94a3b8', whiteSpace: 'nowrap' }}>
                                            {fmtDate(item.updatedAt)}
                                        </td>
                                        <td style={{ padding: '8px 12px' }}>
                                            {confirmDelete === item.helpKey ? (
                                                <div style={{ display: 'flex', gap: 4 }}>
                                                    <button onClick={() => handleDelete(item.helpKey)}
                                                        disabled={deleting === item.helpKey}
                                                        style={{
                                                            padding: '4px 10px', borderRadius: 5, border: '1px solid #fca5a5',
                                                            background: '#fef2f2', color: '#dc2626',
                                                            fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                                                        }}>
                                                        {deleting === item.helpKey ? '…' : 'Confirm'}
                                                    </button>
                                                    <button onClick={() => setConfirmDelete(null)}
                                                        style={{
                                                            padding: '4px 8px', borderRadius: 5, border: '1px solid #e2e8f0',
                                                            background: '#fff', color: '#94a3b8',
                                                            fontSize: 12, cursor: 'pointer',
                                                        }}>
                                                        ✕
                                                    </button>
                                                </div>
                                            ) : (
                                                <div style={{ display: 'flex', gap: 5 }}>
                                                    <IconBtn onClick={() => startEdit(item)} disabled={editKey === item.helpKey} title="Edit">
                                                        <IcEdit /> Edit
                                                    </IconBtn>
                                                    <IconBtn onClick={() => setConfirmDelete(item.helpKey)} danger title="Delete">
                                                        <IcTrash />
                                                    </IconBtn>
                                                </div>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </div>
            )}
        </div>
    );
}
