File size: 12,056 Bytes
e14ce19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import React, { useState, useEffect, useMemo } from 'react';
import { X, ChevronLeft, ChevronRight, Check } from 'lucide-react';
import { useAppConfig } from '../contexts/AppConfigContext';

const buildSteps = (config) => {
  const knowledgeLevels = (config?.login?.knowledge_levels || config?.login?.academic_stages || [])
    .filter((o) => o.value)
    .map((o) => ({ value: o.value, label: o.label }));

  const timezones = (config?.login?.timezones || [])
    .filter((o) => o.value)
    .map((o) => ({ value: o.value, label: o.label }));

  return [
    {
      title: 'Background',
      fields: [
        {
          key: 'knowledge_level',
          label: 'Learner stage',
          type: 'select',
          options: knowledgeLevels.length
            ? knowledgeLevels
            : [
                { value: 'hs_senior', label: 'High school senior' },
                { value: 'transfer', label: 'Community college / transfer' },
                { value: 'returning_adult', label: 'Returning adult / mid-career' },
              ],
        },
        {
          key: 'timezone',
          label: 'Time zone',
          type: 'select',
          options: timezones.length
            ? timezones
            : [{ value: 'UTC', label: 'UTC' }],
        },
      ],
    },
    {
      title: 'Path & modality',
      fields: [
        {
          key: 'cyber_role',
          label: 'Your college search path',
          type: 'select',
          options: [
            'High school / traditional',
            'Returning adult / online',
            'Both / exploring',
            'Transfer pathway',
            'Graduate / professional school later',
            'Other',
          ],
        },
        {
          key: 'organization_type',
          label: 'Preferred learning modality',
          type: 'select',
          options: [
            'On-campus residential',
            'Commuter campus',
            'Fully online',
            'Hybrid / evening',
            'Community college first',
            'Undecided / comparing',
          ],
        },
      ],
    },
    {
      title: 'Goals & majors',
      fields: [
        {
          key: 'primary_domains',
          label: 'Interests / majors / programs (comma-separated)',
          type: 'text',
          placeholder: 'e.g. Nursing, business, CS, education, undecided STEM',
        },
        {
          key: 'certifications',
          label: 'Credentials or prior learning to count (comma-separated)',
          type: 'text',
          placeholder: 'e.g. AA degree, military training, certificates, AP/IB, CLEP',
        },
        {
          key: 'tools_stack',
          label: 'Tools you use for the search (comma-separated)',
          type: 'text',
          placeholder: 'e.g. Common App, College Scorecard, Notion, Google Sheets',
        },
      ],
    },
    {
      title: 'Budget, access & story',
      fields: [
        {
          key: 'compliance_focus',
          label: 'Budget, location & accommodations',
          type: 'text',
          placeholder: 'e.g. Net price under $15k/yr; Colorado or online; ADHD accommodations; no meal plan needed',
        },
        {
          key: 'current_goals',
          label: 'Current college goals',
          type: 'textarea',
          placeholder: 'Build a shortlist, estimate aid, check Disability Services, finish applications by...',
        },
        {
          key: 'learning_preferences',
          label: 'How you like to work the search',
          type: 'text',
          placeholder: 'Weekend research blocks, counselor meetings, family decision nights...',
        },
        {
          key: 'advisor_notes',
          label: 'About you / college narrative',
          type: 'textarea',
          placeholder: 'Who you are, what you want schools to know, work/family context, and any essay themes. Advisors will not invent achievements.',
        },
      ],
    },
  ];
};

const initFormFromProfile = (steps, profile) => {
  const init = {};
  steps.forEach((s) => s.fields.forEach((f) => {
    const val = profile[f.key];
    if (Array.isArray(val)) init[f.key] = val.join(', ');
    else if (val) init[f.key] = val;
  }));
  return init;
};

const ProfileWalkthrough = ({ authToken, onClose, existingProfile }) => {
  const { config } = useAppConfig();
  const steps = useMemo(() => buildSteps(config), [config]);
  const [step, setStep] = useState(0);
  const [formData, setFormData] = useState({});
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    const fetchProfile = async () => {
      try {
        const resp = await fetch(`${process.env.REACT_APP_API_URL}/api/users/me/profile`, {
          headers: { 'Authorization': `Bearer ${authToken}` },
        });
        if (resp.ok && !cancelled) {
          const profile = await resp.json();
          setFormData(initFormFromProfile(steps, profile));
        }
      } catch (e) {
        if (!cancelled && existingProfile) {
          setFormData(initFormFromProfile(steps, existingProfile));
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    fetchProfile();
    return () => { cancelled = true; };
  }, [authToken, existingProfile, steps]);

  const handleChange = (key, value) => setFormData((prev) => ({ ...prev, [key]: value }));

  const saveProfile = async () => {
    const payload = { ...formData };
    ['primary_domains', 'certifications', 'tools_stack'].forEach((k) => {
      if (typeof payload[k] === 'string') {
        payload[k] = payload[k].split(',').map((s) => s.trim()).filter(Boolean);
      }
    });
    const hasData = Object.values(payload).some((v) =>
      (Array.isArray(v) ? v.length > 0 : Boolean(v))
    );
    if (!hasData) return;
    try {
      await fetch(`${process.env.REACT_APP_API_URL}/api/users/me/profile`, {
        method: 'PUT',
        headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
    } catch (e) {
      console.error('Failed to save profile:', e);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    await saveProfile();
    setSaving(false);
    onClose();
  };

  const handleClose = async () => {
    await saveProfile();
    onClose();
  };

  const currentStep = steps[step];
  const isLast = step === steps.length - 1;

  const renderSelectOptions = (options) => options.map((o) => {
    if (o && typeof o === 'object' && o.value != null) {
      return <option key={o.value} value={o.value}>{o.label}</option>;
    }
    return <option key={o} value={o}>{o}</option>;
  });

  return (
    <div onClick={handleClose} style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.5)', display: 'flex',
      alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--bg-primary)', borderRadius: 16,
        width: '90%', maxWidth: 480, padding: 24,
        boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
      }}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-secondary)', fontSize: 14 }}>
            Loading profile...
          </div>
        ) : <>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <h3 style={{ margin: 0, fontSize: 16, color: 'var(--text-primary)' }}>
            {currentStep.title} ({step + 1}/{steps.length})
          </h3>
          <button onClick={handleClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-secondary)' }}>
            <X size={18} />
          </button>
        </div>

        <div style={{ height: 4, background: 'var(--bg-secondary)', borderRadius: 2, marginBottom: 20 }}>
          <div style={{
            height: '100%', borderRadius: 2, background: 'var(--accent-primary)',
            width: `${((step + 1) / steps.length) * 100}%`, transition: 'width 0.3s',
          }} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {currentStep.fields.map((f) => (
            <div key={f.key}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
                {f.label}
              </label>
              {f.type === 'select' ? (
                <select
                  value={formData[f.key] || ''}
                  onChange={(e) => handleChange(f.key, e.target.value)}
                  style={{
                    width: '100%', padding: '8px 10px', borderRadius: 8,
                    border: '1px solid var(--border-primary)', background: 'var(--bg-secondary)',
                    color: 'var(--text-primary)', fontSize: 13,
                  }}
                >
                  <option value="">Select...</option>
                  {renderSelectOptions(f.options)}
                </select>
              ) : f.type === 'textarea' ? (
                <textarea
                  value={formData[f.key] || ''}
                  onChange={(e) => handleChange(f.key, e.target.value)}
                  placeholder={f.placeholder}
                  rows={3}
                  style={{
                    width: '100%', padding: '8px 10px', borderRadius: 8,
                    border: '1px solid var(--border-primary)', background: 'var(--bg-secondary)',
                    color: 'var(--text-primary)', fontSize: 13, resize: 'vertical',
                  }}
                />
              ) : (
                <input
                  type="text"
                  value={formData[f.key] || ''}
                  onChange={(e) => handleChange(f.key, e.target.value)}
                  placeholder={f.placeholder}
                  style={{
                    width: '100%', padding: '8px 10px', borderRadius: 8,
                    border: '1px solid var(--border-primary)', background: 'var(--bg-secondary)',
                    color: 'var(--text-primary)', fontSize: 13,
                  }}
                />
              )}
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24 }}>
          <button
            onClick={() => setStep((s) => s - 1)}
            disabled={step === 0}
            style={{
              display: 'flex', alignItems: 'center', gap: 4, padding: '8px 14px',
              borderRadius: 8, border: '1px solid var(--border-primary)',
              background: 'var(--bg-secondary)', color: 'var(--text-primary)',
              cursor: step === 0 ? 'default' : 'pointer', opacity: step === 0 ? 0.4 : 1,
              fontSize: 13,
            }}
          >
            <ChevronLeft size={14} /> Back
          </button>
          {isLast ? (
            <button
              onClick={handleSave}
              disabled={saving}
              style={{
                display: 'flex', alignItems: 'center', gap: 4, padding: '8px 16px',
                borderRadius: 8, border: 'none',
                background: 'var(--accent-primary)', color: '#fff',
                cursor: 'pointer', fontSize: 13, fontWeight: 600,
              }}
            >
              <Check size={14} /> {saving ? 'Saving...' : 'Save Profile'}
            </button>
          ) : (
            <button
              onClick={() => setStep((s) => s + 1)}
              style={{
                display: 'flex', alignItems: 'center', gap: 4, padding: '8px 14px',
                borderRadius: 8, border: 'none',
                background: 'var(--accent-primary)', color: '#fff',
                cursor: 'pointer', fontSize: 13, fontWeight: 600,
              }}
            >
              Next <ChevronRight size={14} />
            </button>
          )}
        </div>
        </>}
      </div>
    </div>
  );
};

export default ProfileWalkthrough;