// Settings → Your Data — the "own your data" door.
// One button, no ceremony: download everything the workspace holds as a ZIP
// (per-table JSON + CSV + uploaded files + manifest), or a single JSON
// document for scripts. The no-lock-in promise, deliverable in one click.

const DataExportSection = () => {
    const [busy, setBusy] = React.useState(null);   // 'zip' | 'json' | null
    const [error, setError] = React.useState(null);
    const [lastDone, setLastDone] = React.useState(null);

    const run = async (format) => {
        setBusy(format); setError(null);
        try {
            await api.downloadTenantExport(format);
            setLastDone(format);
        } catch (err) {
            setError(err.message);
        } finally {
            setBusy(null);
        }
    };

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1rem' }}>
                Your data is yours. Download a complete copy of this workspace — every account,
                contact, conversation, task, quote, invoice, and uploaded file — any time,
                no questions asked. Passwords, sign-in secrets, and connection keys are never
                included; the bundle's <code>manifest.json</code> lists exactly what is.
            </p>
            <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap', marginBottom: '1rem' }}>
                <button className="btn btn-primary" disabled={!!busy} onClick={() => run('zip')}>
                    {busy === 'zip'
                        ? <><i className="fas fa-spinner fa-spin"></i> Preparing…</>
                        : <><i className="fas fa-file-archive"></i> Download everything (.zip)</>}
                </button>
                <button className="btn btn-secondary" disabled={!!busy} onClick={() => run('json')}>
                    {busy === 'json'
                        ? <><i className="fas fa-spinner fa-spin"></i> Preparing…</>
                        : <><i className="fas fa-code"></i> JSON only</>}
                </button>
            </div>
            {error && <p style={{ color: 'var(--danger)', fontSize: '0.875rem' }}>{error}</p>}
            {lastDone && !error && (
                <p style={{ color: 'var(--text-3)', fontSize: '0.8125rem' }}>
                    <i className="fas fa-check" style={{ color: 'var(--success)' }}></i>{' '}
                    Export downloaded. Keep it somewhere safe — it contains your customers' information.
                </p>
            )}
            <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', marginTop: '0.5rem' }}>
                Need everything about one <em>person</em> instead (a data request from a customer)?
                Managers can download a per-contact bundle from that contact's record.
            </p>
        </div>
    );
};
