File size: 53,321 Bytes
390cffd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
// Challenges page functionality
document.addEventListener('DOMContentLoaded', function() {
    initChallenges();
    initLeaderboard();
    initConnectModal();
    initProfileDrawer();
    initFilters();
});

function initChallenges() {
    loadChallenges();
}

function loadChallenges() {
    const challengesGrid = document.getElementById('challengesGrid');
    const challenges = window.oncoConnect.data.challenges;
    
    // Enhance challenges with detailed hackathon data
    const enhancedChallenges = challenges.map(challenge => ({
        ...challenge,
        ...getChallengeDetails(challenge.id)
    }));
    
    challengesGrid.innerHTML = enhancedChallenges.map(challenge => `
        <div class="challenge-card ${challenge.enrolled ? 'enrolled' : ''}" data-id="${challenge.id}">
            <div class="challenge-header">
                <h3 class="challenge-title">${challenge.title}</h3>
                <div class="challenge-meta">
                    <span class="difficulty-badge ${challenge.difficulty.toLowerCase()}">${challenge.difficulty}</span>
                    <span class="solved-count">${challenge.solved} solved</span>
                </div>
            </div>
            <div class="challenge-description">${challenge.description}</div>
            <div class="challenge-actions">
                <button class="btn btn-primary ${challenge.enrolled ? 'enrolled' : ''}" 
                        onclick="toggleEnrollment('${challenge.id}')">
                    ${challenge.enrolled ? 'Enrolled ✓' : 'Enroll'}
                </button>
                <button class="btn btn-secondary" onclick="openConnectModal('${challenge.id}')">
                    Connect
                </button>
            </div>
        </div>
    `).join('');
}

// Get detailed challenge information for hackathon-style display
function getChallengeDetails(challengeId) {
    const challengeDetails = {
        'rare-disease-drug': {
            theme: 'AI-Powered Drug Response Prediction for Rare Diseases',
            themeDescription: 'Develop machine learning models to predict patient response to candidate compounds for rare diseases using limited clinical data.',
            category: 'Drug Discovery',
            participants: 156,
            daysLeft: 45,
            prizeAmount: '₹75,000',
            
            // Detailed Problem Statement
            problemStatement: {
                title: 'The Rare Disease Drug Development Challenge',
                background: 'Rare diseases affect fewer than 200,000 people in the US, making traditional drug development economically unviable. With limited patient populations and sparse clinical trial data, pharmaceutical companies struggle to develop effective treatments. This challenge addresses the critical need for AI-powered solutions to predict drug response in rare disease patients.',
                objectives: [
                    'Predict patient response to candidate drug compounds with high accuracy',
                    'Develop models that work with limited clinical trial data',
                    'Create interpretable AI systems for clinical decision support',
                    'Build scalable solutions for multiple rare disease types',
                    'Integrate multi-omics data for comprehensive analysis'
                ],
                impact: 'Successful solutions will accelerate rare disease drug development, reduce costs, and bring life-saving treatments to patients faster. The winning models could be integrated into clinical trial design and personalized medicine approaches.',
                targetAudience: 'Data scientists, bioinformaticians, medical researchers, and AI engineers interested in healthcare applications.'
            },
            
            // Technical Requirements
            technicalRequirements: {
                dataScience: [
                    'Proficiency in Python/R for data analysis and modeling',
                    'Experience with machine learning frameworks (TensorFlow, PyTorch, scikit-learn)',
                    'Knowledge of bioinformatics tools and genomic data analysis',
                    'Understanding of clinical trial design and medical data standards',
                    'Experience with cloud computing platforms (AWS, GCP, Azure)'
                ],
                domainKnowledge: [
                    'Basic understanding of drug development process',
                    'Knowledge of rare disease mechanisms and biomarkers',
                    'Familiarity with multi-omics data integration',
                    'Understanding of clinical endpoints and response criteria',
                    'Knowledge of regulatory requirements for medical AI'
                ],
                deliverables: [
                    'Trained ML model with >80% accuracy on validation set',
                    'Complete source code with comprehensive documentation',
                    'Model performance metrics and validation results',
                    '5-minute presentation video explaining approach and results',
                    'Technical report detailing methodology and findings',
                    'Data preprocessing pipeline and feature engineering code',
                    'Model interpretability analysis and clinical insights',
                    'Deployment guide for production implementation'
                ]
            },
            
            // Detailed Dataset Information
            datasets: [
                {
                    title: 'Genomic Variants Dataset (VCF Format)',
                    size: '1.2GB',
                    format: 'VCF 4.2',
                    description: 'Comprehensive variant calling format files containing single nucleotide variants (SNVs), insertions, deletions, and structural variants for 1,000 patients across 15 rare disease types. Includes quality scores, population frequencies, and functional annotations.',
                    columns: [
                        'CHROM: Chromosome identifier',
                        'POS: Genomic position',
                        'ID: Variant identifier',
                        'REF: Reference allele',
                        'ALT: Alternative allele',
                        'QUAL: Quality score',
                        'FILTER: Filter status',
                        'INFO: Additional variant information',
                        'FORMAT: Genotype format',
                        'Sample columns: Individual patient genotypes'
                    ],
                    downloadUrl: '#',
                    sampleData: 'Available: 50 sample variants with annotations',
                    dataQuality: 'High-quality variants with >99% accuracy, filtered for common artifacts'
                },
                {
                    title: 'Transcriptomic Expression Data (RNA-Seq)',
                    size: '800MB',
                    format: 'CSV/TSV',
                    description: 'RNA sequencing expression profiles for 1,000 patients before and after drug treatment. Includes raw counts, normalized expression values, and differential expression analysis results.',
                    columns: [
                        'Gene_ID: Ensembl gene identifier',
                        'Gene_Symbol: Official gene symbol',
                        'Pre_Treatment_Counts: Raw read counts before treatment',
                        'Post_Treatment_Counts: Raw read counts after treatment',
                        'Log2FC: Log2 fold change in expression',
                        'P_Value: Statistical significance',
                        'FDR: False discovery rate correction',
                        'Pathway: KEGG pathway annotation'
                    ],
                    downloadUrl: '#',
                    sampleData: 'Available: Expression data for top 1000 differentially expressed genes',
                    dataQuality: 'High-depth sequencing (>50M reads per sample), quality filtered'
                },
                {
                    title: 'Clinical Outcomes Dataset',
                    size: '50MB',
                    format: 'CSV',
                    description: 'Phase II clinical trial data with patient demographics, treatment responses, adverse events, and follow-up outcomes. Includes both structured and unstructured clinical notes.',
                    columns: [
                        'Patient_ID: Unique patient identifier',
                        'Age: Patient age at enrollment',
                        'Gender: Biological sex',
                        'Disease_Type: Specific rare disease classification',
                        'Treatment_Response: Primary endpoint (CR/PR/SD/PD)',
                        'PFS: Progression-free survival (days)',
                        'OS: Overall survival (days)',
                        'Adverse_Events: Grade 1-5 toxicity events',
                        'Biomarkers: Key molecular markers',
                        'Prior_Treatments: Previous therapy history'
                    ],
                    downloadUrl: '#',
                    sampleData: 'Available: 100 anonymized patient records',
                    dataQuality: 'Curated by clinical experts, validated against source documents'
                },
                {
                    title: 'Commercial Feasibility Dataset',
                    size: '25MB',
                    format: 'JSON/CSV',
                    description: 'Market analysis data including patient population estimates, pricing benchmarks, development costs, and regulatory pathway information for rare disease drug development.',
                    columns: [
                        'Disease_Prevalence: Global patient population estimates',
                        'Market_Size: Addressable market value',
                        'Development_Cost: Estimated R&D costs',
                        'Pricing_Benchmarks: Similar drug pricing data',
                        'Regulatory_Pathway: FDA/EMA approval requirements',
                        'Competitive_Landscape: Existing treatments and competitors',
                        'ROI_Projections: Return on investment estimates'
                    ],
                    downloadUrl: '#',
                    sampleData: 'Available: Market analysis for 5 rare diseases',
                    dataQuality: 'Sourced from industry reports and regulatory databases'
                },
                {
                    title: 'Drug Compound Database',
                    size: '150MB',
                    format: 'SDF/CSV',
                    description: 'Chemical structure data for 500 candidate drug compounds including molecular properties, target information, and known mechanisms of action.',
                    columns: [
                        'Compound_ID: Unique compound identifier',
                        'SMILES: Chemical structure notation',
                        'Molecular_Weight: Compound molecular weight',
                        'LogP: Lipophilicity measure',
                        'Target_Proteins: Known protein targets',
                        'Mechanism: Mechanism of action',
                        'Toxicity_Profile: Known adverse effects',
                        'Drug_Likeness: ADMET properties'
                    ],
                    downloadUrl: '#',
                    sampleData: 'Available: 50 compounds with full chemical data',
                    dataQuality: 'Curated from ChEMBL and PubChem databases'
                }
            ],
            
            // Evaluation Criteria
            evaluationCriteria: {
                primary: [
                    'Model Accuracy: >80% on validation set (40% weight)',
                    'Clinical Relevance: Interpretable and actionable insights (25% weight)',
                    'Innovation: Novel approaches and techniques (20% weight)',
                    'Code Quality: Clean, documented, and reproducible (15% weight)'
                ],
                secondary: [
                    'Computational Efficiency: Model training and inference speed',
                    'Scalability: Ability to handle larger datasets',
                    'Robustness: Performance across different disease types',
                    'Documentation: Clarity and completeness of technical report'
                ],
                bonus: [
                    'Integration of multiple data types (genomics + transcriptomics + clinical)',
                    'Real-time prediction capabilities',
                    'User-friendly interface or API',
                    'Clinical validation with external dataset'
                ]
            },
            
            // Resources and Support
            resources: {
                documentation: [
                    'Comprehensive data dictionary and schema documentation',
                    'API documentation for data access and submission',
                    'Tutorial notebooks with example code and workflows',
                    'Best practices guide for rare disease data analysis',
                    'Clinical trial design and endpoint definitions'
                ],
                tools: [
                    'Jupyter notebooks with starter code templates',
                    'Docker containers with pre-installed dependencies',
                    'Cloud computing credits (AWS/GCP) for model training',
                    'Access to high-performance computing clusters',
                    'Version control and collaboration tools (GitHub)'
                ],
                mentorship: [
                    'Weekly office hours with domain experts',
                    '1-on-1 mentoring sessions with industry professionals',
                    'Technical workshops on genomics and drug discovery',
                    'Peer review and feedback sessions',
                    'Career guidance and networking opportunities'
                ]
            },
            
            // Timeline with detailed milestones
            timeline: [
                {
                    date: 'Dec 20, 2024',
                    title: 'Challenge Launch & Data Release',
                    description: 'Official challenge launch, complete dataset release, technical workshop, and Q&A session with domain experts',
                    deliverables: 'Data access, initial exploration, team formation'
                },
                {
                    date: 'Jan 5, 2025',
                    title: 'Mid-point Checkpoint 1',
                    description: 'Submit initial data exploration results, proposed methodology, and team progress report',
                    deliverables: 'Data analysis report, methodology outline, team updates'
                },
                {
                    date: 'Jan 20, 2025',
                    title: 'Mid-point Checkpoint 2',
                    description: 'Submit preliminary model results, feature engineering approach, and validation strategy',
                    deliverables: 'Baseline model, feature analysis, validation plan'
                },
                {
                    date: 'Feb 5, 2025',
                    title: 'Final Model Development',
                    description: 'Complete model training, hyperparameter optimization, and performance evaluation',
                    deliverables: 'Final model, performance metrics, optimization results'
                },
                {
                    date: 'Feb 15, 2025',
                    title: 'Final Submission Deadline',
                    description: 'Submit complete solution including code, documentation, presentation video, and technical report',
                    deliverables: 'Complete submission package, final presentation'
                },
                {
                    date: 'Feb 25, 2025',
                    title: 'Evaluation & Judging',
                    description: 'Expert panel evaluation, code review, and performance validation on test dataset',
                    deliverables: 'Judging results, feedback reports'
                },
                {
                    date: 'Mar 1, 2025',
                    title: 'Results Announcement & Awards',
                    description: 'Winners announced, prize distribution, networking event, and future collaboration opportunities',
                    deliverables: 'Awards ceremony, networking, follow-up opportunities'
                }
            ],
            
            // Detailed Prizes and Recognition
            prizes: [
                {
                    position: '1st Place',
                    amount: '₹10,00,000',
                    amountLabel: '₹ 10,00,000',
                    perks: [
                        'Research publication opportunity in top-tier journal',
                        '6-month mentorship with industry experts',
                        'Invitation to present at international conference',
                        'Potential collaboration with pharmaceutical company',
                        'Certificate of excellence and recognition'
                    ],
                    additional: 'Opportunity to work on real-world rare disease drug development project',
                    perkBadge: 'Pre-Placement Interview'
                },
                {
                    position: '2nd Place',
                    amount: '₹6,00,000',
                    amountLabel: '₹ 6,00,000',
                    perks: [
                        'Certificate of achievement',
                        '3-month mentorship program',
                        'Industry recognition and networking opportunities',
                        'Invitation to exclusive healthcare AI meetups',
                        'Potential internship opportunities'
                    ],
                    additional: 'Access to premium datasets and research tools',
                    perkBadge: 'Pre-Placement Interview'
                },
                {
                    position: '3rd Place',
                    amount: '₹3,00,000',
                    amountLabel: '₹ 3,00,000',
                    perks: [
                        'Certificate of participation',
                        '1-month mentorship with domain expert',
                        'Networking opportunities with industry professionals',
                        'Access to exclusive workshops and training',
                        'Recognition in community showcase'
                    ],
                    additional: 'Opportunity to contribute to open-source healthcare projects',
                    perkBadge: null
                },
                {
                    position: '4th Place',
                    amount: '₹1,00,000',
                    amountLabel: '₹ 1,00,000',
                    perks: [
                        'Certificate of participation',
                        'Recognition in community showcase',
                        'Access to exclusive workshops and training',
                        'Networking opportunities with industry professionals'
                    ],
                    additional: 'Recognition for outstanding contributions',
                    perkBadge: null
                }
            ],
            
            // Requirements
            requirements: [
                'Build ML model predicting drug response with >80% accuracy on validation set',
                'Submit complete source code with comprehensive documentation and comments',
                'Provide detailed model performance metrics and validation results with statistical significance',
                'Create 5-minute presentation video explaining approach, methodology, and key findings',
                'Include complete data preprocessing pipeline and feature engineering documentation',
                'Submit technical report (10-15 pages) detailing methodology, results, and clinical insights',
                'Provide model interpretability analysis and feature importance rankings',
                'Include deployment guide for production implementation and scalability considerations',
                'Submit code that is reproducible and runs on provided test environment',
                'Include unit tests and validation scripts for model reliability'
            ]
        },
        'prostate-gleason-grading': {
            theme: 'Automated Prostate Cancer Grading',
            themeDescription: 'Create deep learning systems for accurate Gleason scoring of prostate cancer specimens using histopathology images.',
            category: 'Computer Vision',
            participants: 203,
            daysLeft: 32,
            prizeAmount: '₹60,000',
            requirements: [
                'Develop CNN model for Gleason grade classification',
                'Achieve >90% accuracy on validation dataset',
                'Submit trained model weights and inference code',
                'Provide detailed technical documentation',
                'Create visualization of model decision process'
            ],
            datasets: [
                {
                    title: 'Training Images',
                    size: '3.5GB',
                    description: 'High-resolution histopathology images with expert Gleason grade annotations',
                    downloadUrl: '#'
                },
                {
                    title: 'Validation Set',
                    size: '1.2GB',
                    description: 'Test images for model evaluation and performance benchmarking',
                    downloadUrl: '#'
                },
                {
                    title: 'Sample Annotations',
                    size: '100MB',
                    description: 'Expert annotations and grading guidelines for reference',
                    downloadUrl: '#'
                }
            ],
            timeline: [
                {
                    date: 'Dec 15, 2024',
                    title: 'Challenge Start',
                    description: 'Dataset release, model development begins'
                },
                {
                    date: 'Jan 20, 2025',
                    title: 'Progress Review',
                    description: 'Submit intermediate results and model architecture'
                },
                {
                    date: 'Feb 10, 2025',
                    title: 'Final Submission',
                    description: 'Submit complete model and documentation'
                },
                {
                    date: 'Feb 25, 2025',
                    title: 'Results Announcement',
                    description: 'Winners announced, certificates distributed'
                }
            ],
            prizes: [
                {
                    position: '1st Place',
                    amount: '₹10,00,000',
                    amountLabel: '₹ 10,00,000',
                    perks: 'Research Collaboration + Certificate',
                    perkBadge: 'Pre-Placement Interview'
                },
                {
                    position: '2nd Place',
                    amount: '₹6,00,000',
                    amountLabel: '₹ 6,00,000',
                    perks: 'Industry Mentorship + Certificate',
                    perkBadge: 'Pre-Placement Interview'
                },
                {
                    position: '3rd Place',
                    amount: '₹3,00,000',
                    amountLabel: '₹ 3,00,000',
                    perks: 'Certificate + Recognition',
                    perkBadge: null
                },
                {
                    position: '4th Place',
                    amount: '₹1,00,000',
                    amountLabel: '₹ 1,00,000',
                    perks: 'Certificate + Recognition',
                    perkBadge: null
                }
            ]
        },
        'breast-cancer-detection': {
            theme: 'Multi-Modal Breast Cancer Detection',
            themeDescription: 'Develop AI systems combining mammography and pathology data for early breast cancer detection and risk assessment.',
            category: 'Medical Imaging',
            participants: 189,
            daysLeft: 28,
            prizeAmount: '₹85,000',
            requirements: [
                'Build multi-modal AI model for breast cancer detection',
                'Integrate mammography and histopathology data',
                'Achieve >85% sensitivity and >90% specificity',
                'Submit complete pipeline with preprocessing steps',
                'Provide clinical validation and interpretability analysis'
            ],
            datasets: [
                {
                    title: 'Mammography Images',
                    size: '4.2GB',
                    description: 'Digital mammograms with BI-RADS classifications and cancer annotations',
                    downloadUrl: '#'
                },
                {
                    title: 'Histopathology Slides',
                    size: '2.8GB',
                    description: 'H&E stained tissue slides with tumor grade and type annotations',
                    downloadUrl: '#'
                },
                {
                    title: 'Clinical Metadata',
                    size: '15MB',
                    description: 'Patient demographics, risk factors, and follow-up outcomes',
                    downloadUrl: '#'
                }
            ],
            timeline: [
                {
                    date: 'Dec 10, 2024',
                    title: 'Challenge Launch',
                    description: 'Multi-modal dataset release, technical workshop'
                },
                {
                    date: 'Jan 15, 2025',
                    title: 'Mid-term Review',
                    description: 'Submit model architecture and initial results'
                },
                {
                    date: 'Feb 5, 2025',
                    title: 'Final Submission',
                    description: 'Submit complete solution and clinical validation'
                },
                {
                    date: 'Feb 20, 2025',
                    title: 'Awards Ceremony',
                    description: 'Results announcement and networking event'
                }
            ],
            prizes: [
                {
                    position: '1st Place',
                    amount: '₹10,00,000',
                    amountLabel: '₹ 10,00,000',
                    perks: 'Clinical Collaboration + Publication',
                    perkBadge: 'Pre-Placement Interview'
                },
                {
                    position: '2nd Place',
                    amount: '₹6,00,000',
                    amountLabel: '₹ 6,00,000',
                    perks: 'Research Mentorship + Certificate',
                    perkBadge: 'Pre-Placement Interview'
                },
                {
                    position: '3rd Place',
                    amount: '₹3,00,000',
                    amountLabel: '₹ 3,00,000',
                    perks: 'Certificate + Industry Connect',
                    perkBadge: null
                },
                {
                    position: '4th Place',
                    amount: '₹1,00,000',
                    amountLabel: '₹ 1,00,000',
                    perks: 'Certificate + Recognition',
                    perkBadge: null
                }
            ]
        }
    };

    return challengeDetails[challengeId] || {
        theme: 'AI-Powered Medical Innovation',
        themeDescription: 'Develop cutting-edge AI solutions for medical diagnosis and treatment.',
        category: 'Machine Learning',
        participants: Math.floor(Math.random() * 200) + 50,
        daysLeft: Math.floor(Math.random() * 60) + 15,
        prizeAmount: '₹50,000',
        requirements: [
            'Submit a working prototype or solution',
            'Provide detailed documentation',
            'Include performance metrics and evaluation',
            'Submit source code and datasets used',
            'Create a presentation video (max 5 minutes)'
        ],
        datasets: [
            {
                title: 'Training Dataset',
                size: '2.5GB',
                description: 'High-quality medical data for model training and development',
                downloadUrl: '#'
            },
            {
                title: 'Validation Dataset',
                size: '500MB',
                description: 'Test dataset for model validation and performance evaluation',
                downloadUrl: '#'
            }
        ],
        timeline: [
            {
                date: 'Dec 20, 2024',
                title: 'Challenge Launch',
                description: 'Challenge officially begins, datasets available'
            },
            {
                date: 'Jan 15, 2025',
                title: 'Mid-point Check',
                description: 'Submit progress report and initial results'
            },
            {
                date: 'Feb 15, 2025',
                title: 'Final Submission',
                description: 'Submit final solution and documentation'
            },
            {
                date: 'Mar 1, 2025',
                title: 'Results Announcement',
                description: 'Winners announced and prizes distributed'
            }
        ],
        prizes: [
            {
                position: '1st Place',
                amount: '₹10,00,000',
                amountLabel: '₹ 10,00,000',
                perks: 'Mentorship + Certificate',
                perkBadge: 'Pre-Placement Interview'
            },
            {
                position: '2nd Place',
                amount: '₹6,00,000',
                amountLabel: '₹ 6,00,000',
                perks: 'Certificate + Recognition',
                perkBadge: 'Pre-Placement Interview'
            },
            {
                position: '3rd Place',
                amount: '₹3,00,000',
                amountLabel: '₹ 3,00,000',
                perks: 'Certificate + Recognition',
                perkBadge: null
            },
            {
                position: '4th Place',
                amount: '₹1,00,000',
                amountLabel: '₹ 1,00,000',
                perks: 'Certificate',
                perkBadge: null
            }
        ]
    };
}

function initLeaderboard() {
    loadLeaderboard();
}

function loadLeaderboard() {
    const leaderboardBody = document.getElementById('leaderboardBody');
    const profiles = window.oncoConnect.getDefaultProfiles();
    
    // Sort by solved count
    profiles.sort((a, b) => b.solved - a.solved);
    
    leaderboardBody.innerHTML = profiles.map((profile, index) => {
        const rank = index + 1;
        let rankClass = '';
        if (rank === 1) rankClass = 'first';
        else if (rank === 2) rankClass = 'second';
        else if (rank === 3) rankClass = 'third';
        
        return `
            <div class="leaderboard-entry" data-profile="${profile.id}" onclick="openProfile('${profile.id}')">
                <div class="rank ${rankClass}">${rank}</div>
                <div class="name">${profile.name}</div>
                <div class="expertise">
                    ${profile.expertise.slice(0, 2).map(skill => `<span class="tag">${skill}</span>`).join('')}
                </div>
                <div class="solved">${profile.solved}</div>
            </div>
        `;
    }).join('');
}

function initFilters() {
    const enrollmentFilter = document.getElementById('enrollmentFilter');
    
    enrollmentFilter.addEventListener('click', () => {
        const isActive = enrollmentFilter.classList.contains('active');
        
        if (isActive) {
            enrollmentFilter.classList.remove('active');
            enrollmentFilter.setAttribute('aria-pressed', 'false');
            enrollmentFilter.textContent = 'Show My Enrollments Only';
        } else {
            enrollmentFilter.classList.add('active');
            enrollmentFilter.setAttribute('aria-pressed', 'true');
            enrollmentFilter.textContent = 'Show All Challenges';
        }
        
        filterChallenges();
    });
}

function filterChallenges() {
    const showEnrolledOnly = document.getElementById('enrollmentFilter').classList.contains('active');
    const challengeCards = document.querySelectorAll('.challenge-card');
    
    challengeCards.forEach(card => {
        const isEnrolled = card.classList.contains('enrolled');
        
        if (showEnrolledOnly) {
            card.style.display = isEnrolled ? 'block' : 'none';
        } else {
            card.style.display = 'block';
        }
    });
}

function toggleEnrollment(challengeId) {
    requireAuth(() => {
        // Update participant count
        updateParticipantCount(challengeId);
        
        // Open challenge detail modal
        openChallengeDetailModal(challengeId);
    });
}

// Update participant count when someone enrolls
function updateParticipantCount(challengeId) {
    const challenges = window.oncoConnect.data.challenges;
    const challenge = challenges.find(c => c.id === challengeId);
    
    if (challenge) {
        // Increment participant count
        challenge.participants = (challenge.participants || 0) + 1;
        
        // Save to localStorage
        window.oncoConnect.saveData('challenges', challenges);
        
        // Update the display if we're on the challenges page
        if (document.getElementById('challengesGrid')) {
            loadChallenges();
        }
    }
}

// Open challenge detail modal
function openChallengeDetailModal(challengeId) {
    const challenge = window.oncoConnect.data.challenges.find(c => c.id === challengeId);
    if (!challenge) return;
    
    // Get detailed challenge data
    const detailedChallenge = {
        ...challenge,
        ...getChallengeDetails(challengeId)
    };
    
    // Populate modal with challenge data
    populateChallengeModal(detailedChallenge);
    
    // Show modal
    const modal = document.getElementById('challengeDetailModal');
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // Focus trap
    const focusableElements = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
    
    modal.addEventListener('keydown', handleModalKeydown);
    
    function handleModalKeydown(e) {
        if (e.key === 'Escape') {
            closeChallengeDetailModal();
        } else if (e.key === 'Tab') {
            if (e.shiftKey) {
                if (document.activeElement === firstElement) {
                    lastElement.focus();
                    e.preventDefault();
                }
        } else {
                if (document.activeElement === lastElement) {
                    firstElement.focus();
                    e.preventDefault();
                }
            }
        }
    }
    
    // Focus first element
    if (firstElement) {
        firstElement.focus();
    }
}

// Close challenge detail modal
function closeChallengeDetailModal() {
    const modal = document.getElementById('challengeDetailModal');
    modal.style.display = 'none';
    document.body.style.overflow = 'auto';
    
    // Remove event listeners
    modal.removeEventListener('keydown', handleModalKeydown);
}

// Populate challenge modal with data
function populateChallengeModal(challenge) {
    // Header info
    document.getElementById('modalChallengeTitle').textContent = challenge.title;
    document.getElementById('modalChallengeOrganizer').textContent = challenge.organizer || 'Co-Lab';
    document.getElementById('modalChallengeLocation').textContent = challenge.location || 'Online';
    document.getElementById('modalChallengeUpdated').textContent = `Updated On: ${challenge.updatedOn || 'Sep 8, 2025'}`;
    document.getElementById('modalHighlightBadge').textContent = challenge.highlightBadgeText || 'Grab Pre-Placement Interviews & Cash prizes worth ₹20,00,000';
    
    // Tags
    const tagsContainer = document.getElementById('modalChallengeTags');
    const tags = challenge.tags || ['Machine Learning', 'AI', 'Healthcare'];
    tagsContainer.innerHTML = tags.map(tag => `<span class="challenge-tag">${tag}</span>`).join('');
    
    // Quick facts
    document.getElementById('modalPrice').textContent = challenge.priceLabel || 'Free';
    document.getElementById('modalRegistered').textContent = challenge.registeredCount ? challenge.registeredCount.toLocaleString() : '1,90,520';
    document.getElementById('modalDaysLeft').textContent = `${challenge.daysLeft || 12} days left`;
    document.getElementById('modalDeadlineDate').textContent = challenge.deadlineDisplay || 'Aug 25, 2025';
    document.getElementById('modalImpressions').textContent = challenge.impressions ? challenge.impressions.toLocaleString() : '95,87,784';
    document.getElementById('modalParticipation').textContent = challenge.participationType || 'Individual';
    
    // Eligibility
    const eligibilityPills = challenge.eligibilityPills || ['Engineering Students', 'MBA Students', 'Undergraduate', 'Postgraduate'];
    document.getElementById('modalEligibilityPills').innerHTML = eligibilityPills.map(pill => 
        `<span class="eligibility-pill">${pill}</span>`
    ).join('');
    
    // Eligibility details
    const eligibilityDetails = document.getElementById('modalEligibilityDetails');
    if (challenge.eligibleBullets && challenge.eligibleBullets.length > 0) {
        eligibilityDetails.innerHTML = `
            <div class="eligibility-criteria">
                <h4>You're eligible if:</h4>
                <ul>
                    ${challenge.eligibleBullets.map(bullet => `<li>${bullet}</li>`).join('')}
                </ul>
                <h4>You're not eligible if:</h4>
                <ul>
                    ${challenge.notEligibleBullets ? challenge.notEligibleBullets.map(bullet => `<li>${bullet}</li>`).join('') : '<li>You don\'t meet the above criteria</li>'}
                </ul>
            </div>
        `;
    }
    
    // Timeline
    const timeline = challenge.stages || [
        {
            dateLabel: '25 Aug 25',
            title: 'Registration Opens',
            description: 'Challenge registration begins. Submit your team details and get ready to compete.',
            startIso: '2025-08-25T00:00:00Z',
            endIso: '2025-08-25T23:59:59Z',
            linkText: 'Click Here',
            linkUrl: '#'
        },
        {
            dateLabel: '30 Aug 25',
            title: 'Submission Deadline',
            description: 'Last date to submit your solution. Make sure to upload all required files.',
            startIso: '2025-08-30T00:00:00Z',
            endIso: '2025-08-30T23:59:59Z',
            linkText: 'Click Here',
            linkUrl: '#'
        }
    ];
    
    document.getElementById('modalTimeline').innerHTML = timeline.map(stage => `
        <div class="timeline-item">
            <div class="timeline-date">${stage.dateLabel}</div>
            <div class="timeline-content">
                <div class="timeline-title">${stage.title}</div>
                <div class="timeline-description">${stage.description}</div>
                <div class="timeline-dates">
                    Start: ${new Date(stage.startIso).toLocaleString()} | 
                    End: ${new Date(stage.endIso).toLocaleString()}
                </div>
                ${stage.linkText ? `<a href="${stage.linkUrl || '#'}" class="timeline-link">${stage.linkText}</a>` : ''}
            </div>
        </div>
    `).join('');
    
    // About content
    const aboutContent = challenge.aboutParagraphs || [
        'This challenge is designed to test your skills in machine learning and data science. Participants will work on real-world healthcare data to develop innovative solutions.',
        'The challenge focuses on developing AI models that can help in early detection and diagnosis of various medical conditions using advanced machine learning techniques.'
    ];
    
    document.getElementById('modalAboutContent').innerHTML = `
        ${aboutContent.map(paragraph => `<p>${paragraph}</p>`).join('')}
        <div class="eligibility-criteria">
            <h4>Eligibility Criteria</h4>
            <h4>You're eligible if:</h4>
            <ul>
                ${challenge.eligibleBullets ? challenge.eligibleBullets.map(bullet => `<li>${bullet}</li>`).join('') : '<li>You are a student or professional in relevant field</li>'}
            </ul>
            <h4>You're not eligible if:</h4>
            <ul>
                ${challenge.notEligibleBullets ? challenge.notEligibleBullets.map(bullet => `<li>${bullet}</li>`).join('') : '<li>You don\'t meet the above criteria</li>'}
            </ul>
        </div>
    `;
    
    // Important dates
    const importantDates = challenge.importantDates || [
        {
            label: 'Registration Deadline',
            iso: challenge.deadlineIso || '2025-08-25T23:59:59Z'
        }
    ];
    
    document.getElementById('modalImportantDates').innerHTML = importantDates.map(date => `
        <div class="date-item">
            <svg class="date-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 2V5M16 2V5M3.5 9.09H20.5M21 8.5V17.75C21 18.8546 20.1046 19.75 19 19.75H5C3.89543 19.75 3 18.8546 3 17.75V8.5C3 7.39543 3.89543 6.5 5 6.5H19C20.1046 6.5 21 7.39543 21 8.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <span class="date-label">${date.label}</span>
            <span class="date-value">${new Date(date.iso).toLocaleString()}</span>
        </div>
    `).join('');
    
    // Prizes
    const prizes = challenge.prizes || [
        {
            title: '1st Place',
            amountLabel: '₹ 10,00,000',
            perkBadge: 'Pre-Placement Interview',
            illustrationUrl: null
        },
        {
            title: '2nd Place',
            amountLabel: '₹ 6,00,000',
            perkBadge: 'Pre-Placement Interview',
            illustrationUrl: null
        },
        {
            title: '3rd Place',
            amountLabel: '₹ 3,00,000',
            perkBadge: null,
            illustrationUrl: null
        },
        {
            title: '4th Place',
            amountLabel: '₹ 1,00,000',
            perkBadge: null,
            illustrationUrl: null
        }
    ];
    
    document.getElementById('modalPrizes').innerHTML = prizes.map(prize => `
        <div class="prize-card">
            <div class="prize-info">
                <div class="prize-title">${prize.title}</div>
                <div class="prize-description">Cash prize for outstanding performance</div>
                <div class="prize-amount">${prize.amountLabel}</div>
                ${prize.perkBadge ? `<span class="prize-perk">${prize.perkBadge}</span>` : ''}
            </div>
            <div class="prize-illustration">
                🏆
            </div>
        </div>
    `).join('');
    
    // Update button states
    const registerButton = document.getElementById('modalRegisterButton');
    const enrollButton = document.getElementById('modalEnrollButton');
    
    if (challenge.enrolled) {
        registerButton.textContent = 'Enrolled ✓';
        registerButton.disabled = true;
        enrollButton.textContent = 'Enrolled ✓';
        enrollButton.disabled = true;
    } else {
        registerButton.textContent = 'Register';
        registerButton.disabled = false;
        enrollButton.textContent = 'Register';
        enrollButton.disabled = false;
    }
}

// Connect Modal functionality
function initConnectModal() {
    const modal = document.getElementById('connectModal');
    const closeBtn = document.getElementById('closeConnectModal');
    const cancelBtn = document.getElementById('cancelConnect');
    const form = document.getElementById('connectForm');
    
    closeBtn.addEventListener('click', () => {
        window.oncoConnect.closeModal(modal);
    });
    
    cancelBtn.addEventListener('click', () => {
        window.oncoConnect.closeModal(modal);
    });
    
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        sendConnectionRequest();
    });
}

function openConnectModal(challengeId) {
    requireAuth(() => {
    const challenge = window.oncoConnect.data.challenges.find(c => c.id === challengeId);
    if (!challenge) return;
    
    // Handle special case for rare disease challenge
    let challengeDescription = challenge.description;
    if (challenge.id === 'rare-disease-drug') {
        challengeDescription = `
            <div style="margin-bottom: 16px;">
                <strong>Challenge:</strong><br>
                Drug development for rare diseases is slowed by small patient populations and limited trial data. Students are tasked with building an ML model that predicts patient response to candidate compounds using pre-clinical and limited clinical datasets.
            </div>
            <div style="margin-bottom: 16px;">
                <strong>Datasets (Sample/Mock):</strong><br>
                • Genomic Data: Variant profiles (VCF files) for 1,000 patients<br>
                • Transcriptomic Data: RNA-Seq expression profiles pre- and post-treatment<br>
                • Clinical Outcomes: Limited Phase II trial data with response vs. non-response labels<br>
                • Commercial Layer: Cost of development, estimated patient pool size, and pricing benchmarks
            </div>
            <div>
                <strong>Expected Deliverable:</strong><br>
                A prototype ML pipeline that integrates omics and clinical data to predict drug response, with a secondary layer of cost-effectiveness analysis for commercialization feasibility.
            </div>
        `;
    }
    
    // Update challenge info
    const challengeInfo = document.getElementById('selectedChallengeInfo');
    challengeInfo.innerHTML = `
        <h3>${challenge.title}</h3>
        <div>${challengeDescription}</div>
    `;
    
    // Load collaborators
    loadCollaborators(challengeId);
    
    // Open modal
    window.oncoConnect.openModal('connectModal');
    });
}

function loadCollaborators(challengeId) {
    const collaboratorsGrid = document.getElementById('collaboratorsGrid');
    const recipientSelect = document.getElementById('recipientSelect');
    const profiles = window.oncoConnect.getDefaultProfiles();
    
    // Get random 5 profiles
    const collaborators = profiles.sort(() => 0.5 - Math.random()).slice(0, 5);
    
    collaboratorsGrid.innerHTML = collaborators.map(profile => `
        <div class="collaborator-card" data-profile="${profile.id}" onclick="selectCollaborator('${profile.id}')">
            <div class="collaborator-avatar"></div>
            <div class="collaborator-name">${profile.name}</div>
            <div class="collaborator-stats">${profile.solved} solved</div>
            <div class="collaborator-expertise">
                ${profile.expertise.slice(0, 2).map(skill => `<span class="tag">${skill}</span>`).join('')}
            </div>
        </div>
    `).join('');
    
    // Populate select options
    recipientSelect.innerHTML = '<option value="">Select a collaborator</option>' +
        collaborators.map(profile => `<option value="${profile.id}">${profile.name}</option>`).join('');
    
    // Set default message
    const challenge = window.oncoConnect.data.challenges.find(c => c.id === challengeId);
    document.getElementById('connectionMessage').value = 
        `Hi there! I'm enrolling in "${challenge.title}". Your expertise would be valuable for this challenge. Want to team up and collaborate?`;
}

function selectCollaborator(profileId) {
    // Remove previous selections
    document.querySelectorAll('.collaborator-card').forEach(card => {
        card.classList.remove('selected');
    });
    
    // Select clicked card
    const card = document.querySelector(`[data-profile="${profileId}"]`);
    if (card) {
        card.classList.add('selected');
        
        // Update select
        document.getElementById('recipientSelect').value = profileId;
        
        // Update message
        const profile = window.oncoConnect.getDefaultProfiles().find(p => p.id === profileId);
        const challenge = document.querySelector('#selectedChallengeInfo h3').textContent;
        const expertiseText = profile.expertise[0]; // First expertise
        
        document.getElementById('connectionMessage').value = 
            `Hi ${profile.name.split(' ')[1]}, I'm enrolling in ${challenge}. Your ${expertiseText} expertise would be great—want to team up?`;
    }
}

function sendConnectionRequest() {
    requireAuth(() => {
    const recipientId = document.getElementById('recipientSelect').value;
    const message = document.getElementById('connectionMessage').value;
    
    if (!recipientId) {
        window.oncoConnect.showToast('Please select a collaborator', 'error');
        return;
    }
    
    // Save connection request
    const connections = window.oncoConnect.getSavedData('connections') || [];
    connections.push({
        id: window.oncoConnect.generateId(),
        recipientId: recipientId,
        message: message,
        sentAt: new Date().toISOString(),
        status: 'pending'
    });
    
    window.oncoConnect.saveData('connections', connections);
    
    // Close modal
    window.oncoConnect.closeModal('connectModal');
    
    // Show success message
    const recipient = window.oncoConnect.getDefaultProfiles().find(p => p.id === recipientId);
    window.oncoConnect.showToast(`Connection request sent to ${recipient.name}!`);
    
    // Reset form
    document.getElementById('connectForm').reset();
    document.querySelectorAll('.collaborator-card').forEach(card => {
        card.classList.remove('selected');
        });
    });
}

// Profile Drawer functionality
function initProfileDrawer() {
    const drawer = document.getElementById('profileDrawer');
    const closeBtn = document.getElementById('closeDrawer');
    
    closeBtn.addEventListener('click', () => {
        window.oncoConnect.closeDrawer(drawer);
    });
    
    // Close on backdrop click
    drawer.addEventListener('click', (e) => {
        if (e.target === drawer) {
            window.oncoConnect.closeDrawer(drawer);
        }
    });
}

function openProfile(profileId) {
    const profile = window.oncoConnect.getDefaultProfiles().find(p => p.id === profileId);
    if (!profile) return;
    
    const drawerBody = document.getElementById('drawerBody');
    drawerBody.innerHTML = `
        <div class="profile-content">
            <div class="profile-avatar"></div>
            <div class="profile-name">${profile.name}</div>
            <div class="profile-role">${profile.role}</div>
            
            <div class="profile-stats">
                <div class="stat-item">
                    <div class="stat-value">${profile.solved}</div>
                    <div class="stat-label">Solved</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${profile.expertise.length}</div>
                    <div class="stat-label">Skills</div>
                </div>
            </div>
            
            <div class="profile-expertise">
                <h4>Expertise</h4>
                <div class="expertise-tags">
                    ${profile.expertise.map(skill => `<span class="tag">${skill}</span>`).join('')}
                </div>
            </div>
            
            <div class="profile-bio">
                <h4>About</h4>
                <p>${profile.bio}</p>
            </div>
            
            <button class="btn btn-primary" onclick="quickConnect('${profile.id}')">
                Connect
            </button>
        </div>
    `;
    
    window.oncoConnect.openDrawer('profileDrawer');
}

function quickConnect(profileId) {
    requireAuth(() => {
    // Simulate quick connection
    const profile = window.oncoConnect.getDefaultProfiles().find(p => p.id === profileId);
    
    // Save connection
    const connections = window.oncoConnect.getSavedData('connections') || [];
    connections.push({
        id: window.oncoConnect.generateId(),
        recipientId: profileId,
        message: `Hi ${profile.name}, I'd like to connect and collaborate!`,
        sentAt: new Date().toISOString(),
        status: 'pending'
    });
    
    window.oncoConnect.saveData('connections', connections);
    
    // Close drawer
    window.oncoConnect.closeDrawer('profileDrawer');
    
    // Show success
    window.oncoConnect.showToast(`Connection request sent to ${profile.name}!`);
    });
}