// Audit Log — read-only view onto the trigger-written audit trail.
// Migrated from the AdminPanel drawer.

const AuditSection = () => {
    const [auditEntries, setAuditEntries] = React.useState([]);
    const [auditLoading, setAuditLoading] = React.useState(true);

    React.useEffect(() => {
        api.getAudit({ limit: 100 })
            .then(r => setAuditEntries(r.entries || []))
            .catch(console.error)
            .finally(() => setAuditLoading(false));
    }, []);

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1rem' }}>
                Every change to a record is logged automatically — who, when, and what changed. Read-only and tamper-evident.
            </p>
            {auditLoading ? (
                <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
            ) : auditEntries.length === 0 ? (
                <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No audit entries yet.</p>
            ) : (
                <table className="admin-table" style={{ fontSize: '0.8125rem' }}>
                    <thead>
                        <tr>
                            <th>When</th><th>Who</th><th>Action</th><th>Record</th><th>Changed</th>
                        </tr>
                    </thead>
                    <tbody>
                        {auditEntries.map(e => (
                            <tr key={e.id}>
                                <td style={{ whiteSpace: 'nowrap' }}>{new Date(e.changed_at).toLocaleString()}</td>
                                <td>{e.actor_name || <span style={{ color: 'var(--text-3)' }}>system</span>}</td>
                                <td>
                                    <span className={`badge audit-${(e.action || '').toLowerCase()}`} style={{ fontSize: '0.65rem' }}>
                                        {e.action}
                                    </span>
                                </td>
                                <td>{e.table_name} #{e.row_id}</td>
                                <td style={{ color: 'var(--text-3)' }}>{(e.changed_fields || []).join(', ') || '—'}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            )}
        </div>
    );
};
