// Per-user settings — currently just the theme picker. New preferences get
// a section here, a key in SETTINGS_KEYS (server/routes/users.js), and
// nothing else: the JSONB column and the merge endpoint already handle them.
const SettingsModal = ({ currentUser, onClose }) => {
    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 (
        <Modal isOpen={true} onClose={onClose} title="Settings">
            <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>
        </Modal>
    );
};
