// My Preferences — per-user settings (theme + two-factor). Every role sees
// this section; it saves to the signed-in user's own settings JSONB, never
// tenant config. New preferences get a card here, a key in SETTINGS_KEYS
// (server/routes/users.js), and nothing else — the merge endpoint handles them.
// (Extracted from the retired SettingsModal when the nav buttons consolidated
// into Settings, 2026-08-02.)
const PreferencesSection = ({ currentUser }) => {
    const [selected, setSelected] = React.useState(
        localStorage.getItem('crm_theme') || currentUser.settings?.theme || 'dark'
    );
    const [error, setError] = React.useState('');

    const pickTheme = async (themeId) => {
        const previous = selected;
        // Optimistic: apply immediately so the click feels instant, roll
        // back if the server rejects the save.
        setSelected(themeId);
        applyTheme(themeId);
        setError('');
        try {
            await api.updateMySettings({ theme: themeId });
        } catch (err) {
            setSelected(previous);
            applyTheme(previous);
            setError(`Couldn't save theme: ${err.message}`);
        }
    };

    return (
        <div>
            {error && <div className="api-error">{error}</div>}
            <div className="form-section">
                <h4><i className="fas fa-palette" style={{ marginRight: '0.375rem' }}></i>Theme</h4>
                <div className="theme-grid">
                    {THEMES.map(t => (
                        <button
                            key={t.id}
                            className={`theme-swatch ${selected === t.id ? 'selected' : ''}`}
                            onClick={() => pickTheme(t.id)}
                        >
                            <div className="theme-swatch-preview">
                                {t.preview.map((c, i) => <span key={i} style={{ background: c }}></span>)}
                            </div>
                            <div className="theme-swatch-name">
                                {selected === t.id && <i className="fas fa-check"></i>}
                                {t.name}
                            </div>
                        </button>
                    ))}
                </div>
                <p className="settings-hint">Saved to your account — follows you to any browser you sign in from.</p>
            </div>
            <TwoFactorSettings />
        </div>
    );
};
