// My Preferences — per-user look-and-feel settings (theme). 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 2026-08-02; two-factor moved to
// its own Security card the same day — sign-in protection ≠ appearance.)
const PreferencesSection = ({ currentUser, landingOptions = [] }) => {
    const [selected, setSelected] = React.useState(
        localStorage.getItem('crm_theme') || currentUser.settings?.theme || 'dark'
    );
    const [error, setError] = React.useState('');
    // Default landing page — which nav view the app opens on. Dashboard is
    // the product default; landingOptions is the nav list this user actually
    // has (pack-filtered upstream), so a pack view can be picked where enabled.
    const [landing, setLanding] = React.useState(currentUser.settings?.default_view || 'dashboard');
    const pickLanding = async (viewId) => {
        const previous = landing;
        setLanding(viewId); // optimistic, same pattern as theme
        setError('');
        try {
            await api.updateMySettings({ default_view: viewId });
            // Keep the in-memory user in step so a re-render of MainApp's
            // landing logic (no reload) sees the new pick too.
            currentUser.settings = { ...(currentUser.settings || {}), default_view: viewId };
        } catch (err) {
            setLanding(previous);
            setError(`Couldn't save landing page: ${err.message}`);
        }
    };

    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>
            {landingOptions.length > 0 && (
                <div className="form-section">
                    <h4><i className="fas fa-home" style={{ marginRight: '0.375rem' }}></i>Default Landing Page</h4>
                    <div className="tag-filter-chips" style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
                        {landingOptions.map(v => (
                            <span key={v.id}
                                className="tag-pill tag-filter-chip"
                                style={landing === v.id ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : {}}
                                onClick={() => pickLanding(v.id)}>
                                <i className={`fas ${v.icon}`} style={{ marginRight: '0.3rem' }}></i>
                                {v.label}
                                {landing === v.id && <i className="fas fa-check" style={{ marginLeft: '0.3rem' }}></i>}
                            </span>
                        ))}
                    </div>
                    <p className="settings-hint">The view the app opens on when you sign in or load it fresh. Dashboard is the default.</p>
                </div>
            )}
        </div>
    );
};
