-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtmp.dart
More file actions
2427 lines (2245 loc) · 172 KB
/
tmp.dart
File metadata and controls
2427 lines (2245 loc) · 172 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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'firebase_options.dart';
import 'package:flutter_card_swiper/flutter_card_swiper.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
// Key is injected at build/run time via --dart-define=GEMINI_API_KEY=...
// It is NEVER stored in any source file. See README for run instructions.
const String _kGeminiApiKey = String.fromEnvironment(
'GEMINI_API_KEY',
defaultValue: '',
);
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
// Call runApp() IMMEDIATELY — never block on network calls before this!
runApp(const DevForceApp());
}
class DevForceApp extends StatefulWidget {
const DevForceApp({super.key});
@override
State<DevForceApp> createState() => _DevForceAppState();
}
class _DevForceAppState extends State<DevForceApp> {
Widget _homeScreen = const _LoadingScreen();
@override
void initState() {
super.initState();
_determineHomeScreen();
}
Future<void> _determineHomeScreen() async {
Widget destination;
try {
final User? currentUser = FirebaseAuth.instance.currentUser;
if (currentUser == null) {
destination = const EventLandingScreen();
} else {
final doc = await FirebaseFirestore.instance
.collection('users')
.doc(currentUser.uid)
.get();
destination = doc.exists ? const MainScreen() : const OnboardingScreen();
}
} catch (_) {
destination = const EventLandingScreen();
}
if (mounted) {
setState(() => _homeScreen = destination);
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'DevForce',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: _homeScreen,
debugShowCheckedModeBanner: false,
);
}
}
/// Simple loading indicator shown while checking auth state.
class _LoadingScreen extends StatelessWidget {
const _LoadingScreen();
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'DevForce',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
color: Colors.deepPurple,
),
),
SizedBox(height: 24),
CircularProgressIndicator(),
],
),
),
);
}
}
class OnboardingScreen extends StatefulWidget {
const OnboardingScreen({super.key});
@override
State<OnboardingScreen> createState() => _OnboardingScreenState();
}
class _OnboardingScreenState extends State<OnboardingScreen> {
final PageController _pageController = PageController();
int _currentPage = 0;
// Controllers to capture user input
final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _gdgIdController = TextEditingController();
final TextEditingController _roleController = TextEditingController();
final TextEditingController _githubController = TextEditingController();
final TextEditingController _linkedinController = TextEditingController();
final TextEditingController _experienceController = TextEditingController();
final TextEditingController _skillsController = TextEditingController();
final TextEditingController _interestsController = TextEditingController();
@override
void initState() {
super.initState();
// Pre-fill from Google profile — don't make them type what we already know
final user = FirebaseAuth.instance.currentUser;
if (user != null) {
_nameController.text = user.displayName ?? '';
_emailController.text = user.email ?? '';
}
}
Future<void> _saveProfileToFirebase() async {
try {
final currentUser = FirebaseAuth.instance.currentUser;
if (currentUser == null) return; // Safety check
final String? photoUrl = currentUser.photoURL;
// Use the user's UID as the document ID — this is the key change!
// Now the profile is tied to their Google account, not the device.
// .set() is idempotent: safe to call even if the doc already exists.
await FirebaseFirestore.instance
.collection('users')
.doc(currentUser.uid)
.set({
'uid': currentUser.uid,
'fullName': _nameController.text,
'email': _emailController.text,
'gdgId': _gdgIdController.text,
if (photoUrl != null) 'photoUrl': photoUrl,
'developerIdentity': {
'role': _roleController.text,
'githubId': _githubController.text,
'linkedInId': _linkedinController.text,
},
'matchmakerData': {
'experienceLevel': _experienceController.text,
'primarySkills': _skillsController.text.split(','),
'hackathonInterests': _interestsController.text.split(','),
},
'createdAt': DateTime.now(),
});
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const MainScreen()),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Error saving profile: $e')));
}
}
}
void _nextPage() {
if (_currentPage < 2) {
_pageController.animateToPage(
_currentPage + 1,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
} else {
_saveProfileToFirebase();
}
}
// RESTORED BUILD METHOD
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Step ${_currentPage + 1} of 3'),
centerTitle: true,
),
body: Column(
children: [
LinearProgressIndicator(value: (_currentPage + 1) / 3),
Expanded(
child: PageView(
controller: _pageController,
physics: const NeverScrollableScrollPhysics(),
onPageChanged: (int page) {
setState(() {
_currentPage = page;
});
},
children: [
_buildFormPage(
title: 'Who are you?',
fields: [
_buildTextField('Full Name', _nameController),
_buildTextField('Email ID', _emailController),
_buildTextField('GDG ID (Optional)', _gdgIdController),
],
),
_buildFormPage(
title: 'Your Developer Identity',
fields: [
_buildTextField('Designation / Role', _roleController),
_buildTextField('GitHub ID', _githubController),
_buildTextField('LinkedIn ID', _linkedinController),
],
),
_buildFormPage(
title: 'Matchmaker Data',
fields: [
_buildTextField(
'Experience Level (e.g., Beginner, Pro)',
_experienceController,
),
_buildTextField(
'Primary Skills (comma separated)',
_skillsController,
),
_buildTextField(
'Hackathon Interests (comma separated)',
_interestsController,
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.all(24.0),
child: SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: _nextPage,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: Text(
_currentPage < 2 ? "Next" : "Save Profile",
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
),
);
}
Widget _buildFormPage({required String title, required List<Widget> fields}) {
return Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
),
const SizedBox(height: 24),
...fields,
],
),
);
}
Widget _buildTextField(String label, TextEditingController controller) {
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: TextField(
controller: controller,
decoration: InputDecoration(
labelText: label,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
),
),
);
}
} // End of _OnboardingScreenState
// THE MAIN NAVIGATION HUB
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
int _selectedIndex = 0;
// The screens we will switch between
final List<Widget> _screens = [
const SwipeScreen(),
const ConnectionsScreen(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _screens[_selectedIndex], // Displays the currently selected screen
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: _onItemTapped,
selectedItemColor: Theme.of(context).colorScheme.primary,
unselectedItemColor: Colors.grey,
showUnselectedLabels: true,
items: const [
BottomNavigationBarItem(icon: Icon(Icons.explore), label: 'Discover'),
BottomNavigationBarItem(
icon: Icon(Icons.forum),
label: 'Connections',
),
],
),
);
}
}
class SwipeScreen extends StatefulWidget {
const SwipeScreen({super.key});
@override
State<SwipeScreen> createState() => _SwipeScreenState();
}
class _SwipeScreenState extends State<SwipeScreen> {
List<Map<String, dynamic>> _potentialTeammates = [];
Map<String, dynamic>? _myProfile;
// uid → Gemini analysis (score, headline, reason, suggestedRole, projectIdea)
final Map<String, Map<String, dynamic>> _geminiAnalyses = {};
bool _isLoading = true;
String? _errorMessage;
final CardSwiperController controller = CardSwiperController();
@override
void initState() {
super.initState();
_fetchUsersFromFirebase();
}
Future<void> _fetchUsersFromFirebase() async {
try {
final String? currentUid = FirebaseAuth.instance.currentUser?.uid;
if (currentUid == null) throw Exception("User not logged in");
// 1. Fetch the user's existing chats to know who to exclude from Discover
final chatSnapshot = await FirebaseFirestore.instance
.collection('chats')
.where('users', arrayContains: currentUid)
.get();
final Set<String> matchedUids = {};
for (final doc in chatSnapshot.docs) {
final users = doc.data()['users'] as List<dynamic>? ?? [];
for (final u in users) {
if (u.toString() != currentUid) {
matchedUids.add(u.toString());
}
}
}
// 2. Fetch all users
final snapshot = await FirebaseFirestore.instance
.collection('users')
.get();
Map<String, dynamic>? myProfile;
final List<Map<String, dynamic>> others = [];
for (final doc in snapshot.docs) {
final data = doc.data();
final uid = data['uid'] as String?;
if (uid == currentUid) {
myProfile = data; // Save own profile for match scoring
} else if (uid != null && !matchedUids.contains(uid)) {
others.add(data); // Only add if we haven't matched with them yet
}
}
if (mounted) {
setState(() {
_myProfile = myProfile;
_potentialTeammates = others;
_isLoading = false;
});
// Kick off Gemini analyses in the background — cards show immediately
_computeGeminiAnalyses();
}
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
_errorMessage = e.toString();
});
}
}
}
/// Runs Gemini analysis for each teammate sequentially (respects rate limits).
Future<void> _computeGeminiAnalyses() async {
if (_myProfile == null || _kGeminiApiKey.isEmpty)
return;
final model = GenerativeModel(
model: 'gemini-1.5-flash',
apiKey: _kGeminiApiKey,
generationConfig: GenerationConfig(responseMimeType: 'application/json'),
);
for (final teammate in _potentialTeammates) {
final uid = teammate['uid'] as String? ?? '';
if (uid.isEmpty || _geminiAnalyses.containsKey(uid)) continue;
try {
final result = await _getGeminiAnalysis(model, teammate);
if (mounted) setState(() => _geminiAnalyses[uid] = result);
} catch (_) {
/* silently fall back to local score */
}
}
}
Future<Map<String, dynamic>> _getGeminiAnalysis(
GenerativeModel model,
Map<String, dynamic> other,
) async {
final myMD = _myProfile!['matchmakerData'] as Map? ?? {};
final myID = _myProfile!['developerIdentity'] as Map? ?? {};
final thMD = other['matchmakerData'] as Map? ?? {};
final thID = other['developerIdentity'] as Map? ?? {};
final prompt =
'''
You are an expert GDG hackathon team-formation AI.
Analyze compatibility between two developers. Return ONLY valid JSON, no markdown.
Developer A:
Name: ${_myProfile!['fullName']}, Role: ${myID['role']}
Skills: ${(myMD['primarySkills'] as List?)?.join(', ')}
Experience: ${myMD['experienceLevel']}
Interests: ${(myMD['hackathonInterests'] as List?)?.join(', ')}
Developer B:
Name: ${other['fullName']}, Role: ${thID['role']}
Skills: ${(thMD['primarySkills'] as List?)?.join(', ')}
Experience: ${thMD['experienceLevel']}
Interests: ${(thMD['hackathonInterests'] as List?)?.join(', ')}
Return JSON:
{
"score": <40-99>,
"headline": "<≤8 word reason they match>",
"reason": "<2 sentences: technical + interest fit>",
"suggestedRole": "<role Developer B would play>",
"projectIdea": "<one creative Google-tech GDG hackathon project idea>"
}
''';
final resp = await model.generateContent([Content.text(prompt)]);
final text = (resp.text ?? '{}')
.replaceAll('```json', '')
.replaceAll('```', '')
.trim();
return jsonDecode(text) as Map<String, dynamic>;
}
/// Computes a real match score and reason between the current user and another.
/// Logic:
/// - +15 per shared hackathon interest (max 45 pts)
/// - +10 per complementary skill (unique to either side)
/// - +10 per shared skill (collaboration boost)
/// - Base score of 40
/// - Capped at 99%
Map<String, dynamic> _calculateMatch(Map<String, dynamic> other) {
if (_myProfile == null)
return {'score': 70, 'reason': 'Great potential match!'};
final myMatchData = _myProfile!['matchmakerData'] as Map? ?? {};
final theirMatchData = other['matchmakerData'] as Map? ?? {};
final mySkills =
(myMatchData['primarySkills'] as List?)
?.map((e) => e.toString().trim().toLowerCase())
.toSet() ??
{};
final theirSkills =
(theirMatchData['primarySkills'] as List?)
?.map((e) => e.toString().trim().toLowerCase())
.toSet() ??
{};
final myInterests =
(myMatchData['hackathonInterests'] as List?)
?.map((e) => e.toString().trim().toLowerCase())
.toSet() ??
{};
final theirInterests =
(theirMatchData['hackathonInterests'] as List?)
?.map((e) => e.toString().trim().toLowerCase())
.toSet() ??
{};
final sharedInterests = myInterests.intersection(theirInterests);
final sharedSkills = mySkills.intersection(theirSkills);
final complementarySkills = mySkills
.union(theirSkills)
.difference(sharedSkills);
int score = 40;
score += (sharedInterests.length * 15).clamp(0, 45);
score += (sharedSkills.length * 10).clamp(0, 20);
score += (complementarySkills.length * 5).clamp(0, 25);
score = score.clamp(40, 99);
// Build a human-readable reason
final List<String> reasons = [];
if (sharedInterests.isNotEmpty) {
final listed = sharedInterests
.take(2)
.map((s) => _capitalize(s))
.join(' & ');
reasons.add('Both interested in $listed');
}
if (complementarySkills.isNotEmpty) {
final listed = complementarySkills
.take(2)
.map((s) => _capitalize(s))
.join(' + ');
reasons.add('Complementary skills: $listed');
}
if (sharedSkills.isNotEmpty && reasons.isEmpty) {
final listed = sharedSkills
.take(2)
.map((s) => _capitalize(s))
.join(' & ');
reasons.add('Shared expertise in $listed');
}
final reason = reasons.isNotEmpty
? reasons.join('. ') + '.'
: 'Strong overall profile alignment.';
return {'score': score, 'reason': reason};
}
String _capitalize(String s) =>
s.isEmpty ? s : s[0].toUpperCase() + s.substring(1);
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Find Teammates'),
actions: [
IconButton(
icon: const Icon(Icons.person),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SettingsScreen()),
);
},
),
],
),
body: AnimatedMeshBackground(
child: SafeArea(
child: Column(
children: [
Expanded(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
// ── ERROR STATE ──────────────────────────────────────────
? Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.cloud_off,
size: 64,
color: Colors.redAccent,
),
const SizedBox(height: 16),
const Text(
'Could not load profiles',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
// Real error message — tells you exactly what failed
Text(
_errorMessage!,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: () {
setState(() {
_isLoading = true;
_errorMessage = null;
});
_fetchUsersFromFirebase();
},
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
),
],
),
),
)
: _potentialTeammates.isEmpty
? const Center(
child: Text(
"No more matches in your area! ðŸ˜",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
)
// ── SWIPER ───────────────────────────────────────────────
: CardSwiper(
controller: controller,
cardsCount: _potentialTeammates.length,
numberOfCardsDisplayed: _potentialTeammates.length == 1 ? 1 : 2,
onSwipe: _onSwipe,
onEnd: () {
setState(() {
_potentialTeammates.clear();
});
},
padding: const EdgeInsets.all(24.0),
cardBuilder:
(
context,
index,
horizontalOffsetPercentage,
verticalOffsetPercentage,
) {
return _buildTeammateCard(
_potentialTeammates[index],
);
},
),
),
// The Action Buttons (Now wired to the swiper controller!)
Padding(
padding: const EdgeInsets.only(bottom: 40.0, top: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
FloatingActionButton(
heroTag: 'no',
onPressed: () => controller.swipe(CardSwiperDirection.left),
backgroundColor: Colors.redAccent,
child: const Icon(
Icons.close,
color: Colors.white,
size: 30,
),
),
FloatingActionButton(
heroTag: 'yes',
onPressed: () =>
controller.swipe(CardSwiperDirection.right),
backgroundColor: Colors.greenAccent,
child: const Icon(
Icons.favorite,
color: Colors.white,
size: 30,
),
),
],
),
),
],
),
),
);
}
// Handle what happens when a card is actually swiped
// Handle what happens when a card is swiped
bool _onSwipe(
int previousIndex,
int? currentIndex,
CardSwiperDirection direction,
) {
if (direction == CardSwiperDirection.right) {
final matchedUser = _potentialTeammates[previousIndex];
final uid = matchedUser['uid'] as String? ?? '';
// CREATE CHAT DOCUMENT on right swipe (Match)
final currentUid = FirebaseAuth.instance.currentUser?.uid;
if (currentUid != null && uid.isNotEmpty) {
final chatId = [currentUid, uid]..sort();
FirebaseFirestore.instance.collection('chats').doc(chatId.join('_')).set({
'users': [currentUid, uid],
'lastUpdated': FieldValue.serverTimestamp(),
}, SetOptions(merge: true));
}
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => MatchDialog(
matchedUser: matchedUser,
myProfile: _myProfile,
geminiAnalysis: _geminiAnalyses[uid],
),
);
}
return true;
}
// Card UI — Gemini-powered when analysis is ready, local score as instant fallback
Widget _buildTeammateCard(Map<String, dynamic> user) {
final identity = user['developerIdentity'] ?? {};
final matchData = user['matchmakerData'] ?? {};
final primarySkills = matchData['primarySkills'] != null
? List<String>.from(matchData['primarySkills'])
: ['Unknown'];
final String? photoUrl = user['photoUrl'] as String?;
final String experienceLevel = matchData['experienceLevel'] ?? '';
final String uid = user['uid'] as String? ?? '';
final Map<String, dynamic>? gemini = _geminiAnalyses[uid];
// Build initials as fallback
final String name = user['fullName'] ?? 'U';
final List<String> parts = name
.trim()
.split(' ')
.where((s) => s.isNotEmpty)
.toList();
final String initials = parts.length > 1
? '${parts[0][0]}${parts[1][0]}'.toUpperCase()
: parts.isNotEmpty
? parts[0][0].toUpperCase()
: 'U';
// Use Gemini result when available, local algorithm as instant fallback
final localMatch = _calculateMatch(user);
final int matchScore =
(gemini?['score'] as num?)?.toInt() ?? localMatch['score'] as int;
final String matchReason =
(gemini?['reason'] as String?) ?? localMatch['reason'] as String;
final String? projectIdea = gemini?['projectIdea'] as String?;
final String? suggestedRole = gemini?['suggestedRole'] as String?;
final bool geminiReady = gemini != null;
final Color scoreColor = matchScore >= 80
? Colors.green
: matchScore >= 60
? Colors.amber.shade700
: Colors.redAccent;
final Color scoreBg = matchScore >= 80
? Colors.greenAccent.withValues(alpha: 0.15)
: matchScore >= 60
? Colors.amber.withValues(alpha: 0.15)
: Colors.red.withValues(alpha: 0.1);
return GlassCard(
child: Container(
width: double.infinity,
height: double.infinity,
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// ── Match score badge ─────────────────────────────────────────
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 7,
),
decoration: BoxDecoration(
color: scoreBg,
borderRadius: BorderRadius.circular(20),
),
child: Text(
'$matchScore% Match',
style: TextStyle(
color: scoreColor,
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
if (geminiReady) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 7,
),
decoration: BoxDecoration(
color: Colors.blue.shade50,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: Colors.blue.shade200),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.auto_awesome,
size: 12,
color: Colors.blue.shade700,
),
const SizedBox(width: 3),
Text(
'Gemini',
style: TextStyle(
fontSize: 11,
color: Colors.blue.shade700,
fontWeight: FontWeight.bold,
),
),
],
),
),
] else ...[
const SizedBox(width: 6),
SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.blue.shade300,
),
),
],
],
),
const SizedBox(height: 16),
// ── Profile picture ───────────────────────────────────────────
CircleAvatar(
radius: 48,
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
backgroundImage: photoUrl != null ? NetworkImage(photoUrl) : null,
child: photoUrl == null
? Text(
initials,
style: TextStyle(
color: Theme.of(context).colorScheme.primary,
fontSize: 28,
fontWeight: FontWeight.bold,
),
)
: null,
),
const SizedBox(height: 12),
// ── Name ──────────────────────────────────────────────────────
Text(
name,
style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 4),
// ── Role + Experience badge ───────────────────────────────────
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
identity['role'] ?? 'Developer',
style: const TextStyle(fontSize: 16, color: Colors.grey),
),
if (experienceLevel.isNotEmpty) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 2,
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Text(
experienceLevel,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
],
],
),
const SizedBox(height: 16),
// ── Skills chips ──────────────────────────────────────────────
Wrap(
spacing: 6.0,
runSpacing: 6.0,
alignment: WrapAlignment.center,
children: primarySkills.take(4).map((skill) {
return Chip(
label: Text(skill, style: const TextStyle(fontSize: 12)),
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
padding: EdgeInsets.zero,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}).toList(),
),
const SizedBox(height: 16),
// ── Match reason ──────────────────────────────────────────────
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.grey.shade50,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey.shade200),
),
child: Text(
matchReason,
textAlign: TextAlign.center,
style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 12,
color: Colors.grey.shade700,
),
),
),
// ── Gemini project idea ───────────────────────────────────────
if (projectIdea != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue.shade50, Colors.purple.shade50],
),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.blue.shade100),