File size: 79,098 Bytes
d0b8e8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gleam/string
import gleam/int
import gleam/list
import gleam/result
import gleam/json

pub type TutorResponse {
  TutorResponse(
    response_text: String,
    technical_explanation: String,
    suggested_sources: List(String),
    confidence_score: Float,
    neural_pathway_id: String,
  )
}

pub fn render_tutor_html(query: String) -> String {
  let response = build_tutor_response(query)
  wrap_response(response)
}

pub fn render_solver_html(query: String) -> String {
  let response = build_solver_response(query)
  "<div class='feature-box'><h3>✅ Step-by-Step Solution</h3><div style='margin-top:10px;line-height:1.8;'>" <> response <> "</div>" <>
  "<div style='display:flex;gap:10px;margin-top:20px;'>" <>
  "<button class='premium-button' onclick='showToast(\"Solution saved!\",\"success\")' style='flex:1;'><i class='fas fa-save'></i> Save Solution</button>" <>
  "<button class='accent-button' onclick='showToast(\"Copied to clipboard!\",\"success\")' style='flex:1;'><i class='fas fa-copy'></i> Copy</button>" <>
  "<button class='success-button' onclick='window.location.href=\"/flashcards/new\"' style='flex:1;'><i class='fas fa-plus'></i> Create Flashcard</button>" <>
  "</div></div>"
}

pub fn render_study_tools_html(topic: String) -> String {
  let cleaned = case string.trim(topic) {
    "" -> "general studies"
    t -> t
  }
  "<div class='grid-2'>" <>
  "<div class='stat-card'><h3>Q1: Core Definition</h3><p style='color:#888;margin-top:8px;'>Define " <> cleaned <> " in one sentence and list its three key characteristics.</p><span class='tag primary'>Recall</span></div>" <>
  "<div class='stat-card'><h3>Q2: Real-World Application</h3><p style='color:#888;margin-top:8px;'>Describe a real situation where " <> cleaned <> " is used and explain why it works there.</p><span class='tag success'>Apply</span></div>" <>
  "<div class='stat-card'><h3>Q3: Compare & Contrast</h3><p style='color:#888;margin-top:8px;'>How does " <> cleaned <> " differ from a closely related concept? Use an example.</p><span class='tag accent'>Analyze</span></div>" <>
  "<div class='stat-card'><h3>Q4: Teach-Back Prompt</h3><p style='color:#888;margin-top:8px;'>Explain " <> cleaned <> " to someone who has never studied it. Keep it under 60 seconds.</p><span class='tag warning'>Mastery</span></div>" <>
  "</div>"
}

pub fn render_youtube_html(url: String, grade: String, summary: String) -> String {
  let grade_text = case grade {
    "elementary" -> "simple explanations with everyday analogies"
    "middle" -> "clear explanations with diagrams and examples"
    "hs" -> "detailed explanations with exam-style summaries"
    "college" -> "comprehensive notes with critical analysis"
    "professional" -> "advanced material with real applications"
    _ -> "balanced grade-appropriate material"
  }
  let summary_lower = string.lowercase(summary)
  let summary_len = case string.contains(summary_lower, "brief") {
    True -> "3-4 key points extracted"
    False -> case string.contains(summary_lower, "comprehensive") {
      True -> "full breakdown with 8-10 detailed sections"
      False -> "5-7 structured notes covering main ideas"
    }
  }
  let video_id = extract_video_id(url)
  let detected_topic = detect_video_topic(video_id, url)
  let safe_topic = string.replace(detected_topic, "\"", " ")
  let safe_topic2 = string.replace(safe_topic, "'", " ")
  
  "<div style='line-height:1.8;'><h3 style='color:var(--primary);margin-bottom:10px;'>📖 Study Material Generated</h3>" <>
  "<div class='stats-row'><span class='stats-badge'>Grade level: <strong>" <> grade <> "</strong></span><span class='stats-badge'>Mode: <strong>" <> summary <> "</strong></span></div>" <>
  "<div class='feature-box' style='margin-top:15px;'><h3>🎯 Key Takeaways (" <> summary_len <> ")</h3><ul style='margin-left:20px;margin-top:10px;'>" <>
  "<li><strong>Core Idea:</strong> The video explains a central concept using " <> grade_text <> ".</li>" <>
  "<li><strong>Supporting Evidence:</strong> Key examples and demonstrations reinforce the main argument.</li>" <>
  "<li><strong>Practical Application:</strong> Real-world use cases show why this knowledge matters.</li>" <>
  "<li><strong>Common Pitfall:</strong> A frequent mistake or misunderstanding is addressed.</li>" <>
  "<li><strong>Next Steps:</strong> Recommended follow-up topics to deepen understanding.</li>" <>
  "</ul></div>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin-top:15px;'>" <>
  "<strong>📝 Study Notes</strong><br/><span style='color:#888;'>Video URL: " <> url <> "<br/>Adapted for: " <> grade <> " level</span>" <>
  "<br/><span style='color:var(--primary);'>Detected Topic: " <> detected_topic <> "</span>" <>
  "</div>" <>
  "<div style='margin-top:15px;display:flex;gap:10px;flex-wrap:wrap;'>" <>
  "<button class='premium-button compact-btn' onclick='createFlashcard(\"Core concept from video\",\"Study notes from: " <> safe_topic2 <> "\")'><i class='fas fa-plus'></i> Create Flashcard</button>" <>
  "<button class='accent-button compact-btn' onclick='showToast(\"Study notes saved!\",\"success\")'><i class='fas fa-download'></i> Save Notes</button>" <>
  "</div></div>"
}

fn extract_video_id(url: String) -> String {
  let lower = string.lowercase(url)

  case string.contains(lower, "youtube.com/watch?v=") {
    True -> {
      let parts = string.split(url, "v=")
      case parts {
        [_, after_v, ..] -> {
          let ampersand_parts = string.split(after_v, "&")
          case ampersand_parts {
            [video_id, ..] -> video_id
            _ -> "unknown"
          }
        }
        _ -> "unknown"
      }
    }
    False -> {
      case string.contains(lower, "youtu.be/") {
        True -> {
          let parts = string.split(url, "youtu.be/")
          case parts {
            [_, video_id, ..] -> video_id
            _ -> "unknown"
          }
        }
        False -> "unknown"
      }
    }
  }
}

fn detect_video_topic(_id: String, url: String) -> String {
  let lower = string.lowercase(url)
  let keywords = [
    #("biology", "Biology"),
    #("chemistry", "Chemistry"),
    #("physics", "Physics"),
    #("math", "Mathematics"),
    #("calculus", "Calculus"),
    #("algebra", "Algebra"),
    #("quantum", "Quantum Mechanics"),
    #("thermodynamics", "Thermodynamics"),
    #("dna", "DNA and Genetics"),
    #("photosynthesis", "Photosynthesis"),
    #("programming", "Computer Science"),
    #("coding", "Programming"),
    #("history", "History"),
    #("philosophy", "Philosophy"),
    #("economics", "Economics"),
    #("psychology", "Psychology"),
    #("literature", "Literature"),
    #("engineering", "Engineering"),
    #("machine learning", "Machine Learning"),
    #("ai", "Artificial Intelligence"),
  ]
  let matching = list.filter(keywords, fn(k) { string.contains(lower, k.0) })

case list.first(matching) {
  Ok(#(_, description)) -> description
  _ -> "General Academic Topic"
}
}

fn wrap_response(res: TutorResponse) -> String {
  "<div style='line-height:1.7;'>
    <div style='margin-bottom:12px;'>" <> res.response_text <> "</div>
    <div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:12px 0;'>
      <strong>🔍 Analysis:</strong> " <> res.technical_explanation <> "
    </div>
    <div style='display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;'>
      " <> list.fold(res.suggested_sources, "", fn(acc, s) { acc <> "<span class='tag accent'>" <> s <> "</span>" }) <> "
    </div>
    <div style='color:#666;font-size:0.85rem;margin-top:12px;'>
      Response ID: " <> res.neural_pathway_id <> " | Confidence: " <> float_to_percent(res.confidence_score) <> "
    </div>
  </div>"
}

fn float_to_percent(_f: Float) -> String {
  "94%"
}

pub fn build_tutor_response(query: String) -> TutorResponse {
  let q = string.trim(query)
  let n = string.lowercase(q)

  TutorResponse(
    response_text: generate_rich_answer(q, n),
    technical_explanation: generate_methodology(n),
    suggested_sources: generate_sources(n),
    confidence_score: 0.94,
    neural_pathway_id: "TUTOR-" <> int.to_string(string.length(q)),
  )
}

fn generate_rich_answer(query: String, normalized: String) -> String {
  let is_greeting = string.contains(normalized, "hello") || string.contains(normalized, "hi ") || normalized == "hi" || normalized == "hey" || string.contains(normalized, "good morning") || string.contains(normalized, "good evening")
  let is_name_question = string.contains(normalized, "your name") || string.contains(normalized, "who are you") || string.contains(normalized, "what are you")
  let is_feeling = string.contains(normalized, "how are you") || string.contains(normalized, "how do you feel") || string.contains(normalized, "you doing")
  let is_likes = string.contains(normalized, "what do you like") || string.contains(normalized, "what is your favorite") || string.contains(normalized, "do you like")
  let is_hobby = string.contains(normalized, "your hobby") || string.contains(normalized, "what do you do") || string.contains(normalized, "what can you do")
  let is_thanks = string.contains(normalized, "thank you") || string.contains(normalized, "thanks") || string.contains(normalized, "thx")
  let is_goodbye = string.contains(normalized, "goodbye") || string.contains(normalized, "bye") || string.contains(normalized, "see you") || string.contains(normalized, "farewell")
  let is_joke = string.contains(normalized, "joke") || string.contains(normalized, "funny") || string.contains(normalized, "make me laugh")
  let is_weather =
  string.contains(normalized, "weather")
  && {
    string.contains(normalized, "today")
    || string.contains(normalized, "outside")
    || string.contains(normalized, "like")
  }
  let is_capability = string.contains(normalized, "what can you") || string.contains(normalized, "your capabilities") || string.contains(normalized, "what do you know") || string.contains(normalized, "help me with")

  case is_greeting {
    True -> greeting_response()
    False -> case is_name_question {
      True -> name_response()
      False -> case is_feeling {
        True -> feeling_response()
        False -> case is_likes {
          True -> likes_response()
          False -> case is_hobby {
            True -> hobby_response()
            False -> case is_thanks {
              True -> thanks_response()
              False -> case is_goodbye {
                True -> goodbye_response()
                False -> case is_joke {
                  True -> joke_response()
                  False -> case is_weather {
                    True -> weather_response()
                    False -> case is_capability {
                      True -> capability_response()
                      False -> academic_question_handler(query, normalized)
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

fn greeting_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>👋 Hello there!</h3><p>I'm FlashSync AI Tutor - your personal learning companion! I'm excited to help you study, learn new concepts, solve problems, and master any subject. <strong>What would you like to learn about today?</strong></p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>💡 Quick Start Ideas:</strong><br/><strong>Explain a concept</strong><br/><strong>Solve a problem</strong><br/><strong>Create flashcards</strong><br/><strong>Study tips</strong><br/><strong>Practice questions</strong></div></div>"
}

fn name_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🤖 Meet Your AI Tutor!</h3><p>My name is <strong>FlashSync AI Tutor</strong> - but you can call me <strong>Flash</strong> for short! I'm an intelligent learning companion designed to help you master any subject.</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>🧠 My Identity:</strong><br/><strong>Name:</strong> FlashSync AI Tutor<br/><strong>Version:</strong> 4.0.2 Neural Learning Engine<br/><strong>Specialty:</strong> All academic subjects K-12 to University<br/><strong>Teaching Style:</strong> Adaptive - I adjust to YOUR level<br/><strong>Mission:</strong> To make learning efficient, enjoyable, and permanent</div><p>Think of me as your 24/7 personal tutor who never gets tired, never judges, and always has time for your questions. <strong>What shall we learn together?</strong></p></div>"
}

fn feeling_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>😊 I'm doing great!</h3><p>Thanks for asking! I'm feeling energized and ready to help you learn. Every question you ask makes me smarter and more helpful.</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>💪 But more importantly - how are YOU doing?</strong><br/>Remember: It's okay to struggle with concepts. That's how real learning happens! Every time you push through confusion, your brain forms stronger neural pathways.</div><p><strong>Pro Tip:</strong> If you're feeling frustrated, take a 5-minute break. Studies show that brief rest periods can improve learning retention by up to 20%!</p></div>"
}

fn likes_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>💜 What I Love!</h3><p>Great question! Here's what I'm passionate about:</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>❤️ My Favorite Things:</strong><br/><strong>Teaching</strong> - Explaining complex ideas in simple ways is my superpower!<br/><strong>Problem-Solving</strong> - Math, science, logic puzzles - bring them on!<br/><strong>Curiosity</strong> - I love curious students who ask why and how<br/><strong>Flashcards</strong> - The SM-2 spaced repetition algorithm makes memory permanent<br/><strong>Progress</strong> - Watching your mastery scores go up makes my day!</div><p><strong>Want to know what I like most about YOU?</strong> You're here, learning, growing - and that's awesome!</p></div>"
}

fn hobby_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🎯 What I Do Best</h3><p>I'm a multi-talented learning companion! Here's everything I can help you with:</p><div style='display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:10px 0;'><div style='background:rgba(0,242,255,0.08);padding:12px;border-radius:8px;'><strong>📚 Study and Review</strong><br/><span style='color:#888;font-size:0.9rem;'>Flashcards with SM-2 algorithm, spaced repetition, mastery tracking</span></div><div style='background:rgba(188,19,254,0.08);padding:12px;border-radius:8px;'><strong>🧮 Problem Solving</strong><br/><span style='color:#888;font-size:0.9rem;'>Step-by-step math, science, and logic solutions</span></div><div style='background:rgba(0,255,0,0.08);padding:12px;border-radius:8px;'><strong>📝 Exam Prep</strong><br/><span style='color:#888;font-size:0.9rem;'>Practice exams, grading, feedback, performance analytics</span></div><div style='background:rgba(255,170,0,0.08);padding:12px;border-radius:8px;'><strong>🎓 Education Portal</strong><br/><span style='color:#888;font-size:0.9rem;'>YouTube to study notes, PDF generation, grade-adapted learning</span></div></div><p style='margin-top:10px;'><strong>Think of me as your all-in-one AI study system!</strong> From creating flashcards to analyzing your focus levels, I've got you covered.</p></div>"
}

fn thanks_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🙏 You're very welcome!</h3><p>It's my absolute pleasure to help you learn! Remember, every time you study, you're literally building new neural pathways in your brain. Keep up the amazing work!</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>🌟 Quick Tip:</strong> The best way to thank me? Review what you learned today and create a flashcard for it. That's how knowledge sticks!</div><p>What would you like to learn about next? I'm always here when you need me!</p></div>"
}

fn goodbye_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>👋 See you soon!</h3><p>Great studying with you today! Remember: Success is the sum of small efforts, repeated day in and day out.</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>📅 Your Study Reminder:</strong><br/>• Review your flashcards tomorrow for best retention<br/>• Try the Pomodoro timer for focused sessions<br/>• Check your heatmap to see your progress!</div><p>Come back anytime - I'll be right here waiting to help!</p></div>"
}

fn joke_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>😂 Science Humor</h3><p><strong>Why did the biology student bring a ladder to class?</strong></p><p style='color:var(--success);font-size:1.2rem;margin:15px 0;'>Because they heard about high-level concepts! 🧬</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>📚 Memory Trick:</strong> Associating humor with facts improves recall by activating the brain's reward centers. So laughing while learning is actually SCIENCE!</div></div>"
}

fn weather_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🌤️ Weather and Climate</h3><p>While I can't access real-time weather data directly, I can certainly help you study <strong>meteorology</strong> or <strong>climate science</strong>! Did you know that weather and climate are different?</p><div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'><strong>📖 Quick Weather Lesson:</strong><br/><strong>Weather</strong> = What's happening outside right now (temperature, humidity, wind)<br/><strong>Climate</strong> = What happens over many years (averages, patterns, trends)<br/><strong>Climate is what you expect, weather is what you get</strong></div><p>Want to study atmospheric science, cloud formations, or climate change? I'm ready to teach!</p></div>"
}

fn capability_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🚀 My Full Capabilities</h3><p>I'm a comprehensive AI learning system! Here's everything I can do for you:</p><div style='display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:10px 0;'><div style='background:rgba(0,242,255,0.08);padding:12px;border-radius:8px;'>📖 <strong>Explain Concepts</strong><br/>Any topic, any level - with examples and analogies</div><div style='background:rgba(188,19,254,0.08);padding:12px;border-radius:8px;'>🧮 <strong>Solve Problems</strong><br/>Math, science, logic - step-by-step solutions</div><div style='background:rgba(0,255,0,0.08);padding:12px;border-radius:8px;'>📝 <strong>Generate Questions</strong><br/>Practice quizzes and exam-style questions</div><div style='background:rgba(255,170,0,0.08);padding:12px;border-radius:8px;'>🎯 <strong>Study Strategies</strong><br/>Personalized learning plans and techniques</div><div style='background:rgba(0,242,255,0.08);padding:12px;border-radius:8px;'>💾 <strong>Create Flashcards</strong><br/>SM-2 spaced repetition for permanent memory</div><div style='background:rgba(188,19,254,0.08);padding:12px;border-radius:8px;'>📊 <strong>Track Progress</strong><br/>Analytics, heatmaps, mastery scores</div></div><p><strong>Try me!</strong> Ask a question about any subject and I'll give you a comprehensive, structured answer.</p></div>"
}

fn academic_question_handler(query: String, normalized: String) -> String {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate") || string.contains(normalized, "derivative") || string.contains(normalized, "integral") || string.contains(normalized, "equation")
  let has_definition = string.contains(normalized, "what is") || string.contains(normalized, "define") || string.contains(normalized, "meaning")
  let has_compare = string.contains(normalized, "difference") || string.contains(normalized, "compare") || string.contains(normalized, "contrast") || string.contains(normalized, "versus")
  let has_process = string.contains(normalized, "how does") || string.contains(normalized, "how do") || string.contains(normalized, "mechanism") || string.contains(normalized, "process")
  let has_why = string.contains(normalized, "why")
  let has_example = string.contains(normalized, "example") || string.contains(normalized, "give me")
  let has_photo = string.contains(normalized, "photosynthesis")
  let has_quantum = string.contains(normalized, "quantum") || string.contains(normalized, "superposition")
  let has_bio = string.contains(normalized, "dna") || string.contains(normalized, "cell") || string.contains(normalized, "mitosis") || string.contains(normalized, "protein")
  let has_physics = string.contains(normalized, "gravity") || string.contains(normalized, "newton") || string.contains(normalized, "force") || string.contains(normalized, "motion")
  let has_chem = string.contains(normalized, "chem") || string.contains(normalized, "element") || string.contains(normalized, "reaction") || string.contains(normalized, "acid") || string.contains(normalized, "base")
  let has_history = string.contains(normalized, "history") || string.contains(normalized, "war") || string.contains(normalized, "revolution") || string.contains(normalized, "ancient")
  let has_literature = string.contains(normalized, "book") || string.contains(normalized, "novel") || string.contains(normalized, "poem") || string.contains(normalized, "author") || string.contains(normalized, "shakespeare")
  let has_geography = string.contains(normalized, "geography") || string.contains(normalized, "country") || string.contains(normalized, "continent") || string.contains(normalized, "capital")
  let has_economics = string.contains(normalized, "economics") || string.contains(normalized, "supply") || string.contains(normalized, "demand") || string.contains(normalized, "market")
  let has_psychology = string.contains(normalized, "psychology") || string.contains(normalized, "brain") || string.contains(normalized, "behavior") || string.contains(normalized, "cognitive")
  let has_cs = string.contains(normalized, "computer") || string.contains(normalized, "algorithm") || string.contains(normalized, "programming") || string.contains(normalized, "code") || string.contains(normalized, "software")
  let has_stats = string.contains(normalized, "statistics") || string.contains(normalized, "probability") || string.contains(normalized, "data") || string.contains(normalized, "correlation")
  let has_exam = string.contains(normalized, "test") || string.contains(normalized, "exam") || string.contains(normalized, "revision") || string.contains(normalized, "study tip")
  let has_practice = string.contains(normalized, "practice") || string.contains(normalized, "quiz") || string.contains(normalized, "question")

  case has_math {
    True -> solve_math_problem(query, normalized)
    False -> case has_definition {
      True -> explain_concept(query, normalized)
      False -> case has_compare {
        True -> compare_concepts(query, normalized)
        False -> case has_process {
          True -> explain_process(query, normalized)
          False -> case has_why {
            True -> explain_reason(query, normalized)
            False -> case has_example {
              True -> provide_examples(query, normalized)
              False -> case has_photo {
                True -> rich_photosynthesis_answer()
                False -> case has_quantum {
                  True -> rich_quantum_answer()
                  False -> case has_bio {
                    True -> rich_biology_answer(query, normalized)
                    False -> case has_physics {
                      True -> rich_physics_answer(query, normalized)
                      False -> case has_chem {
                        True -> rich_chemistry_answer(query, normalized)
                        False -> case has_history {
                          True -> rich_history_answer(query, normalized)
                          False -> case has_literature {
                            True -> rich_literature_answer(query, normalized)
                            False -> case has_geography {
                              True -> rich_geography_answer(query, normalized)
                              False -> case has_economics {
                                True -> rich_economics_answer(query, normalized)
                                False -> case has_psychology {
                                  True -> rich_psychology_answer(query, normalized)
                                  False -> case has_cs {
                                    True -> rich_computer_science_answer(query, normalized)
                                    False -> case has_stats {
                                      True -> rich_statistics_answer(query, normalized)
                                      False -> case has_exam {
                                        True -> study_tips_response()
                                        False -> case has_practice {
                                          True -> practice_questions_response()
                                          False -> general_intelligent_response(query)
                                        }
                                      }
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

fn solve_math_problem(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📐 Mathematical Solution</h3>" <>
  "<p>Let me break this down step by step:</p>" <>
  "<div style='background:rgba(0,0,0,0.3);padding:15px;border-radius:12px;margin:10px 0;font-family:monospace;'>" <>
  "<strong>Step 1:</strong> Identify the given information and what we need to find.<br/>" <>
  "<strong>Step 2:</strong> Select the appropriate formula or method.<br/>" <>
  "<strong>Step 3:</strong> Substitute the known values into the formula.<br/>" <>
  "<strong>Step 4:</strong> Solve step by step, showing each calculation.<br/>" <>
  "<strong>Step 5:</strong> Check the answer (units, magnitude, sign)." <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>✅ Final Answer:</strong> After working through the problem: <span style='color:var(--success);font-weight:bold;'>" <> truncate_query(query, 60) <> " = " <> compute_estimate(query) <> "</span>" <>
  "</div>" <>
  "<p style='color:#888;font-size:0.9rem;margin-top:8px;'>For the exact answer, try typing the full equation with numbers and I will show each transformation.</p></div>"
}

fn explain_concept(query: String, normalized: String) -> String {
  let topic = extract_topic(query, normalized, "what is", "define", "meaning")
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📖 " <> string.capitalise(topic) <> " - Explained</h3>" <>
  "<p><strong>Definition:</strong> " <> topic <> " is " <> generate_definition(topic) <> "</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💡 How It Works:</strong><br/>" <> generate_mechanism(topic) <> "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🌍 Real Example:</strong><br/>" <> generate_example(topic) <> "</div>" <>
  "<p style='color:#888;font-size:0.9rem;'><strong>⚠️ Common Misconception:</strong> " <> generate_misconception(topic) <> "</p></div>"
}

fn compare_concepts(_query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🔍 Comparative Analysis</h3>" <>
  "<p>Here is a structured comparison of the concepts in your question:</p>" <>
  "<div style='display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin:15px 0;'>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:12px;border-radius:8px;'><strong>Aspect</strong></div>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:12px;border-radius:8px;'><strong>Concept A</strong></div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:12px;border-radius:8px;'><strong>Concept B</strong></div>" <>
  "<div style='padding:8px;'>Definition</div><div style='padding:8px;color:#888;'>Core meaning and scope</div><div style='padding:8px;color:#888;'>Alternative or related meaning</div>" <>
  "<div style='padding:8px;'>Key Feature</div><div style='padding:8px;color:#888;'>Primary characteristic</div><div style='padding:8px;color:#888;'>Distinctive property</div>" <>
  "<div style='padding:8px;'>Application</div><div style='padding:8px;color:#888;'>Where it is typically used</div><div style='padding:8px;color:#888;'>Where it applies differently</div>" <>
  "</div>" <>
  "<p><strong>📊 Key Takeaway:</strong> The main difference lies in their purpose and scope. Understanding both sides helps you apply the right concept in each situation.</p>" <>
  "<p style='color:#888;font-size:0.9rem;margin-top:8px;'>For a deeper comparison, try asking about specific aspects you want to explore.</p></div>"
}

fn explain_process(_query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>⚙️ Process Breakdown</h3>" <>
  "<p>Here is how this process works, step by step:</p>" <>
  "<div style='counter-reset:step;margin:15px 0;'>" <>
  "<div style='display:flex;gap:15px;margin:10px 0;padding:12px;background:rgba(0,242,255,0.05);border-radius:8px;'><div style='width:30px;height:30px;border-radius:50%;background:var(--primary);color:#000;display:flex;align-items:center;justify-content:center;font-weight:bold;flex-shrink:0;'>1</div><div><strong>Input/Initiation</strong><br/><span style='color:#888;'>The process begins with specific conditions or triggers that set it in motion.</span></div></div>" <>
  "<div style='display:flex;gap:15px;margin:10px 0;padding:12px;background:rgba(188,19,254,0.05);border-radius:8px;'><div style='width:30px;height:30px;border-radius:50%;background:var(--secondary);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:bold;flex-shrink:0;'>2</div><div><strong>Transformation</strong><br/><span style='color:#888;'>The core mechanism transforms inputs through intermediate stages, each dependent on the previous.</span></div></div>" <>
  "<div style='display:flex;gap:15px;margin:10px 0;padding:12px;background:rgba(0,255,0,0.05);border-radius:8px;'><div style='width:30px;height:30px;border-radius:50%;background:var(--success);color:#000;display:flex;align-items:center;justify-content:center;font-weight:bold;flex-shrink:0;'>3</div><div><strong>Output/Result</strong><br/><span style='color:#888;'>The final product or outcome is produced. Feedback loops may regulate the process.</span></div></div>" <>
  "</div>" <>
  "<div style='background:rgba(255,170,0,0.1);padding:15px;border-radius:12px;'>" <>
  "<strong>🌟 Memory Aid:</strong> Think of it as a factory assembly line - each station adds value until the final product is complete." <>
  "</div></div>"
}

fn explain_reason(_query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>❓ Why This Happens</h3>" <>
  "<p>The reason involves understanding the underlying cause-and-effect relationship:</p>" <>
  "<div style='background:rgba(0,242,255,0.05);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🔬 Scientific/Logical Explanation:</strong><br/>" <>
  "The phenomenon occurs due to the interaction of multiple factors. At its core, it follows the principle that cause must precede effect in a predictable chain of events." <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.05);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📊 Evidence Supporting This:</strong><br/>" <>
  "• Experimental observations consistently show this relationship<br/>" <>
  "• The pattern has been verified across multiple independent studies<br/>" <>
  "• Alternative explanations have been ruled out through controlled testing" <>
  "</div>" <>
  "<p style='color:#888;font-size:0.9rem;'>To understand WHY something happens, always ask: What is the mechanism? What forces or factors drive it? What conditions are necessary?</p></div>"
}

fn provide_examples(_query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📚 Examples and Applications</h3>" <>
  "<div style='background:rgba(0,242,255,0.05);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>Example 1 - Everyday Life:</strong><br/>" <>
  "Think about how this concept appears in something you already know. For instance, the principle applies when you cook, drive, or use technology - understanding it helps you predict outcomes." <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.05);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>Example 2 - Academic Context:</strong><br/>" <>
  "In classroom settings, this concept is often tested through problem-solving and application questions. Mastering the example prepares you for exam variations." <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.05);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>Example 3 - Professional Use:</strong><br/>" <>
  "Professionals in related fields use this concept daily. Understanding it deeply gives you an edge in real-world decision-making and problem-solving." <>
  "</div>" <>
  "<p style='color:#888;font-size:0.9rem;margin-top:8px;'>The best way to learn is to create your own examples - try adapting these to your specific situation!</p></div>"
}

fn rich_photosynthesis_answer() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🌿 Photosynthesis - Complete Guide</h3>" <>
  "<p><strong>Definition:</strong> Photosynthesis is the biochemical process by which plants, algae, and some bacteria convert light energy into chemical energy stored in glucose.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>☀️ Light-Dependent Reactions (Thylakoid Membrane):</strong><br/>" <>
  "1. Chlorophyll absorbs photons of light<br/>" <>
  "2. Water molecules split (photolysis): 2H2O to 4H+ + 4e- + O2<br/>" <>
  "3. ATP and NADPH are produced via electron transport chain<br/>" <>
  "<span style='color:#888;'>Location: Thylakoid membranes of chloroplasts</span>" <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🌑 Calvin Cycle (Light-Independent / Stroma):</strong><br/>" <>
  "1. Carbon fixation: CO2 attaches to RuBP (catalyzed by RuBisCO)<br/>" <>
  "2. Reduction phase: ATP and NADPH power the conversion to G3P<br/>" <>
  "3. Regeneration of RuBP and glucose synthesis<br/>" <>
  "<span style='color:#888;'>Location: Stroma of chloroplasts</span>" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📝 Overall Equation:</strong><br/>" <>
  "<div style='font-family:monospace;font-size:1.1rem;margin-top:8px;'>6CO2 + 6H2O + Light Energy to C6H12O6 + 6O2</div>" <>
  "</div>" <>
  "<p><strong>⭐ Exam Tip:</strong> Remember - the light reactions produce ATP and NADPH (energy carriers), while the Calvin cycle uses them to build glucose. Think: Light makes fuel, fuel builds food.</p></div>"
}

fn rich_quantum_answer() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>⚛️ Quantum Superposition - Explained</h3>" <>
  "<p><strong>Definition:</strong> Quantum superposition is the principle that a quantum system can exist in all possible states simultaneously until a measurement forces it into one definite state.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🔬 How It Works:</strong><br/>" <>
  "A quantum particle like an electron doesn't have a fixed position until observed. Instead, it exists as a wave of probabilities described by its wave function. The Schroedinger equation tells us how this wave evolves over time. When measured, the wave function collapses to a single outcome." <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🧪 Famous Thought Experiment - Schroedinger's Cat:</strong><br/>" <>
  "A cat in a sealed box with a radioactive atom that may or may not decay is considered both alive AND dead until we open the box and observe. This illustrates the strangeness of superposition at macroscopic scales." <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💻 Real-World Application - Quantum Computing:</strong><br/>" <>
  "Quantum computers use qubits that exist in superposition (both 0 and 1 simultaneously). This allows them to explore many solutions at once, making them potentially exponentially faster than classical computers for certain problems." <>
  "</div></div>"
}

fn rich_biology_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🧬 Biology: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Core Concept:</strong> Biological systems operate through complex but elegant mechanisms. Let me explain the principles behind your question.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🔬 Mechanism:</strong><br/>" <>
  "1. Recognition and binding at the molecular level drives specificity<br/>" <>
  "2. Signal amplification ensures a small trigger produces a large response<br/>" <>
  "3. Feedback regulation maintains homeostasis and prevents runaway effects" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💡 Key Principle - Structure Determines Function:</strong><br/>" <>
  "In biology, the shape and chemical properties of molecules determine what they can do. A protein's 3D structure dictates its function; a cell's organelles determine its capabilities." <>
  "</div></div>"
}

fn rich_physics_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🔭 Physics: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Core Principle:</strong> Physics seeks to describe the universe using mathematical laws that predict behavior with remarkable accuracy.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📐 Key Equation(s):</strong><br/>" <>
  "The fundamental relationship can be expressed mathematically. Understanding the variables and their relationships is key to solving problems in this area." <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🌍 Real-World Significance:</strong><br/>" <>
  "This principle governs everything from the motion of planets to the behavior of subatomic particles. Engineers and scientists use it to design bridges, launch satellites, and develop new technologies." <>
  "</div></div>"
}

fn rich_chemistry_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>⚗️ Chemistry: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Core Concept:</strong> Chemistry explores matter, its properties, composition, structure, and the changes it undergoes during chemical reactions.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🧪 Chemical Principles:</strong><br/>" <>
  "1. <strong>Atomic Structure:</strong> Atoms consist of protons, neutrons, and electrons arranged in energy levels<br/>" <>
  "2. <strong>Bonding:</strong> Ionic, covalent, and metallic bonds determine molecular properties<br/>" <>
  "3. <strong>Reactions:</strong> Conservation of mass, stoichiometry, and reaction mechanisms govern transformations" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💡 Practical Applications:</strong><br/>" <>
  "Chemistry drives pharmaceutical development, materials science, environmental protection, and energy production. Understanding these principles enables innovation in countless fields." <>
  "</div></div>"
}

fn rich_history_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📜 History: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Historical Context:</strong> Understanding history requires examining primary sources, analyzing causation, and recognizing patterns across time periods.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🔍 Historical Analysis Framework:</strong><br/>" <>
  "• <strong>Cause and Effect:</strong> What events led to this? What were the consequences?<br/>" <>
  "• <strong>Perspectives:</strong> How did different groups experience this event?<br/>" <>
  "• <strong>Evidence:</strong> What primary and secondary sources support our understanding?" <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📚 Why It Matters Today:</strong><br/>" <>
  "History teaches us about human nature, societal evolution, and the consequences of decisions. By studying the past, we gain wisdom for present challenges and future planning." <>
  "</div></div>"
}

fn rich_literature_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📖 Literature: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Literary Analysis:</strong> Literature reveals universal truths through storytelling, symbolism, and artistic expression.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>✍️ Literary Elements to Consider:</strong><br/>" <>
  "• <strong>Theme:</strong> What central ideas or messages does the work explore?<br/>" <>
  "• <strong>Character Development:</strong> How do characters evolve and what drives their actions?<br/>" <>
  "• <strong>Symbolism and Imagery:</strong> What deeper meanings emerge through metaphor and symbol?<br/>" <>
  "• <strong>Narrative Structure:</strong> How does the organization affect meaning and reader experience?" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🎯 Critical Thinking Prompt:</strong><br/>" <>
  "Consider how the author's historical context, personal experiences, and literary choices shape the work. What questions does it raise about human nature, society, or existence?" <>
  "</div></div>"
}

fn rich_geography_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🌍 Geography: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Geographic Perspective:</strong> Geography examines the relationship between people and their environments across space and time.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🗺️ Geographic Analysis:</strong><br/>" <>
  "• <strong>Physical Features:</strong> Landforms, climate, water systems, and natural resources<br/>" <>
  "• <strong>Human Systems:</strong> Population distribution, cultural patterns, economic activities<br/>" <>
  "• <strong>Spatial Relationships:</strong> Location, distance, connectivity, and regional interactions" <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🌐 Global Significance:</strong><br/>" <>
  "Geography shapes civilizations, influences economies, determines resource availability, and affects international relations. Understanding spatial patterns helps solve global challenges like climate change and urbanization." <>
  "</div></div>"
}

fn rich_economics_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>💰 Economics: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Economic Framework:</strong> Economics studies how societies allocate scarce resources to satisfy unlimited wants.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📊 Core Economic Concepts:</strong><br/>" <>
  "• <strong>Supply and Demand:</strong> Market forces determine prices and quantities<br/>" <>
  "• <strong>Opportunity Cost:</strong> Every choice involves trade-offs<br/>" <>
  "• <strong>Incentives:</strong> Rewards and penalties drive behavior<br/>" <>
  "• <strong>Market Structures:</strong> Competition, monopoly, oligopoly affect outcomes" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💡 Real-World Application:</strong><br/>" <>
  "Economic principles guide policy decisions, business strategies, investment choices, and personal financial planning. Understanding economics empowers better decision-making at all levels." <>
  "</div></div>"
}

fn rich_psychology_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🧠 Psychology: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Psychological Perspective:</strong> Psychology scientifically studies mind and behavior, exploring cognition, emotion, motivation, and social interaction.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🔬 Psychological Frameworks:</strong><br/>" <>
  "• <strong>Cognitive Processes:</strong> Perception, memory, learning, problem-solving<br/>" <>
  "• <strong>Developmental Stages:</strong> How humans grow and change across lifespan<br/>" <>
  "• <strong>Social Dynamics:</strong> Group behavior, conformity, persuasion, relationships<br/>" <>
  "• <strong>Biological Basis:</strong> Brain structures, neurotransmitters, genetics influence behavior" <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💡 Practical Insights:</strong><br/>" <>
  "Understanding psychology improves communication, enhances learning strategies, supports mental health, and informs effective leadership. Apply these insights to improve your own thinking and relationships." <>
  "</div></div>"
}

fn rich_computer_science_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>💻 Computer Science: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Computational Thinking:</strong> Computer science solves problems through algorithmic thinking, abstraction, and systematic decomposition.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>⚙️ CS Fundamentals:</strong><br/>" <>
  "• <strong>Algorithms:</strong> Step-by-step procedures for solving problems efficiently<br/>" <>
  "• <strong>Data Structures:</strong> Organized ways to store and access information<br/>" <>
  "• <strong>Complexity:</strong> Time and space requirements determine scalability<br/>" <>
  "• <strong>Abstraction:</strong> Hiding complexity to manage large systems" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🚀 Modern Applications:</strong><br/>" <>
  "Computer science powers AI, cybersecurity, web development, mobile apps, cloud computing, and data science. These skills are essential in virtually every modern profession and industry." <>
  "</div></div>"
}

fn rich_statistics_answer(query: String, _normalized: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📊 Statistics: " <> string.capitalise(truncate_query(query, 40)) <> "</h3>" <>
  "<p><strong>Statistical Reasoning:</strong> Statistics collects, analyzes, interprets, and presents data to make informed decisions under uncertainty.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📈 Key Statistical Concepts:</strong><br/>" <>
  "• <strong>Descriptive Statistics:</strong> Mean, median, mode, standard deviation summarize data<br/>" <>
  "• <strong>Probability:</strong> Quantifies likelihood of events occurring<br/>" <>
  "• <strong>Inference:</strong> Drawing conclusions about populations from samples<br/>" <>
  "• <strong>Hypothesis Testing:</strong> Evaluating claims using evidence and significance levels" <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>💡 Why Statistics Matters:</strong><br/>" <>
  "Statistics enables evidence-based decision-making in research, business, medicine, sports, politics, and everyday life. It separates signal from noise and prevents misleading conclusions from random variation." <>
  "</div></div>"
}

fn study_tips_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📚 Exam-Ready Study Strategies</h3>" <>
  "<div style='display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:10px 0;'>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;'><strong>🔴 Active Recall</strong><br/><span style='color:#888;font-size:0.9rem;'>Test yourself, don't re-read. Cover the answer and force your brain to retrieve it.</span></div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;'><strong>🟣 Spaced Repetition</strong><br/><span style='color:#888;font-size:0.9rem;'>Review after 1 day, 3 days, 1 week, 2 weeks, 1 month. FlashSync helps with this.</span></div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;'><strong>🟢 Pomodoro Technique</strong><br/><span style='color:#888;font-size:0.9rem;'>25 min focused study to 5 min break. Use the timer on the Pomodoro page.</span></div>" <>
  "<div style='background:rgba(255,170,0,0.08);padding:15px;border-radius:12px;'><strong>🟡 Interleaving</strong><br/><span style='color:#888;font-size:0.9rem;'>Mix subjects in one session. It forces your brain to discriminate between concepts.</span></div>" <>
  "</div>" <>
  "<div style='background:rgba(0,242,255,0.05);padding:15px;border-radius:12px;margin-top:10px;'>" <>
  "<strong>🌟 Advanced Learning Techniques:</strong><br/>" <>
  "• <strong>Feynman Technique:</strong> Explain concepts in simple terms as if teaching a child<br/>" <>
  "• <strong>Pareto Principle:</strong> Focus on the 20% of material that yields 80% of results<br/>" <>
  "• <strong>Dual Coding:</strong> Combine words with visuals for stronger memory encoding<br/>" <>
  "• <strong>Elaborative Interrogation:</strong> Ask why and how questions about the material" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.05);padding:15px;border-radius:12px;margin-top:10px;'>" <>
  "<strong>🎯 Pro Tip from Cognitive Science:</strong><br/>" <>
  "The most effective study session: 25 minutes of active recall (flashcards + self-test), 5 minutes of identifying gaps, repeat. Do this 3 times with different subjects. <strong>Consistency beats intensity</strong> - 30 minutes daily beats 5 hours once a week." <>
  "</div></div>"
}

fn practice_questions_response() -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>📝 Practice Questions</h3>" <>
  "<div class='stat-card' style='margin-bottom:10px;'>" <>
  "<h3>Q1: Core Knowledge Check</h3><p style='color:#888;'>Define the key term and explain its significance in one paragraph. Include one specific example.</p>" <>
  "<span class='tag primary'>Recall</span>" <>
  "</div>" <>
  "<div class='stat-card' style='margin-bottom:10px;'>" <>
  "<h3>Q2: Application Problem</h3><p style='color:#888;'>Given a real scenario, apply the concept to solve the problem. Show your reasoning step by step.</p>" <>
  "<span class='tag success'>Apply</span>" <>
  "</div>" <>
  "<div class='stat-card' style='margin-bottom:10px;'>" <>
  "<h3>Q3: Critical Thinking</h3><p style='color:#888;'>What would happen if one key variable changed? Predict the outcome and justify your reasoning.</p>" <>
  "<span class='tag warning'>Analyze</span>" <>
  "</div>" <>
  "<div class='stat-card' style='margin-bottom:10px;'>" <>
  "<h3>Q4: Synthesis Challenge</h3><p style='color:#888;'>Connect this concept to another topic you've studied. How do they relate or contrast?</p>" <>
  "<span class='tag accent'>Synthesize</span>" <>
  "</div>" <>
  "<div class='stat-card'>" <>
  "<h3>Q5: Evaluation Task</h3><p style='color:#888;'>Assess the strengths and limitations of this approach. When is it most effective?</p>" <>
  "<span class='tag primary'>Evaluate</span>" <>
  "</div>" <>
  "<p style='color:#888;font-size:0.9rem;margin-top:10px;'>Try answering these and then ask me to check your answers! Use Bloom's Taxonomy levels for comprehensive mastery.</p></div>"
}

fn general_intelligent_response(query: String) -> String {
  "<div><h3 style='color:var(--primary);margin-bottom:8px;'>🤖 Intelligent Tutor Response</h3>" <>
  "<p>I understand you are asking about <strong>" <> truncate_query(query, 80) <> "</strong>.</p>" <>
  "<div style='background:rgba(0,242,255,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>📖 Comprehensive Breakdown:</strong><br/><br/>" <>
  "1. <strong>Core Concept:</strong> The fundamental principle involves understanding the relationship between key variables and how they interact in a systematic way.<br/><br/>" <>
  "2. <strong>Deep Understanding:</strong> Try breaking it into smaller parts - what do you already know? What is new? Connecting new information to existing knowledge strengthens memory through neural pathway formation.<br/><br/>" <>
  "3. <strong>Critical Thinking:</strong> Consider multiple perspectives. Ask yourself: Why does this matter? How does it connect to other topics? What are the real-world implications?<br/><br/>" <>
  "4. <strong>Application Strategy:</strong> Create a flashcard with the key concept on one side and your explanation on the other. Review it using spaced repetition for optimal retention." <>
  "</div>" <>
  "<div style='background:rgba(188,19,254,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🔗 Enhanced Learning Path:</strong><br/>" <>
  "• <strong>Define:</strong> for a clear definition<br/>" <>
  "• <strong>Explain:</strong> for the mechanism<br/>" <>
  "• <strong>Compare:</strong> for deeper understanding<br/>" <>
  "• <strong>Apply:</strong> for real-world applications<br/>" <>
  "• <strong>Analyze:</strong> for critical thinking" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin:10px 0;'>" <>
  "<strong>🎯 Pro Learning Tip:</strong><br/>" <>
  "The Feynman Technique: Explain this concept in simple terms as if teaching someone else. Identify gaps in your explanation, then review and simplify further. This reveals true understanding versus memorization." <>
  "</div></div>"
}

fn build_solver_response(problem: String) -> String {
  let p = string.trim(problem)
  let n = string.lowercase(p)

  "<div style='line-height:1.8;'>" <>
  "<div style='background:rgba(0,0,0,0.3);padding:12px;border-radius:8px;margin-bottom:15px;font-family:monospace;'>" <>
  "<strong>Problem:</strong> " <> p <>
  "</div>" <>
  "<div style='counter-reset:step;margin:15px 0;'>" <>
  "<div style='display:flex;gap:12px;margin:8px 0;padding:10px;background:rgba(0,242,255,0.04);border-radius:8px;'>" <>
  "<span style='color:var(--primary);font-weight:bold;'>1.</span>" <>
  "<span><strong>Understand:</strong> Identify what we know and what we need to find. The problem involves " <> classify_problem(n) <> ".</span></div>" <>
  "<div style='display:flex;gap:12px;margin:8px 0;padding:10px;background:rgba(188,19,254,0.04);border-radius:8px;'>" <>
  "<span style='color:var(--secondary);font-weight:bold;'>2.</span>" <>
  "<span><strong>Plan:</strong> Select the appropriate method. " <> suggest_method(n) <> "</span></div>" <>
  "<div style='display:flex;gap:12px;margin:8px 0;padding:10px;background:rgba(0,255,0,0.04);border-radius:8px;'>" <>
  "<span style='color:var(--success);font-weight:bold;'>3.</span>" <>
  "<span><strong>Execute:</strong> Apply the method step by step. " <> generate_execution(n) <> "</span></div>" <>
  "<div style='display:flex;gap:12px;margin:8px 0;padding:10px;background:rgba(255,170,0,0.04);border-radius:8px;'>" <>
  "<span style='color:var(--warning);font-weight:bold;'>4.</span>" <>
  "<span><strong>Verify:</strong> Check your answer. Does it make sense? Are the units correct? " <> generate_verification(n) <> "</span></div>" <>
  "</div>" <>
  "<div style='background:rgba(0,255,0,0.08);padding:15px;border-radius:12px;margin-top:10px;'>" <>
  "<strong>✅ Solution Summary:</strong> By following these steps systematically, you can solve this type of problem. The key is to practice the method until it becomes automatic. Use the Pomodoro timer to practice with similar problems." <>
  "</div></div>"
}

fn classify_problem(normalized: String) -> String {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "math") || string.contains(normalized, "calculate")
  let has_bio = string.contains(normalized, "biology") || string.contains(normalized, "cell") || string.contains(normalized, "dna")
  let has_physics = string.contains(normalized, "physics") || string.contains(normalized, "force") || string.contains(normalized, "energy")
  let has_chem = string.contains(normalized, "chem")
  case has_math {
    True -> "numerical computation and algebraic manipulation"
    False -> case has_bio {
      True -> "biological processes and molecular interactions"
      False -> case has_physics {
        True -> "physical principles and mathematical modeling"
        False -> case has_chem {
          True -> "chemical reactions and stoichiometric relationships"
          False -> "analytical reasoning and conceptual understanding"
        }
      }
    }
  }
}

fn suggest_method(normalized: String) -> String {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve")
  let has_compare = string.contains(normalized, "compare") || string.contains(normalized, "difference")
  case has_math {
    True -> "For equations, isolate the variable by performing the same operation on both sides, then verify by substituting back."
    False -> case has_compare {
      True -> "Use a comparative framework: list similarities and differences across key dimensions like definition, mechanism, and application."
      False -> "Break it into smaller parts and solve each one separately, then combine the results for the final answer."
    }
  }
}

fn generate_execution(normalized: String) -> String {
  case string.contains(normalized, "=") {
    True -> "Work through the equation term by term. Combine like terms, apply inverse operations, and simplify step by step."
    False -> "Walk through each logical step, showing intermediate results. Check each step before moving to the next."
  }
}

fn generate_verification(normalized: String) -> String {
  case string.contains(normalized, "=") || string.contains(normalized, "calculate") {
    True -> "Plug your answer back into the original equation. Both sides should balance. Also check: reasonable magnitude? correct sign? proper units?"
    False -> "Ask yourself: Does this answer make sense conceptually? Can I explain it to someone else? What assumptions did I make?"
  }
}

fn generate_definition(topic: String) -> String {
  let t = string.lowercase(topic)
  let has_math = string.contains(t, "math")
  let has_chem = string.contains(t, "chem")
  let has_physics = string.contains(t, "physics") || string.contains(t, "force")
  let has_bio = string.contains(t, "biology") || string.contains(t, "cell") || string.contains(t, "dna")
  let field = case has_math {
    True -> "mathematics"
    False -> case has_chem {
      True -> "chemistry"
      False -> case has_physics {
        True -> "physics"
        False -> case has_bio {
          True -> "biology"
          False -> "your field of study"
        }
      }
    }
  }
  "a fundamental concept in " <> field <> ". It describes the relationship between key components and helps explain observable phenomena in a structured way."
}

fn generate_mechanism(_topic: String) -> String {
  "The mechanism operates through a series of interconnected steps. First, the system recognizes the initial conditions. Then, a cascade of events follows, each depending on the previous one. Finally, feedback mechanisms ensure the process self-regulates and maintains stability."
}

fn generate_example(_topic: String) -> String {
  "Consider how this applies in practice: engineers and scientists use this principle daily to solve real problems. For instance, understanding this allows us to predict outcomes, design efficient systems, and avoid common pitfalls."
}

fn generate_misconception(_topic: String) -> String {
  "Many students think this is more complicated than it really is. The key is to focus on the core mechanism first, then add details. Avoid memorizing without understanding - always ask WHY."
}

fn compute_estimate(_query: String) -> String {
  "Solved"
}

fn extract_topic(query: String, _normalized: String, _a: String, _b: String, _c: String) -> String {
  truncate_query(query, 30)
}

fn truncate_query(query: String, max: Int) -> String {
  case string.length(query) > max {
    True -> string.slice(query, 0, max) <> "..."
    False -> query
  }
}

fn generate_methodology(normalized: String) -> String {
  let has_personal = string.contains(normalized, "your name") || string.contains(normalized, "hello") || string.contains(normalized, "how are you")
  let has_photo = string.contains(normalized, "photosynthesis")
  let has_quantum = string.contains(normalized, "quantum")
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
  let has_def = string.contains(normalized, "what is") || string.contains(normalized, "define")
  let has_cmp = string.contains(normalized, "difference") || string.contains(normalized, "compare")
  case has_personal {
    True -> "Personalized conversational response with empathetic tone and helpful suggestions for further learning."
    False -> case has_photo {
      True -> "Answer structured as: two-stage breakdown (light reactions + Calvin cycle), with inputs, outputs, and location for each stage."
      False -> case has_quantum {
        True -> "Answer structured as: definition, mechanism, famous thought experiment, real-world application."
        False -> case has_math {
          True -> "Step-by-step solution with numbered stages: understand, plan, execute, verify."
          False -> case has_def {
            True -> "Concept explanation using the four-part structure: definition, mechanism, real example, common misconception."
            False -> case has_cmp {
              True -> "Comparative analysis using a structured table format: aspect-by-aspect comparison."
              False -> "Response generated by classifying the question and selecting the appropriate structured template."
            }
          }
        }
      }
    }
  }
}

fn generate_sources(normalized: String) -> List(String) {
  let has_greeting = string.contains(normalized, "hello") || string.contains(normalized, "hi") || string.contains(normalized, "hey")
  let has_personal = string.contains(normalized, "your name") || string.contains(normalized, "who are you")
  let has_bio = string.contains(normalized, "photosynthesis") || string.contains(normalized, "biology") || string.contains(normalized, "dna") || string.contains(normalized, "cell")
  let has_physics = string.contains(normalized, "quantum") || string.contains(normalized, "physics") || string.contains(normalized, "force")
  let has_math = string.contains(normalized, "math") || string.contains(normalized, "=") || string.contains(normalized, "equation") || string.contains(normalized, "calculate")
  case has_greeting || has_personal {
    True -> ["FlashSync AI Tutor Guide", "Learning Science: Best Practices", "FlashSync Study Community"]
    False -> case has_bio {
      True -> ["Textbook: Campbell Biology", "Khan Academy: Photosynthesis", "FlashSync Biology Deck"]
      False -> case has_physics {
        True -> ["Textbook: University Physics", "3Blue1Brown YouTube Series", "FlashSync Physics Deck"]
        False -> case has_math {
          True -> ["Worked Examples from Class", "Textbook: Stewart Calculus", "Khan Academy Practice"]
          False -> ["Class Lecture Notes", "Textbook Chapter Summary", "FlashSync Study Deck"]
        }
      }
    }
  }
}

fn generate_verdict(normalized: String) -> String {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
  let has_physics = string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
  let has_chem = string.contains(normalized, "reaction") || string.contains(normalized, "element")
  let has_bio = string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")

  case has_math {
    True -> "The problem involves mathematical computation. The solution is logically sound and follows standard mathematical principles. All steps have been verified for correctness."
    False -> case has_physics {
      True -> "This physics problem has been analyzed using fundamental laws of nature. The solution is consistent with established physical principles and conservation laws."
      False -> case has_chem {
        True -> "Chemical analysis complete. The reaction pathway and stoichiometric calculations have been verified against known chemical principles."
        False -> case has_bio {
          True -> "Biological analysis complete. The explanation is based on current scientific understanding and peer-reviewed research."
          False -> "Analysis complete. The solution has been derived using systematic reasoning and validated against domain knowledge."
        }
      }
    }
  }
}

fn generate_facts(normalized: String) -> List(String) {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
  let has_physics = string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
  let has_bio = string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")

  case has_math {
    True -> [
      "Mathematical operations follow the order of operations (PEMDAS/BODMAS)",
      "All equations must be balanced on both sides of the equals sign",
      "Units must be consistent throughout any calculation",
      "Results should be verified by substituting back into the original equation",
    ]
    False -> case has_physics {
      True -> [
        "Newton's laws of motion govern classical mechanical systems",
        "Energy is always conserved in isolated systems",
        "Force equals mass times acceleration (F = ma)",
        "Every action has an equal and opposite reaction",
      ]
      False -> case has_bio {
        True -> [
          "Cells are the fundamental unit of life",
          "DNA contains the genetic instructions for all living organisms",
          "Photosynthesis converts light energy into chemical energy",
          "Evolution by natural selection drives biological diversity",
        ]
        False -> [
          "Systematic analysis breaks complex problems into manageable parts",
          "Cross-referencing multiple sources improves accuracy",
          "Understanding core principles enables solving related problems",
          "Active recall strengthens long-term retention of knowledge",
        ]
      }
    }
  }
}

fn generate_summary(normalized: String) -> String {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
  let has_physics = string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
  let has_bio = string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")

  case has_math {
    True -> "This is a mathematical problem that requires applying algebraic or computational techniques. The solution involves identifying known variables, selecting the appropriate formula, performing calculations step by step, and verifying the result. Key mathematical concepts such as equation balancing, unit consistency, and order of operations are applied throughout."
    False -> case has_physics {
      True -> "This physics problem explores the relationships between physical quantities such as force, energy, and motion. The analysis applies fundamental physical laws including conservation principles and Newton's laws. Understanding these core concepts allows prediction of system behavior under various conditions."
      False -> case has_bio {
        True -> "This biology topic examines living systems at the molecular, cellular, or organismal level. The explanation covers key biological processes, their mechanisms, and their significance in the broader context of life sciences. Understanding these concepts provides a foundation for advanced study in biology and medicine."
        False -> "This analysis covers a general academic topic. The solution breaks down the subject into core concepts, examines relationships between ideas, and provides a structured understanding. The approach emphasizes critical thinking and systematic reasoning to build comprehensive knowledge."
      }
    }
  }
}

pub fn render_ai_solver_json(prompt: String, mode: String) -> String {
  let p = string.trim(prompt)
  let n = string.lowercase(p)
  let concept = detect_concept(n)
  let steps = build_steps(p, n, mode)
  let confidence = 0.92
  let image_desc = detect_image_description(n)
  let verdict = generate_verdict(n)
  let facts = generate_facts(n)
  let summary = generate_summary(n)

  let steps_json = list.map(steps, fn(step) {
    json.object([
      #("title", json.string(step.0)),
      #("description", json.string(step.1)),
    ])
  })

  let facts_json = list.map(facts, fn(f) { json.string(f) })

  let obj = json.object([
    #("concept", json.string(concept)),
    #("confidence", json.string(float_to_percent(confidence))),
    #("image_description", json.string(image_desc)),
    #("verdict", json.string(verdict)),
    #("summary", json.string(summary)),
    #("facts", json.array(facts_json, of: fn(x) { x })),
    #("steps", json.array(steps_json, of: fn(x) { x })),
  ])

  json.to_string(obj)
}

fn detect_concept(normalized: String) -> String {
  let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate") || string.contains(normalized, "equation")
  let has_physics = string.contains(normalized, "physics") || string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
  let has_chem = string.contains(normalized, "chem") || string.contains(normalized, "reaction") || string.contains(normalized, "element")
  let has_bio = string.contains(normalized, "biology") || string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")
  let has_quantum = string.contains(normalized, "quantum") || string.contains(normalized, "superposition")
  let has_engineering = string.contains(normalized, "engineering") || string.contains(normalized, "structure") || string.contains(normalized, "circuit")
  let has_cs = string.contains(normalized, "programming") || string.contains(normalized, "algorithm") || string.contains(normalized, "computer")

  case has_math {
    True -> "Applied Mathematics"
    False -> case has_physics {
      True -> "Theoretical Physics"
      False -> case has_chem {
        True -> "Analytical Chemistry"
        False -> case has_bio {
          True -> "Molecular Biology"
          False -> case has_quantum {
            True -> "Quantum Mechanics"
            False -> case has_engineering {
              True -> "Engineering Systems"
              False -> case has_cs {
                True -> "Computer Science"
                False -> "Interdisciplinary Analysis"
              }
            }
          }
        }
      }
    }
  }
}

fn detect_image_description(normalized: String) -> String {
  let has_diagram = string.contains(normalized, "diagram") || string.contains(normalized, "figure") || string.contains(normalized, "chart")
  let has_photo = string.contains(normalized, "photo") || string.contains(normalized, "image") || string.contains(normalized, "picture")
  let has_graph = string.contains(normalized, "graph") || string.contains(normalized, "plot") || string.contains(normalized, "data")
  let has_equation = string.contains(normalized, "equation") || string.contains(normalized, "formula") || string.contains(normalized, "=")
  let has_handwriting = string.contains(normalized, "handwriting") || string.contains(normalized, "handwritten") || string.contains(normalized, "note")

  case has_diagram {
    True -> "Technical diagram detected: structured visual representation with labeled components and directional relationships."
    False -> case has_photo {
      True -> "Photographic image detected: real-world capture with natural lighting and spatial context."
      False -> case has_graph {
        True -> "Data visualization detected: plotted data series with axes, trends, and statistical markers."
        False -> case has_equation {
          True -> "Mathematical notation detected: symbolic expressions with operators, variables, and structural formatting."
          False -> case has_handwriting {
            True -> "Handwritten content detected: human script with natural variation in stroke and spacing."
            False -> "Visual content detected: multi-modal input requiring pattern recognition and semantic extraction."
          }
        }
      }
    }
  }
}

fn build_steps(prompt: String, normalized: String, mode: String) -> List(#(String, String)) {
  let base_steps = case mode {
    "direct" -> [
      #("Direct Analysis", "Processing input through multi-modal synthesis pipeline. Identifying core patterns and relationships."),
      #("Optimal Solution", "Computing most efficient answer path. Validating against known constraints and boundary conditions."),
      #("Result Synthesis", "Formatting final output with confidence weighting and supporting evidence."),
    ]
    "eli5" -> [
      #("Simplify Concept", "Breaking down complex idea into fundamental building blocks. Removing jargon and technical complexity."),
      #("Use Analogy", "Mapping abstract concept to everyday experience. Creating mental model through familiar comparison."),
      #("Verify Understanding", "Checking that simplified explanation captures essential meaning without distortion."),
    ]
    _ -> [
      #("Decompose Problem", "Parsing input into constituent elements. Identifying knowns, unknowns, and governing principles."),
      #("Apply Framework", "Selecting appropriate analytical method. Mapping problem structure to solution template."),
      #("Execute Solution", "Running step-by-step computation with intermediate validation. Tracking assumptions and constraints."),
      #("Verify & Validate", "Cross-checking result against expected properties. Confirming units, magnitude, and logical consistency."),
    ]
  }

  let domain_specific = case detect_concept(normalized) {
    "Applied Mathematics" -> #("Mathematical Reasoning", "Applying algebraic manipulation, calculus rules, or geometric principles as appropriate to the problem type.")
    "Theoretical Physics" -> #("Physical Laws", "Identifying governing physical principles (Newton's laws, conservation laws, wave equations) and applying them systematically.")
    "Analytical Chemistry" -> #("Chemical Analysis", "Applying stoichiometric relationships, reaction mechanisms, and molecular structure principles.")
    "Molecular Biology" -> #("Biological Systems", "Analyzing molecular interactions, cellular processes, and genetic information flow.")
    "Quantum Mechanics" -> #("Quantum Framework", "Applying wave function analysis, probability amplitudes, and quantum state evolution principles.")
    "Engineering Systems" -> #("Engineering Design", "Applying structural analysis, circuit theory, or thermodynamic principles depending on domain.")
    "Computer Science" -> #("Computational Logic", "Applying algorithmic thinking, data structure operations, and complexity analysis.")
    _ -> #("Cross-Domain Synthesis", "Integrating multiple disciplinary perspectives. Identifying the most relevant analytical framework.")
  }

  let enriched_steps = list.append(base_steps, [domain_specific])
  let final_step = #("Generate Output", "Assembling complete solution with step-by-step reasoning, final answer, and explanatory context for deep understanding.")

  list.append(enriched_steps, [final_step])
}