forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfilePage.tsx
More file actions
885 lines (797 loc) · 40.7 KB
/
Copy pathProfilePage.tsx
File metadata and controls
885 lines (797 loc) · 40.7 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Shield,
Key,
CreditCard,
Bell,
Award,
Zap,
Activity,
Camera,
Image as ImageIcon,
Check,
ChevronRight,
Sparkles,
AlertCircle,
Laptop,
LogOut,
Loader2,
} from 'lucide-react';
import { Github } from '@/components/icons/BrandIcons';
import { useAppStore, appStore } from '@/lib/store';
import { normalizeNotificationPreferences } from '@/lib/appConfig';
import { API_BASE, apiService } from '@/services/api';
import { Avatar } from '../components/ui/Avatar';
import type { ActiveSession, NotificationPreferences, UserProfile } from '../types';
// ─── Constants ──────────────────────────────────────────────────────────────
const NAME_MIN_LENGTH = 2;
const NAME_MAX_LENGTH = 60;
const MAX_AVATAR_BYTES = 2 * 1024 * 1024; // 2 MB
const MAX_BANNER_BYTES = 5 * 1024 * 1024; // 5 MB
const SAVE_LATENCY_MS = 600;
const SAVED_FLASH_MS = 2000;
const ERROR_FLASH_MS = 3000;
const ACCOUNT_LINKS = [
{ id: 'billing', icon: CreditCard, label: 'Billing & invoices', toast: 'Billing page not implemented' },
{ id: 'tokens', icon: Key, label: 'API access tokens', toast: 'Token management not implemented' },
] as const;
// ─── Helpers ────────────────────────────────────────────────────────────────
function getBrowserTimezone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Unknown';
} catch {
return 'Unknown';
}
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function readImageAsDataUrl(file: File, maxBytes: number): Promise<string> {
return new Promise((resolve, reject) => {
if (!file.type.startsWith('image/')) {
reject(new Error('Please choose an image file.'));
return;
}
if (file.size > maxBytes) {
reject(new Error(`Image must be smaller than ${formatBytes(maxBytes)}.`));
return;
}
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(new Error('Could not read the image.'));
reader.readAsDataURL(file);
});
}
function validateName(value: string): string | null {
const trimmed = value.trim();
if (!trimmed) return 'Name is required.';
if (trimmed.length < NAME_MIN_LENGTH) return `Name must be at least ${NAME_MIN_LENGTH} characters.`;
if (trimmed.length > NAME_MAX_LENGTH) return `Name must be ${NAME_MAX_LENGTH} characters or fewer.`;
return null;
}
/** Format an ISO-8601 date string into a compact relative/absolute label. */
function formatSessionDate(isoString: string): string {
try {
const date = new Date(isoString);
const now = Date.now();
const diffMs = now - date.getTime();
const diffMins = Math.floor(diffMs / 60_000);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMins < 1) return 'Active now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays === 1) return '1 day ago';
if (diffDays < 7) return `${diffDays} days ago`;
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
} catch {
return isoString;
}
}
// ─── Hooks ──────────────────────────────────────────────────────────────────
type SaveStatus = 'idle' | 'saving' | 'saved' | 'error';
function useSaveStatus() {
const [status, setStatus] = useState<SaveStatus>('idle');
const [error, setError] = useState<string | null>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
}, []);
const clearFlash = () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
const scheduleReset = (ms: number) => {
clearFlash();
timeoutRef.current = setTimeout(() => {
if (mountedRef.current) {
setStatus('idle');
setError(null);
}
}, ms);
};
return {
status,
error,
isMounted: () => mountedRef.current,
begin: () => {
clearFlash();
setError(null);
setStatus('saving');
},
succeed: () => {
if (!mountedRef.current) return;
setStatus('saved');
scheduleReset(SAVED_FLASH_MS);
},
fail: (message: string) => {
if (!mountedRef.current) return;
setError(message);
setStatus('error');
scheduleReset(ERROR_FLASH_MS);
},
};
}
interface ProfileFormValues {
name: string;
}
function useProfileForm(user: UserProfile) {
const initial = useMemo<ProfileFormValues>(() => ({ name: user.name }), [user.name]);
const [values, setValues] = useState<ProfileFormValues>(initial);
const [errors, setErrors] = useState<Partial<Record<keyof ProfileFormValues, string>>>({});
const [prevInitial, setPrevInitial] = useState(initial);
// Resync when the source user changes externally (e.g. via /signin or another tab).
if (initial !== prevInitial) {
setPrevInitial(initial);
setValues(initial);
setErrors({});
}
const setField = useCallback(<K extends keyof ProfileFormValues>(key: K, value: ProfileFormValues[K]) => {
setValues((v) => ({ ...v, [key]: value }));
setErrors((e) => (e[key] ? { ...e, [key]: undefined } : e));
}, []);
const isDirty = useMemo(
() => values.name.trim() !== initial.name.trim(),
[values, initial],
);
const validate = useCallback((): boolean => {
const next: Partial<Record<keyof ProfileFormValues, string>> = {};
const nameError = validateName(values.name);
if (nameError) next.name = nameError;
setErrors(next);
return Object.keys(next).length === 0;
}, [values]);
const reset = useCallback(() => {
setValues(initial);
setErrors({});
}, [initial]);
return { values, errors, isDirty, setField, validate, reset };
}
function useImageUpload(field: 'avatarUrl' | 'bannerUrl', maxBytes: number) {
const inputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false);
const trigger = useCallback(() => inputRef.current?.click(), []);
const onChange = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
// Reset the input so picking the same file twice still fires onChange.
e.target.value = '';
if (!file) return;
setIsUploading(true);
try {
const dataUrl = await readImageAsDataUrl(file, maxBytes);
appStore.updateUser({ [field]: dataUrl });
appStore.showToast(field === 'avatarUrl' ? 'Avatar updated' : 'Banner updated', 'success');
} catch (err) {
const message = err instanceof Error ? err.message : 'Upload failed.';
appStore.showToast(message, 'error');
} finally {
setIsUploading(false);
}
},
[field, maxBytes],
);
return { inputRef, trigger, onChange, isUploading };
}
// ─── Sessions hook ───────────────────────────────────────────────────────────
type SessionsState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'ready'; data: ActiveSession[] }
| { status: 'error'; message: string };
function useActiveSessions() {
const [state, setState] = useState<SessionsState>({ status: 'idle' });
const [revokingId, setRevokingId] = useState<string | null>(null);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => { mountedRef.current = false; };
}, []);
const load = useCallback(async () => {
setState({ status: 'loading' });
try {
const sessions = await apiService.getSessions();
if (!mountedRef.current) return;
setState({ status: 'ready', data: sessions });
} catch (err) {
if (!mountedRef.current) return;
const message = err instanceof Error ? err.message : 'Failed to load sessions.';
setState({ status: 'error', message });
}
}, []);
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- intentional fetch-on-mount
load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const revoke = useCallback(async (sessionId: string) => {
setRevokingId(sessionId);
try {
await apiService.revokeSession(sessionId);
if (!mountedRef.current) return;
appStore.showToast('Session revoked', 'success');
// Reload the list.
await load();
} catch (err) {
if (!mountedRef.current) return;
const message = err instanceof Error ? err.message : 'Could not revoke session.';
appStore.showToast(message, 'error');
} finally {
if (mountedRef.current) setRevokingId(null);
}
}, [load]);
return { state, revokingId, retry: load, revoke };
}
// ─── Presentational ─────────────────────────────────────────────────────────
interface StatCardProps {
icon: React.ReactNode;
label: string;
value: string;
sub: string;
accent?: boolean;
}
const StatCard: React.FC<StatCardProps> = ({ icon, label, value, sub, accent = false }) => (
<div
className={`relative rounded-xl border p-4 transition-colors ${
accent
? 'bg-electric-violet/[0.06] border-electric-violet/20 hover:border-electric-violet/30'
: 'bg-dark-indigo-glow border-white/[0.08] hover:border-white/[0.12]'
}`}
>
<div className="flex items-center justify-between mb-3">
<div className={`p-1.5 rounded-lg ${accent ? 'bg-electric-violet/[0.12] text-electric-violet' : 'bg-white/[0.04] text-slate-400'}`}>
{icon}
</div>
<span className="text-[11px] text-slate-500">{label}</span>
</div>
<div className="text-xl font-semibold text-white tracking-tight">{value}</div>
<div className="text-xs text-slate-500 mt-0.5">{sub}</div>
</div>
);
interface SectionProps {
title: string;
description?: string;
children: React.ReactNode;
}
const Section: React.FC<SectionProps> = ({ title, description, children }) => (
<section>
<div className="mb-3">
<h2 className="text-sm font-semibold text-slate-200 tracking-tight">{title}</h2>
{description && <p className="text-xs text-slate-500 mt-0.5">{description}</p>}
</div>
{children}
</section>
);
interface FieldProps {
label: string;
children: React.ReactNode;
hint?: string;
error?: string;
htmlFor?: string;
}
interface PreferenceToggleProps {
title: string;
description: string;
checked: boolean;
onChange: (checked: boolean) => void;
}
const PreferenceToggle: React.FC<PreferenceToggleProps> = ({
title,
description,
checked,
onChange,
}) => (
<label className="flex items-center gap-4 px-5 py-4 cursor-pointer hover:bg-white/[0.03] transition-colors">
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium text-slate-200">{title}</span>
<span className="block text-xs text-slate-500 mt-0.5 leading-relaxed">{description}</span>
</span>
<input
type="checkbox"
className="sr-only peer"
checked={checked}
onChange={(event) => onChange(event.target.checked)}
/>
<span className="relative h-6 w-11 shrink-0 rounded-full bg-slate-700 transition-colors peer-checked:bg-electric-violet/80 after:absolute after:left-1 after:top-1 after:h-4 after:w-4 after:rounded-full after:bg-white after:transition-transform peer-checked:after:translate-x-5" />
</label>
);
const Field: React.FC<FieldProps> = ({ label, children, hint, error, htmlFor }) => (
<div className="space-y-1.5">
<label htmlFor={htmlFor} className="block text-xs font-medium text-slate-400">
{label}
</label>
{children}
{error ? (
<p className="flex items-center gap-1.5 text-[11px] text-rose-400">
<AlertCircle size={11} />
{error}
</p>
) : (
hint && <p className="text-[11px] text-slate-500">{hint}</p>
)}
</div>
);
const baseInputClass =
'w-full bg-near-black border border-white/[0.08] rounded-lg px-3 py-2 text-sm text-slate-200 placeholder:text-slate-600 outline-none transition-colors';
const editableInputClass = `${baseInputClass} focus:border-electric-violet/60 focus:bg-white/[0.02]`;
const readonlyInputClass = `${baseInputClass} text-slate-500 cursor-not-allowed select-text`;
const errorInputClass = `${baseInputClass} border-rose-500/40 focus:border-rose-500/60`;
// ─── Sessions section ────────────────────────────────────────────────────────
interface ActiveSessionsSectionProps {
sessions: ActiveSession[];
revokingId: string | null;
onRevoke: (id: string) => void;
onRetry: () => void;
status: SessionsState['status'];
errorMessage?: string;
}
const ActiveSessionsSection: React.FC<ActiveSessionsSectionProps> = ({
sessions,
revokingId,
onRevoke,
onRetry,
status,
errorMessage,
}) => {
if (status === 'loading') {
return (
<div className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl flex items-center justify-center gap-2 py-8 text-slate-500 text-sm">
<Loader2 size={15} className="animate-spin" />
Loading sessions…
</div>
);
}
if (status === 'error') {
return (
<div className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl px-5 py-5">
<p className="flex items-center gap-1.5 text-xs text-rose-400 mb-3">
<AlertCircle size={13} />
{errorMessage ?? 'Could not load sessions.'}
</p>
<button
onClick={onRetry}
className="text-[11px] font-medium text-electric-violet hover:text-soft-purple transition-colors"
>
Try again
</button>
</div>
);
}
if (status === 'ready' && sessions.length === 0) {
return (
<div className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl flex items-center justify-center py-8 text-slate-500 text-sm">
No active sessions found.
</div>
);
}
return (
<div className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl overflow-hidden">
<div className="divide-y divide-white/[0.06]">
{sessions.map((s) => {
const isRevoking = revokingId === s.id;
return (
<div key={s.id} className="flex items-center gap-4 px-5 py-3 text-sm">
{/* Status dot */}
<span
className={`h-2 w-2 rounded-full shrink-0 ${
s.is_current
? 'bg-emerald-400 shadow-[0_0_6px_rgba(52,211,153,0.6)]'
: 'bg-slate-600'
}`}
/>
{/* Device icon */}
<Laptop
size={14}
className="text-slate-500 shrink-0 hidden sm:block"
/>
{/* Info */}
<div className="min-w-0 flex-1">
<div className="text-slate-200 truncate">
{s.device_label}
{s.is_current && (
<span className="ml-2 text-[10px] font-medium text-emerald-400 uppercase tracking-wide">
Current
</span>
)}
</div>
<div className="text-xs text-slate-500 mt-0.5 truncate">
{s.ip_address !== 'unknown' ? s.ip_address : 'IP unavailable'}
</div>
</div>
{/* Last active */}
<div className="text-xs text-slate-500 shrink-0">
{formatSessionDate(s.last_active_at)}
</div>
{/* Revoke — hidden for the current session */}
{!s.is_current && (
<button
onClick={() => onRevoke(s.id)}
disabled={isRevoking}
className="shrink-0 p-1.5 rounded-md text-slate-600 hover:text-rose-400 hover:bg-rose-500/[0.08] disabled:opacity-40 transition-colors"
title="Revoke session"
aria-label={`Revoke session for ${s.device_label}`}
>
{isRevoking ? (
<Loader2 size={13} className="animate-spin" />
) : (
<LogOut size={13} />
)}
</button>
)}
</div>
);
})}
</div>
</div>
);
};
// ─── Container ──────────────────────────────────────────────────────────────
export const ProfilePage: React.FC = () => {
const { user, history } = useAppStore();
if (!user) {
return <div className="p-10 text-slate-500">Please log in.</div>;
}
return <ProfilePageContent user={user} historyCount={history.length} />;
};
interface ProfilePageContentProps {
user: UserProfile;
historyCount: number;
}
const ProfilePageContent: React.FC<ProfilePageContentProps> = ({ user, historyCount }) => {
const { values, errors, isDirty, setField, validate } = useProfileForm(user);
const save = useSaveStatus();
const {
inputRef: avatarInputRef,
trigger: avatarTrigger,
onChange: avatarOnChange,
isUploading: avatarIsUploading,
} = useImageUpload('avatarUrl', MAX_AVATAR_BYTES);
const {
inputRef: bannerInputRef,
trigger: bannerTrigger,
onChange: bannerOnChange,
isUploading: bannerIsUploading,
} = useImageUpload('bannerUrl', MAX_BANNER_BYTES);
const { state: sessionsState, revokingId, retry: retrySessions, revoke: revokeSession } =
useActiveSessions();
const timezone = useMemo(() => getBrowserTimezone(), []);
const notificationPreferences = normalizeNotificationPreferences(
user.notificationPreferences
);
const handleNotificationPreferenceChange = useCallback(async (
key: keyof NotificationPreferences,
enabled: boolean
) => {
const nextPreferences = {
...notificationPreferences,
[key]: enabled
};
appStore.updateUser({
notificationPreferences: nextPreferences
});
try {
const updatedUser =
await apiService.updateNotificationPreferences(
nextPreferences
);
appStore.updateUser(updatedUser);
appStore.showToast('Notification preferences saved', 'success');
} catch {
appStore.showToast('Saved notification preferences locally. Sync will retry when the API is available.', 'info');
}
}, [notificationPreferences]);
const handleSave = useCallback(async () => {
if (!isDirty || save.status === 'saving') return;
if (!validate()) return;
save.begin();
try {
await new Promise<void>((resolve) => setTimeout(resolve, SAVE_LATENCY_MS));
if (!save.isMounted()) return;
appStore.updateUser({ name: values.name.trim() });
save.succeed();
} catch (err) {
const message = err instanceof Error ? err.message : 'Could not save changes.';
save.fail(message);
}
}, [isDirty, save, validate, values.name]);
const saveLabel = (() => {
switch (save.status) {
case 'saving': return 'Saving…';
case 'saved': return 'Saved';
case 'error': return 'Retry';
default: return 'Save changes';
}
})();
const saveButtonClass = (() => {
if (save.status === 'saved') return 'bg-emerald-500/[0.15] text-emerald-300 border border-emerald-500/30';
if (save.status === 'error') return 'bg-rose-500/[0.15] text-rose-300 border border-rose-500/30 hover:bg-rose-500/20';
return 'bg-electric-violet hover:bg-electric-violet/90 text-white shadow-[0_0_20px_-8px_rgba(163,163,163,0.6)]';
})();
const isSaveDisabled = save.status === 'saving' || (!isDirty && save.status !== 'error');
return (
<div className="h-full bg-near-black overflow-y-auto custom-scrollbar">
<div className="max-w-6xl mx-auto px-4 md:px-8 py-6 md:py-8 space-y-6">
{/* Top row: identity + stats */}
<div className="grid grid-cols-1 lg:grid-cols-6 gap-3">
{/* Identity card */}
<div className="lg:col-span-2 relative overflow-hidden rounded-xl border border-white/[0.08] bg-dark-indigo-glow">
{user.bannerUrl ? (
<>
<div
className="absolute inset-0 opacity-20"
style={{ backgroundImage: `url(${user.bannerUrl})`, backgroundSize: 'cover', backgroundPosition: 'center' }}
/>
<div className="absolute inset-0 bg-gradient-to-b from-near-black/40 via-near-black/60 to-near-black/85" />
</>
) : (
<>
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_rgba(163,163,163,0.18),_transparent_60%)]" />
<div className="absolute inset-0 dot-grid opacity-20" style={{ backgroundSize: '18px 18px' }} />
</>
)}
<div className="relative p-5 flex items-center gap-4">
<div className="relative group/avatar shrink-0">
<div className="p-0.5 bg-near-black rounded-2xl ring-1 ring-white/[0.08]">
<Avatar size="xl" type="user" className="rounded-xl" src={user.avatarUrl} seed={user.email} />
</div>
<input
type="file"
ref={avatarInputRef}
className="hidden"
accept="image/*"
onChange={avatarOnChange}
/>
<button
onClick={avatarTrigger}
disabled={avatarIsUploading}
className="absolute inset-0.5 flex items-center justify-center bg-near-black/70 backdrop-blur-sm text-white opacity-0 group-hover/avatar:opacity-100 focus-visible:opacity-100 disabled:opacity-60 rounded-xl transition-opacity"
aria-label={avatarIsUploading ? 'Uploading avatar' : 'Change avatar'}
>
<Camera size={18} />
</button>
</div>
<div className="min-w-0 flex-1">
<h1 className="text-base md:text-lg font-semibold text-white tracking-tight truncate">{user.name}</h1>
<p className="text-xs text-slate-400 truncate mt-0.5">{user.email}</p>
<p className="text-[11px] font-mono text-slate-500 truncate mt-0.5">ID {user.id}</p>
</div>
</div>
{/* Banner upload trigger — discreet corner action */}
<input
type="file"
ref={bannerInputRef}
className="hidden"
accept="image/*"
onChange={bannerOnChange}
/>
<button
onClick={bannerTrigger}
disabled={bannerIsUploading}
className="absolute top-2 right-2 p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] disabled:opacity-40 transition-colors"
title={bannerIsUploading ? 'Uploading…' : 'Customize background'}
aria-label="Customize background"
>
<ImageIcon size={13} />
</button>
</div>
{/* Stats */}
<div className="lg:col-span-4 grid grid-cols-2 sm:grid-cols-4 gap-3">
<StatCard icon={<Zap className="w-4 h-4" />} label="Plan" value="Pro" sub="Unlimited" accent />
<StatCard icon={<Activity className="w-4 h-4" />} label="Activity" value={String(historyCount)} sub="Calls this session" />
<StatCard icon={<Award className="w-4 h-4" />} label="Reputation" value="Lvl 42" sub="Sui builder" />
<StatCard icon={<Shield className="w-4 h-4" />} label="Security" value="Strong" sub="2FA enabled" />
</div>
</div>
{/* Section grid */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Main column */}
<div className="lg:col-span-2 space-y-6">
<Section title="Profile information" description="Update how you appear across txio.">
<form
className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl overflow-hidden"
onSubmit={(e) => { e.preventDefault(); void handleSave(); }}
>
<div className="p-5 md:p-6 grid grid-cols-1 md:grid-cols-2 gap-5">
<Field label="Display name" htmlFor="profile-name" error={errors.name}>
<input
id="profile-name"
className={errors.name ? errorInputClass : editableInputClass}
value={values.name}
onChange={(e) => setField('name', e.target.value)}
placeholder="Your name"
maxLength={NAME_MAX_LENGTH + 10}
autoComplete="name"
/>
</Field>
<Field label="Email" hint="Used for sign-in. Contact support to change." htmlFor="profile-email">
<input
id="profile-email"
className={readonlyInputClass}
value={user.email}
readOnly
aria-readonly
/>
</Field>
<Field label="GitHub" hint="Link your GitHub to publish recipes and sync gists.">
<div className={`${readonlyInputClass} flex items-center gap-2`}>
<Github size={14} className={user.githubAccount ? "text-slate-200 shrink-0" : "text-slate-400 shrink-0"} />
<span className={user.githubAccount ? "truncate text-slate-200" : "truncate text-slate-500"}>
{user.githubAccount ? `@${user.githubAccount.login}` : "Not connected"}
</span>
{!user.githubAccount && (
<button
type="button"
onClick={() => window.location.href = `${API_BASE}/auth/github/login`}
className="ml-auto text-[11px] text-electric-violet hover:text-soft-purple font-medium transition-colors"
>
Connect →
</button>
)}
</div>
</Field>
{user.githubAccount && (
<div className="mt-2">
<button
type="button"
onClick={async () => {
try {
await apiService.unlinkGithub();
appStore.updateUser({ githubAccount: undefined });
appStore.showToast("GitHub unlinked", "success");
} catch {
appStore.showToast("Failed to unlink GitHub", "error");
}
}}
className="text-[11px] text-rose-400 hover:text-rose-300 transition-colors"
>
Unlink GitHub
</button>
</div>
)}
<Field label="Timezone" hint="Detected from your browser." htmlFor="profile-tz">
<input
id="profile-tz"
className={readonlyInputClass}
value={timezone}
readOnly
aria-readonly
/>
</Field>
</div>
{/* Form footer */}
<div className="flex items-center justify-between gap-4 px-5 md:px-6 py-3 border-t border-white/[0.06] bg-white/[0.015]">
<p className="text-[11px] text-slate-500">
{save.error
? <span className="text-rose-400 inline-flex items-center gap-1.5"><AlertCircle size={11} /> {save.error}</span>
: isDirty
? 'You have unsaved changes.'
: 'All changes saved.'}
</p>
<button
type="submit"
disabled={isSaveDisabled}
className={`px-3.5 py-1.5 text-xs font-semibold rounded-lg transition-colors flex items-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed ${saveButtonClass}`}
>
{save.status === 'saved' && <Check size={13} />}
{save.status === 'error' && <AlertCircle size={13} />}
{saveLabel}
</button>
</div>
</form>
</Section>
<Section title="Notification preferences" description="Choose the updates txio sends by email and in-app alerts.">
<div className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl overflow-hidden divide-y divide-white/[0.06]">
<PreferenceToggle
title="Weekly email digest"
description="Receive a summary of request activity, usage, and workspace changes."
checked={notificationPreferences.emailDigests}
onChange={(checked) => handleNotificationPreferenceChange('emailDigests', checked)}
/>
<PreferenceToggle
title="Security emails"
description="Get email alerts for sign-ins, password changes, and account recovery events."
checked={notificationPreferences.emailSecurityAlerts}
onChange={(checked) => handleNotificationPreferenceChange('emailSecurityAlerts', checked)}
/>
<PreferenceToggle
title="In-app activity alerts"
description="Show workspace activity and request lifecycle alerts inside txio."
checked={notificationPreferences.inAppActivityAlerts}
onChange={(checked) => handleNotificationPreferenceChange('inAppActivityAlerts', checked)}
/>
<PreferenceToggle
title="Product updates"
description="Show announcements for new API, wallet, and builder workflow features."
checked={notificationPreferences.inAppProductUpdates}
onChange={(checked) => handleNotificationPreferenceChange('inAppProductUpdates', checked)}
/>
</div>
</Section>
<Section
title="Active sessions"
description="Devices currently signed in to your account. Revoke any session you don't recognise."
>
<ActiveSessionsSection
sessions={sessionsState.status === 'ready' ? sessionsState.data : []}
revokingId={revokingId}
onRevoke={revokeSession}
onRetry={retrySessions}
status={sessionsState.status}
errorMessage={
sessionsState.status === 'error'
? sessionsState.message
: undefined
}
/>
</Section>
</div>
{/* Side column */}
<div className="space-y-6">
<Section title="Account">
<div className="bg-dark-indigo-glow border border-white/[0.08] rounded-xl p-1.5 space-y-0.5">
{ACCOUNT_LINKS.map(({ id, icon: Icon, label, toast }) => (
<button
key={id}
onClick={() => appStore.showToast(toast, 'info')}
className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-slate-300 hover:bg-white/[0.04] hover:text-white group transition-colors"
>
<Icon size={15} className="text-slate-500 group-hover:text-electric-violet transition-colors" />
<span className="flex-1 text-left">{label}</span>
<ChevronRight size={14} className="text-slate-600 group-hover:text-slate-400 transition-colors" />
</button>
))}
</div>
</Section>
<div className="relative rounded-xl border border-electric-violet/20 bg-gradient-to-br from-electric-violet/[0.08] via-near-black to-near-black p-5 overflow-hidden">
<div className="absolute -top-12 -right-12 w-32 h-32 bg-electric-violet/20 blur-3xl rounded-full pointer-events-none" />
<div className="relative">
<div className="flex items-center gap-2 mb-2">
<div className="p-1 rounded-md bg-electric-violet/[0.15] text-electric-violet">
<Sparkles size={13} />
</div>
<span className="text-[11px] font-semibold text-electric-violet uppercase tracking-wider">Team</span>
</div>
<h3 className="text-white font-semibold tracking-tight mb-1.5">Upgrade to Team</h3>
<p className="text-xs text-slate-400 leading-relaxed mb-4">
Share collections, sync environments, and collaborate with your team in real time.
</p>
<button
onClick={() => appStore.showToast('Upgrade txio not implemented', 'info')}
className="w-full py-2 bg-white hover:bg-slate-100 text-near-black font-semibold text-xs rounded-lg transition-colors"
>
View plans
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
};