File size: 45,343 Bytes
00e4c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FinWise โ€” AI Insights</title>
<link rel="stylesheet" href="shared.css">
<style>
/* โ”€โ”€ AI Chat Interface โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
.ai-chat-wrap {
  display: flex;
  flex-direction: column;
  height: 420px;
  background: var(--bg2);
  border: 1px solid var(--border);
  border-radius: var(--r);
  overflow: hidden;
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
}
.chat-message {
  display: flex;
  gap: 10px;
  max-width: 90%;
  animation: fadeInUp 0.3s ease;
}
.chat-message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}
.chat-avatar {
  width: 32px; height: 32px;
  border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
  align-self: flex-end;
}
.chat-avatar.ai-av   { background: linear-gradient(135deg, var(--cyan), var(--emerald)); }
.chat-avatar.user-av { background: linear-gradient(135deg, var(--violet), var(--indigo)); }
.chat-bubble {
  padding: 12px 16px;
  border-radius: 14px;
  font-size: 14px;
  line-height: 1.6;
  max-width: 100%;
}
.chat-bubble.ai   { background: var(--card); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
.chat-bubble.user { background: linear-gradient(135deg,var(--cyan-d),var(--cyan)); color: var(--bg); border-bottom-right-radius: 4px; }
.chat-bubble.ai strong { color: var(--cyan); }
.chat-bubble.ai em { color: var(--emerald); font-style: normal; font-weight: 600; }
.chat-bubble ul { padding-left: 18px; margin-top: 6px; }
.chat-bubble li { margin-bottom: 4px; }

.chat-typing {
  display: flex;
  gap: 4px;
  padding: 14px 16px;
  background: var(--card);
  border: 1px solid var(--border);
  border-radius: 14px;
  border-bottom-left-radius: 4px;
  width: fit-content;
}
.chat-typing span {
  width: 7px; height: 7px;
  border-radius: 50%;
  background: var(--cyan);
  animation: typing 1.2s infinite;
}
.chat-typing span:nth-child(2) { animation-delay: 0.2s; }
.chat-typing span:nth-child(3) { animation-delay: 0.4s; }
@keyframes typing { 0%,100%{opacity:0.3;transform:scale(0.8)} 50%{opacity:1;transform:scale(1)} }

.chat-input-bar {
  border-top: 1px solid var(--border);
  padding: 12px 16px;
  display: flex;
  gap: 10px;
  background: var(--bg2);
}
.chat-input {
  flex: 1;
  background: var(--bg3);
  border: 1px solid var(--border);
  border-radius: 100px;
  padding: 10px 18px;
  color: var(--text);
  font-family: var(--font-body);
  font-size: 14px;
  outline: none;
  transition: border-color var(--transition);
  width: auto;
}
.chat-input:focus { border-color: var(--cyan); }
.chat-send-btn {
  width: 42px; height: 42px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--cyan-d), var(--cyan));
  border: none;
  cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  font-size: 18px;
  transition: all var(--transition);
  flex-shrink: 0;
}
.chat-send-btn:hover { box-shadow: 0 0 16px rgba(34,211,238,0.5); transform: scale(1.05); }
.chat-send-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

.quick-prompts {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  padding: 10px 16px;
  border-top: 1px solid var(--border);
  background: var(--bg2);
}
.quick-prompt {
  padding: 6px 12px;
  border-radius: 100px;
  border: 1px solid var(--border2);
  background: transparent;
  color: var(--text2);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  font-family: var(--font-body);
  transition: all var(--transition);
  white-space: nowrap;
}
.quick-prompt:hover { border-color: var(--cyan); color: var(--cyan); background: rgba(34,211,238,0.06); }

/* โ”€โ”€ Concept Cards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
.concept-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}
.concept-card {
  background: var(--card);
  border: 1px solid var(--border);
  border-radius: var(--r);
  padding: 20px;
  transition: all var(--transition);
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.concept-card::before {
  content: '';
  position: absolute;
  top: 0; left: 0; right: 0;
  height: 2px;
  background: var(--concept-color, var(--cyan));
}
.concept-card:hover {
  border-color: var(--border2);
  transform: translateY(-3px);
  box-shadow: 0 8px 30px rgba(0,0,0,0.4);
}
.concept-icon  { font-size: 32px; margin-bottom: 10px; }
.concept-title { font-family: var(--font-head); font-size: 16px; font-weight: 700; margin-bottom: 6px; }
.concept-desc  { font-size: 13px; color: var(--text2); line-height: 1.5; }
.concept-tag   { margin-top: 12px; }

/* โ”€โ”€ Do's & Don'ts โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
.dos-donts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}
.do-card {
  background: rgba(16,185,129,0.05);
  border: 1px solid rgba(16,185,129,0.2);
  border-radius: var(--r);
  padding: 20px;
}
.dont-card {
  background: rgba(244,63,94,0.05);
  border: 1px solid rgba(244,63,94,0.2);
  border-radius: var(--r);
  padding: 20px;
}
.do-header   { font-family: var(--font-head); font-size: 16px; font-weight: 800; color: var(--emerald); margin-bottom: 14px; }
.dont-header { font-family: var(--font-head); font-size: 16px; font-weight: 800; color: var(--rose);    margin-bottom: 14px; }
.tip-item {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  font-size: 13px;
  line-height: 1.5;
}
.tip-icon { flex-shrink: 0; font-size: 16px; margin-top: 1px; }

/* โ”€โ”€ Insight Cards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
.insight-feed { display: flex; flex-direction: column; gap: 14px; }
.insight-item {
  display: flex;
  gap: 14px;
  padding: 16px;
  background: var(--card);
  border: 1px solid var(--border);
  border-radius: var(--r-sm);
  transition: all var(--transition);
}
.insight-item:hover { border-color: var(--border2); }
.insight-category {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 10px;
  font-weight: 800;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  margin-bottom: 6px;
}
.insight-title { font-weight: 700; font-size: 14px; margin-bottom: 5px; }
.insight-body  { font-size: 13px; color: var(--text2); line-height: 1.5; }

/* โ”€โ”€ Glossary โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
.glossary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px,1fr));
  gap: 12px;
}
.glossary-item {
  background: var(--bg3);
  border-radius: var(--r-sm);
  padding: 14px;
  border: 1px solid var(--border);
}
.glos-term { font-weight: 700; color: var(--cyan); margin-bottom: 4px; font-size: 14px; }
.glos-def  { font-size: 12px; color: var(--text2); line-height: 1.5; }

/* โ”€โ”€ Tabs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */
.insight-tabs {
  display: flex;
  gap: 6px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}
.ins-tab {
  padding: 9px 18px;
  border-radius: 100px;
  border: 1px solid var(--border);
  background: transparent;
  color: var(--text2);
  font-family: var(--font-body);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all var(--transition);
}
.ins-tab:hover { border-color: var(--border2); color: var(--text); }
.ins-tab.active { border-color: var(--cyan); background: rgba(34,211,238,0.1); color: var(--cyan); }

.ins-panel { display: none; }
.ins-panel.active { display: block; }

.gamification-bar {
  background: linear-gradient(135deg, rgba(139,92,246,0.1), rgba(34,211,238,0.05));
  border: 1px solid rgba(139,92,246,0.2);
  border-radius: var(--r);
  padding: 20px 24px;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
}
.xp-badge {
  background: linear-gradient(135deg, var(--violet), var(--indigo));
  border-radius: var(--r-sm);
  padding: 14px;
  text-align: center;
  min-width: 80px;
}
.xp-val { font-family: var(--font-head); font-size: 22px; font-weight: 800; }
.xp-lbl { font-size: 10px; text-transform: uppercase; letter-spacing: 0.1em; opacity: 0.8; }
.level-info { flex: 1; }
.level-name { font-family: var(--font-head); font-size: 18px; font-weight: 700; margin-bottom: 4px; }
.achievements {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 12px;
}
.achievement {
  background: var(--bg3);
  border-radius: var(--r-sm);
  padding: 8px 12px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  border: 1px solid var(--border);
}
.achievement.earned { border-color: rgba(245,158,11,0.4); background: rgba(245,158,11,0.08); }
</style>
</head>
<body>
<div class="app-shell">
  <nav class="sidebar">
    <div class="sidebar-logo">
      <div class="logo-mark">
        <div class="logo-icon">๐Ÿ“ˆ</div>
        <div><div class="logo-text">FinWise</div><div class="logo-sub">Smart Investing</div></div>
      </div>
    </div>
    <div class="nav-section">
      <div class="nav-label">Main</div>
      <a href="index.html"       class="nav-item"><span class="nav-icon">๐Ÿ </span> Dashboard</a>
      <a href="portfolio.html"   class="nav-item"><span class="nav-icon">๐Ÿ“Š</span> Portfolio Builder</a>
      <a href="risk.html"        class="nav-item"><span class="nav-icon">๐ŸŽฏ</span> Risk Analyzer</a>
      <a href="tracker.html"     class="nav-item"><span class="nav-icon">๐Ÿ“ˆ</span> Tracker</a>
      <div class="nav-label">Tools</div>
      <a href="calculators.html" class="nav-item"><span class="nav-icon">๐Ÿงฎ</span> Calculators</a>
      <a href="insights.html"    class="nav-item"><span class="nav-icon">๐Ÿ’ก</span> Insights <span class="nav-badge">New</span></a>
    </div>
    <div class="sidebar-footer">
      <div class="market-ticker">Live Market</div>
      <div id="sidebar-tickers"></div>
    </div>
  </nav>

  <main class="main-content">
    <div class="page-header fade-in">
      <div class="page-title">AI <span>Insights</span></div>
      <div class="page-subtitle">Personalized guidance, education, and smart financial tips powered by AI</div>
    </div>

    <!-- Gamification Bar -->
    <div class="gamification-bar fade-in">
      <div class="xp-badge">
        <div class="xp-val">340</div>
        <div class="xp-lbl">XP Points</div>
      </div>
      <div class="level-info">
        <div class="level-name">๐ŸŒฑ Growing Investor โ€” Level 4</div>
        <div class="text-muted text-sm">160 XP until Level 5: Savvy Saver</div>
        <div class="progress-bar" style="margin-top:8px">
          <div class="progress-fill" style="width:68%;background:linear-gradient(90deg,var(--violet),var(--cyan))"></div>
        </div>
        <div class="achievements">
          <div class="achievement earned">๐Ÿ† First Portfolio</div>
          <div class="achievement earned">๐Ÿ“Š Risk Assessed</div>
          <div class="achievement earned">๐Ÿงฎ Calc Explorer</div>
          <div class="achievement" style="opacity:0.5">๐ŸŽฏ Goal Setter</div>
          <div class="achievement" style="opacity:0.5">๐Ÿ’ฐ $10K Milestone</div>
        </div>
      </div>
    </div>

    <!-- Tab Nav -->
    <div class="insight-tabs fade-in">
      <button class="ins-tab active" data-ins="ai-chat">๐Ÿค– AI Advisor</button>
      <button class="ins-tab" data-ins="daily">๐Ÿ’ก Daily Insights</button>
      <button class="ins-tab" data-ins="concepts">๐Ÿ“š Concepts</button>
      <button class="ins-tab" data-ins="dos-donts">โœ… Do's & Don'ts</button>
      <button class="ins-tab" data-ins="glossary">๐Ÿ“– Glossary</button>
    </div>

    <!-- โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
         AI ADVISOR TAB
    โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• -->
    <div class="ins-panel active fade-in" id="ins-ai-chat">
      <div class="grid-60-40">
        <div>
          <div class="card" style="padding:0;overflow:hidden">
            <div style="padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px">
              <div style="width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,var(--cyan),var(--emerald));display:flex;align-items:center;justify-content:center;font-size:18px">๐Ÿค–</div>
              <div>
                <div style="font-weight:700;font-size:15px">FinWise AI</div>
                <div style="font-size:12px;color:var(--emerald)">โ— Online ยท Powered by Claude</div>
              </div>
              <div style="margin-left:auto">
                <span class="badge badge-cyan">Beta</span>
              </div>
            </div>
            <div class="ai-chat-wrap" style="border:none;border-radius:0;height:380px">
              <div class="chat-messages" id="chat-messages">
                <!-- Initial message -->
                <div class="chat-message">
                  <div class="chat-avatar ai-av">๐Ÿค–</div>
                  <div class="chat-bubble ai">
                    <strong>Hey there, investor! ๐Ÿ‘‹</strong><br><br>
                    I'm your AI financial advisor. I can help you understand your portfolio, explain investing concepts, and give personalized guidance based on your goals.<br><br>
                    <em>What would you like to explore today?</em>
                  </div>
                </div>
              </div>
              <div class="quick-prompts">
                <button class="quick-prompt" onclick="sendQuickPrompt(this)">๐Ÿ“Š Analyze my portfolio</button>
                <button class="quick-prompt" onclick="sendQuickPrompt(this)">๐ŸŽฏ Am I taking too much risk?</button>
                <button class="quick-prompt" onclick="sendQuickPrompt(this)">๐Ÿ’ก How do ETFs work?</button>
                <button class="quick-prompt" onclick="sendQuickPrompt(this)">๐Ÿ–๏ธ Retirement planning tips</button>
                <button class="quick-prompt" onclick="sendQuickPrompt(this)">๐Ÿ“ˆ What is dollar-cost averaging?</button>
                <button class="quick-prompt" onclick="sendQuickPrompt(this)">โšก Should I rebalance now?</button>
              </div>
              <div class="chat-input-bar">
                <input type="text" class="chat-input" id="chat-input" placeholder="Ask me anything about investingโ€ฆ" onkeydown="if(event.key==='Enter')sendMessage()">
                <button class="chat-send-btn" id="send-btn" onclick="sendMessage()">โžค</button>
              </div>
            </div>
          </div>
        </div>

        <!-- Sidebar topics -->
        <div>
          <div class="card">
            <div class="card-title">๐Ÿ“Œ Suggested Topics</div>
            <div class="insight-feed">
              <div class="insight-item" style="cursor:pointer" onclick="sendText('What is compound interest and why is it important?')">
                <div>
                  <div class="insight-category" style="color:var(--cyan)">๐ŸŽ“ Education</div>
                  <div class="insight-title">The Magic of Compound Interest</div>
                  <div class="insight-body">Why time in market beats timing the market</div>
                </div>
              </div>
              <div class="insight-item" style="cursor:pointer" onclick="sendText('Explain the 4% rule for retirement withdrawals')">
                <div>
                  <div class="insight-category" style="color:var(--emerald)">๐Ÿ–๏ธ Retirement</div>
                  <div class="insight-title">The 4% Withdrawal Rule</div>
                  <div class="insight-body">How much you can safely spend in retirement</div>
                </div>
              </div>
              <div class="insight-item" style="cursor:pointer" onclick="sendText('What is portfolio rebalancing and when should I do it?')">
                <div>
                  <div class="insight-category" style="color:var(--violet)">โš–๏ธ Strategy</div>
                  <div class="insight-title">When to Rebalance</div>
                  <div class="insight-body">Keep your risk in check automatically</div>
                </div>
              </div>
              <div class="insight-item" style="cursor:pointer" onclick="sendText('What is the difference between ETFs and mutual funds?')">
                <div>
                  <div class="insight-category" style="color:var(--amber)">๐Ÿ“Š Basics</div>
                  <div class="insight-title">ETFs vs Mutual Funds</div>
                  <div class="insight-body">Which is better for beginner investors?</div>
                </div>
              </div>
            </div>
          </div>

          <!-- AI context card -->
          <div class="card" style="margin-top:16px;background:linear-gradient(135deg,rgba(34,211,238,0.06),rgba(16,185,129,0.03))">
            <div class="card-title">๐Ÿ“Š Your Portfolio Context</div>
            <div id="context-summary" style="font-size:13px;color:var(--text2);line-height:1.6"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
         DAILY INSIGHTS TAB
    โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• -->
    <div class="ins-panel" id="ins-daily">
      <div class="insight-feed">
        <div class="insight-item">
          <div style="font-size:36px">๐ŸŒ…</div>
          <div>
            <div class="insight-category badge-cyan">Daily Tip</div>
            <div class="insight-title">Automate Your Investments</div>
            <div class="insight-body">Set up automatic monthly contributions โ€” even $100/month invested consistently can grow to over $200,000 in 30 years at a 10% return. Automation removes emotion from the equation and builds the habit effortlessly.</div>
          </div>
        </div>
        <div class="insight-item">
          <div style="font-size:36px">๐Ÿ“ฐ</div>
          <div>
            <div class="insight-category badge-amber">Market Insight</div>
            <div class="insight-title">Fed Policy & Your Bonds</div>
            <div class="insight-body">When interest rates rise, bond prices fall. If you're holding BND or similar ETFs in your portfolio, rising rates reduce their short-term value โ€” but also mean higher yields going forward. Long-term investors should stay the course.</div>
          </div>
        </div>
        <div class="insight-item">
          <div style="font-size:36px">โšก</div>
          <div>
            <div class="insight-category badge-emerald">Action Item</div>
            <div class="insight-title">Review Your Emergency Fund First</div>
            <div class="insight-body">Before investing more, ensure you have 3-6 months of expenses in a high-yield savings account (HYSA). With rates above 4.5% APY at some banks, your emergency fund can earn real money while staying liquid.</div>
          </div>
        </div>
        <div class="insight-item">
          <div style="font-size:36px">๐Ÿง </div>
          <div>
            <div class="insight-category badge-violet">Behavioral Finance</div>
            <div class="insight-title">Don't Check Your Portfolio Daily</div>
            <div class="insight-body">Studies show that investors who check their portfolios more often make more emotional trades and achieve worse returns. Set a calendar reminder to review quarterly โ€” not daily. Your future self will thank you.</div>
          </div>
        </div>
        <div class="insight-item">
          <div style="font-size:36px">๐Ÿ’ก</div>
          <div>
            <div class="insight-category badge-rose">Watch Out For</div>
            <div class="insight-title">Expense Ratios Add Up</div>
            <div class="insight-body">A fund with 1% expense ratio vs 0.03% (like VOO) costs you over $250,000 on a $100K investment over 30 years. Always compare expense ratios before buying mutual funds or ETFs.</div>
          </div>
        </div>
      </div>
    </div>

    <!-- โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
         CONCEPTS TAB
    โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• -->
    <div class="ins-panel" id="ins-concepts">
      <div class="concept-grid">
        <div class="concept-card" style="--concept-color:var(--cyan)" onclick="sendText('Explain compound interest with a real example')">
          <div class="concept-icon">โšก</div>
          <div class="concept-title">Compound Interest</div>
          <div class="concept-desc">The 8th wonder of the world โ€” earning interest on your interest. Time is your greatest asset.</div>
          <div class="concept-tag"><span class="badge badge-cyan">Beginner</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--emerald)" onclick="sendText('What is dollar-cost averaging and how do I use it?')">
          <div class="concept-icon">๐Ÿ“…</div>
          <div class="concept-title">Dollar-Cost Averaging</div>
          <div class="concept-desc">Invest a fixed amount regularly regardless of price. Reduces the impact of volatility automatically.</div>
          <div class="concept-tag"><span class="badge badge-emerald">Strategy</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--violet)" onclick="sendText('Explain diversification and why it matters')">
          <div class="concept-icon">๐ŸŒ</div>
          <div class="concept-title">Diversification</div>
          <div class="concept-desc">Don't put all your eggs in one basket. Spreading across assets reduces risk without sacrificing returns.</div>
          <div class="concept-tag"><span class="badge badge-violet">Risk Management</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--amber)" onclick="sendText('What is asset allocation and how should I allocate my portfolio?')">
          <div class="concept-icon">๐Ÿฅง</div>
          <div class="concept-title">Asset Allocation</div>
          <div class="concept-desc">How you divide money between stocks, bonds, and other assets. The most important investment decision you'll make.</div>
          <div class="concept-tag"><span class="badge badge-amber">Portfolio</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--rose)" onclick="sendText('What is beta in investing and what does it tell me?')">
          <div class="concept-icon">ฮฒ</div>
          <div class="concept-title">Beta & Volatility</div>
          <div class="concept-desc">Beta measures how much an asset moves relative to the market. A beta of 1.5 means 50% more volatile than S&P 500.</div>
          <div class="concept-tag"><span class="badge badge-rose">Metrics</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--indigo)" onclick="sendText('What is an index fund and why do most pros recommend it?')">
          <div class="concept-icon">๐Ÿ“Š</div>
          <div class="concept-title">Index Funds</div>
          <div class="concept-desc">Passively track a market index like the S&P 500. Low cost, diversified, and statistically outperform most active funds.</div>
          <div class="concept-tag"><span class="badge badge-cyan">Beginner</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--emerald)" onclick="sendText('Explain the 4% rule for retirement')">
          <div class="concept-icon">๐Ÿ–๏ธ</div>
          <div class="concept-title">The 4% Rule</div>
          <div class="concept-desc">Withdraw 4% of your nest egg annually in retirement. Based on 95% survival rate across 30-year historical periods.</div>
          <div class="concept-tag"><span class="badge badge-emerald">Retirement</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--cyan)" onclick="sendText('What is rebalancing and when should I rebalance my portfolio?')">
          <div class="concept-icon">โš–๏ธ</div>
          <div class="concept-title">Rebalancing</div>
          <div class="concept-desc">Selling overweight assets and buying underweight ones to restore your target allocation. Do it annually or at 5% drift.</div>
          <div class="concept-tag"><span class="badge badge-cyan">Strategy</span></div>
        </div>
        <div class="concept-card" style="--concept-color:var(--amber)" onclick="sendText('What is expense ratio and how does it affect my returns?')">
          <div class="concept-icon">๐Ÿ’ธ</div>
          <div class="concept-title">Expense Ratios</div>
          <div class="concept-desc">The annual fee funds charge as % of your investment. Even 0.5% more can cost $100K+ over 30 years.</div>
          <div class="concept-tag"><span class="badge badge-amber">Cost</span></div>
        </div>
      </div>
    </div>

    <!-- โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
         DO'S & DON'TS TAB
    โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• -->
    <div class="ins-panel" id="ins-dos-donts">
      <div class="dos-donts">
        <div class="do-card">
          <div class="do-header">โœ… Do This</div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ•ฐ๏ธ</div><div><strong>Start early</strong> โ€” Even $50/month at 22 beats $500/month starting at 40. Time is your biggest multiplier.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ“…</div><div><strong>Automate contributions</strong> โ€” Set it and forget it. Remove emotion and ensure consistency every month.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ“Š</div><div><strong>Keep expense ratios low</strong> โ€” Choose ETFs like VOO (0.03%) over actively managed funds (1%+).</div></div>
          <div class="tip-item"><div class="tip-icon">๐ŸŒ</div><div><strong>Diversify broadly</strong> โ€” No single stock should exceed 10% of your portfolio when starting out.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ’ฐ</div><div><strong>Max out tax-advantaged accounts</strong> โ€” 401k, Roth IRA, or HSA first before taxable accounts.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ›ก๏ธ</div><div><strong>Maintain an emergency fund</strong> โ€” 3โ€“6 months of expenses in cash before investing aggressively.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ“š</div><div><strong>Keep learning</strong> โ€” Read one finance book a year. Try "The Little Book of Common Sense Investing" by Bogle.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ“†</div><div><strong>Review quarterly</strong> โ€” Check your portfolio every 3 months, not every day. Avoid reaction trading.</div></div>
        </div>
        <div class="dont-card">
          <div class="dont-header">โŒ Don't Do This</div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ“ฐ</div><div><strong>Don't invest based on news</strong> โ€” By the time it's news, the market has already priced it in. Stay the course.</div></div>
          <div class="tip-item"><div class="tip-icon">๐ŸŽฒ</div><div><strong>Don't YOLO into meme stocks</strong> โ€” Treat speculative picks as entertainment money โ€” never more than 5% of portfolio.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ˜ฑ</div><div><strong>Don't panic sell in crashes</strong> โ€” Market drops of 20โ€“40% are normal and temporary. Selling locks in your loss permanently.</div></div>
          <div class="tip-item"><div class="tip-icon">โฐ</div><div><strong>Don't try to time the market</strong> โ€” Missing the 10 best days in the market over 20 years can cut your returns in half.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ’ณ</div><div><strong>Don't invest money you need soon</strong> โ€” Any money needed within 3 years should be in a HYSA, not the market.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿค™</div><div><strong>Don't take tips from social media</strong> โ€” Most "finfluencers" are not licensed advisors. Verify everything independently.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿฆ</div><div><strong>Don't ignore fees</strong> โ€” Trading commissions, fund fees, and advisory fees compound over time just like returns do โ€” negatively.</div></div>
          <div class="tip-item"><div class="tip-icon">๐Ÿ”ฎ</div><div><strong>Don't predict the market</strong> โ€” Even professional fund managers fail to consistently beat the index. Humility pays.</div></div>
        </div>
      </div>
    </div>

    <!-- โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
         GLOSSARY TAB
    โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• -->
    <div class="ins-panel" id="ins-glossary">
      <div style="margin-bottom:16px">
        <input type="text" id="glossary-search" placeholder="๐Ÿ” Search termsโ€ฆ" oninput="filterGlossary()" style="max-width:320px">
      </div>
      <div class="glossary-grid" id="glossary-grid"></div>
    </div>

  </main>
</div>

<nav class="bottom-nav">
  <div class="bottom-nav-inner">
    <a href="index.html"       class="bottom-nav-item"><span class="bnav-icon">๐Ÿ </span>Home</a>
    <a href="portfolio.html"   class="bottom-nav-item"><span class="bnav-icon">๐Ÿ“Š</span>Portfolio</a>
    <a href="risk.html"        class="bottom-nav-item"><span class="bnav-icon">๐ŸŽฏ</span>Risk</a>
    <a href="tracker.html"     class="bottom-nav-item"><span class="bnav-icon">๐Ÿ“ˆ</span>Track</a>
    <a href="calculators.html" class="bottom-nav-item"><span class="bnav-icon">๐Ÿงฎ</span>Calc</a>
    <a href="insights.html"    class="bottom-nav-item"><span class="bnav-icon">๐Ÿ’ก</span>Insights</a>
  </div>
</nav>

<script src="shared.js"></script>
<script>
// โ”€โ”€ Tab Switching โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
document.querySelectorAll('.ins-tab').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.ins-tab,.ins-panel').forEach(el => el.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('ins-' + btn.dataset.ins).classList.add('active');
  });
});

// โ”€โ”€ Portfolio Context Summary โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function buildContextSummary() {
  const p = getPortfolio();
  const totalVal = p.assets.reduce((s,a)=>s+a.shares*a.price,0);
  const riskScore = calcRiskScore(p);
  const divScore  = calcDiversification(p);
  const equityPct = p.assets.filter(a=>a.type==='Stock'||a.type==='ETF').reduce((s,a)=>s+a.pct,0);
  document.getElementById('context-summary').innerHTML = `
    <div style="display:flex;flex-direction:column;gap:6px">
      <div>๐Ÿ’ผ <strong>${p.assets.length} holdings</strong> ยท Total: <strong>${fmt$(totalVal)}</strong></div>
      <div>๐ŸŽฏ Risk Score: <strong style="color:var(--amber)">${riskScore}/100</strong> ยท Profile: <strong>${p.riskProfile||'Moderate'}</strong></div>
      <div>๐ŸŒ Diversification: <strong style="color:var(--emerald)">${divScore}/100</strong></div>
      <div>๐Ÿ“Š Equity: <strong>${equityPct}%</strong> ยท Goals: <strong>${(p.goals||['Wealth Building']).join(', ')}</strong></div>
    </div>
  `;
}

// โ”€โ”€ AI Chat โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
let chatHistory = [];
let isLoading   = false;

function buildSystemPrompt() {
  const p = getPortfolio();
  const totalVal = p.assets.reduce((s,a)=>s+a.shares*(MARKET_PRICES[a.ticker]?.price||a.price),0);
  const riskScore = calcRiskScore(p);
  const divScore  = calcDiversification(p);
  const equityPct = p.assets.filter(a=>a.type==='Stock'||a.type==='ETF').reduce((s,a)=>s+a.pct,0);
  const bondPct   = p.assets.filter(a=>a.type==='Bond').reduce((s,a)=>s+a.pct,0);

  return `You are FinWise AI, a friendly, expert financial advisor built into the FinWise personal finance app.

USER'S PORTFOLIO CONTEXT:
- Holdings: ${p.assets.map(a=>`${a.ticker} (${a.pct}%)`).join(', ')}
- Total Value: $${totalVal.toFixed(2)}
- Total Invested: $${p.totalInvested}
- Risk Score: ${riskScore}/100 (${p.riskProfile || 'Moderate'})
- Diversification Score: ${divScore}/100
- Equity Allocation: ${equityPct}%
- Bond Allocation: ${bondPct}%
- Investment Goals: ${(p.goals||['Wealth Building']).join(', ')}

PERSONA:
- Friendly, warm, encouraging โ€” never condescending
- Use simple language; avoid jargon (or explain it when necessary)
- Be direct and actionable โ€” give concrete advice, not just generic platitudes
- Use bullet points and bold text for clarity
- Add relevant emojis to make responses engaging
- Be concise but complete โ€” aim for 100-200 words per response
- Always note: you're an AI, not a licensed financial advisor

FOCUS: Help beginners understand investing. Provide personalized insights based on their actual portfolio above.`;
}

async function sendMessage() {
  const input = document.getElementById('chat-input');
  const msg = input.value.trim();
  if (!msg || isLoading) return;
  input.value = '';
  sendText(msg);
}

function sendQuickPrompt(btn) {
  sendText(btn.textContent.replace(/^[^ ]+ /,'').trim());
}

async function sendText(text) {
  if (isLoading) return;

  appendMessage('user', text);
  chatHistory.push({ role:'user', content: text });

  isLoading = true;
  document.getElementById('send-btn').disabled = true;

  const typingEl = appendTyping();

  try {
    const response = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: 'claude-sonnet-4-20250514',
        max_tokens: 1000,
        system: buildSystemPrompt(),
        messages: chatHistory
      })
    });

    typingEl.remove();
    const data = await response.json();

    if (data.error) throw new Error(data.error.message);

    const reply = data.content?.[0]?.text || 'Sorry, I had trouble generating a response. Please try again.';
    appendMessage('ai', formatAIReply(reply));
    chatHistory.push({ role:'assistant', content: reply });

  } catch (err) {
    typingEl.remove();
    // Fallback: use built-in responses
    const fallback = getFallbackResponse(text);
    appendMessage('ai', formatAIReply(fallback));
    chatHistory.push({ role:'assistant', content: fallback });
  }

  isLoading = false;
  document.getElementById('send-btn').disabled = false;
}

function formatAIReply(text) {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/\n\n/g, '<br><br>')
    .replace(/\n- /g, '<br>โ€ข ')
    .replace(/\nโ€ข /g, '<br>โ€ข ')
    .replace(/\n(\d+)\. /g, '<br>$1. ');
}

function getFallbackResponse(query) {
  const q = query.toLowerCase();
  const p = getPortfolio();
  const equityPct = p.assets.filter(a=>a.type==='Stock'||a.type==='ETF').reduce((s,a)=>s+a.pct,0);
  const riskScore = calcRiskScore(p);

  if (q.includes('portfolio') || q.includes('analyze')) {
    return `**Here's a quick analysis of your portfolio:** ๐Ÿ“Š\n\n` +
      `You're holding **${p.assets.length} assets** with **${equityPct}% in equities**. ` +
      `Your risk score is **${riskScore}/100**, which puts you in the **${p.riskProfile||'Moderate'}** category.\n\n` +
      `**Strengths:**\n- Good asset count for diversification\n- Mix of ETFs and individual stocks\n\n` +
      `**Suggestions:**\n- Consider if bond allocation matches your timeline\n- Review any single position over 30%\n\n` +
      `*Disclaimer: This is AI-generated analysis, not licensed financial advice.*`;
  }
  if (q.includes('etf') || q.includes('index')) {
    return `**ETFs (Exchange-Traded Funds) 101:** ๐Ÿ“Š\n\nAn ETF is a basket of stocks or bonds that trades on an exchange like a single stock.\n\n**Why they're great for beginners:**\n- **Instant diversification** โ€” VOO holds ~500 companies\n- **Low cost** โ€” VOO charges just 0.03% annually\n- **No stock picking required** โ€” just buy the market\n\n**Your portfolio already has ETFs:** ${p.assets.filter(a=>a.type==='ETF').map(a=>a.ticker).join(', ')||'None yet'} โ€” great choice! ๐ŸŽ‰`;
  }
  if (q.includes('compound')) {
    return `**Compound Interest โ€” The 8th Wonder of the World** โšก\n\nCompound interest means earning returns on your returns.\n\n**Simple example:**\n- Invest $10,000 at 8%/year\n- Year 1: $10,800\n- Year 10: $21,589\n- Year 30: $100,627 โ€” **10ร— your money!**\n\nThe key insight: **time accelerates everything**. Starting at 25 vs 35 can mean the difference of $300,000+ at retirement โ€” even with the same contributions.`;
  }
  if (q.includes('risk') || q.includes('rebalance')) {
    return `**Your Risk Profile:** ๐ŸŽฏ\n\nYour current risk score is **${riskScore}/100**.\n\n**Quick rebalancing check:**\n- If any single asset has drifted >5% from target โ†’ trim it\n- If equity % has grown significantly โ†’ add bonds\n- Do this **annually** or when allocation drifts >5%\n\n**For your portfolio:** ${equityPct > 80 ? 'โš ๏ธ High equity concentration. Consider adding some bonds for stability.' : 'โœ… Equity balance looks reasonable for a growth-oriented investor.'}\n\n*Review every quarter, rebalance annually.*`;
  }
  if (q.includes('retirement') || q.includes('4%')) {
    return `**The 4% Rule Explained** ๐Ÿ–๏ธ\n\nThe 4% rule says: in retirement, you can safely withdraw 4% of your portfolio annually and it should last 30+ years.\n\n**Example:**\n- $1,000,000 nest egg โ†’ $40,000/year ($3,333/mo)\n- $500,000 โ†’ $20,000/year ($1,667/mo)\n\n**Your goal:** Save **25ร— your annual expenses**\n\n**Use our Retirement Calculator** to see exactly when you'll hit your number! ๐Ÿงฎ`;
  }
  if (q.includes('dollar') || q.includes('dca') || q.includes('averaging')) {
    return `**Dollar-Cost Averaging (DCA)** ๐Ÿ“…\n\nInstead of investing a lump sum, you invest a fixed amount at regular intervals โ€” regardless of the market price.\n\n**Why it works:**\n- Removes emotion from investing\n- You buy more shares when prices are low\n- You buy fewer shares when prices are high\n- Averages out your cost over time\n\n**Example:** $300/month in VOO no matter what the market does. You don't need to predict anything โ€” just stay consistent. That's it! ๐ŸŽฏ`;
  }

  return `**Great question!** ๐Ÿ’ก\n\nThat's an important topic in personal finance. Based on your portfolio (${p.assets.map(a=>a.ticker).join(', ')}), here's what I'd suggest:\n\n- Keep learning and asking questions like this โ€” financial literacy compounds just like money does!\n- Use the Calculators to model different scenarios\n- Review the Concepts section for deeper dives\n\n*Connect to the internet to get fully personalized AI responses powered by Claude.* ๐Ÿค–`;
}

function appendMessage(role, html) {
  const msgs = document.getElementById('chat-messages');
  const div = document.createElement('div');
  div.className = 'chat-message ' + (role==='user'?'user':'');
  div.innerHTML = `
    <div class="chat-avatar ${role==='user'?'user-av':'ai-av'}">${role==='user'?'๐Ÿ‘ค':'๐Ÿค–'}</div>
    <div class="chat-bubble ${role}">${html}</div>
  `;
  msgs.appendChild(div);
  msgs.scrollTop = msgs.scrollHeight;
  return div;
}

function appendTyping() {
  const msgs = document.getElementById('chat-messages');
  const div = document.createElement('div');
  div.className = 'chat-message';
  div.innerHTML = `
    <div class="chat-avatar ai-av">๐Ÿค–</div>
    <div class="chat-typing"><span></span><span></span><span></span></div>
  `;
  msgs.appendChild(div);
  msgs.scrollTop = msgs.scrollHeight;
  return div;
}

// โ”€โ”€ Glossary โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
const GLOSSARY = [
  { term:'APY', def:'Annual Percentage Yield โ€” the real return earned in a year, including compound interest.' },
  { term:'Asset Allocation', def:'How you divide your portfolio among different asset classes like stocks, bonds, and cash.' },
  { term:'Bear Market', def:'A market decline of 20% or more from recent highs, lasting at least 2 months.' },
  { term:'Beta', def:'Measures an asset\'s volatility vs the market. Beta>1 = more volatile than the S&P 500.' },
  { term:'Blue-Chip Stock', def:'Shares of large, reputable companies with long track records of stable performance.' },
  { term:'Bond', def:'A loan you give to a company or government. They pay you interest and return your principal at maturity.' },
  { term:'Bull Market', def:'A period of rising prices, generally defined as a 20%+ gain from recent lows.' },
  { term:'Compound Interest', def:'Earning returns on your returns. The longer you invest, the more powerful this becomes.' },
  { term:'Diversification', def:'Spreading investments across many assets to reduce risk without necessarily reducing returns.' },
  { term:'Dividend', def:'A portion of a company\'s profits paid to shareholders, usually quarterly.' },
  { term:'DCA', def:'Dollar-Cost Averaging โ€” investing a fixed amount regularly, regardless of market price.' },
  { term:'ETF', def:'Exchange-Traded Fund โ€” a basket of securities that trades on an exchange like a single stock.' },
  { term:'Expense Ratio', def:'Annual fee charged by mutual funds/ETFs, expressed as % of your investment.' },
  { term:'FIRE', def:'Financial Independence, Retire Early โ€” movement focused on saving aggressively to retire young.' },
  { term:'Index Fund', def:'A fund that tracks a market index (like S&P 500) passively. Usually low-cost and diversified.' },
  { term:'Liquidity', def:'How easily an asset can be converted to cash. Stocks are liquid; real estate is not.' },
  { term:'Market Cap', def:'Total market value of a company\'s outstanding shares (Price ร— Shares Outstanding).' },
  { term:'P/E Ratio', def:'Price-to-Earnings ratio โ€” how much investors pay per dollar of earnings. Measures valuation.' },
  { term:'Rebalancing', def:'Adjusting your portfolio back to target allocation by selling overweighted and buying underweighted assets.' },
  { term:'Risk Tolerance', def:'Your ability (financial) and willingness (emotional) to endure market fluctuations.' },
  { term:'Roth IRA', def:'A retirement account funded with after-tax money. Qualified withdrawals are tax-free.' },
  { term:'S&P 500', def:'An index tracking 500 of the largest US publicly traded companies by market cap.' },
  { term:'SIP', def:'Systematic Investment Plan โ€” regular, automated investments at fixed intervals.' },
  { term:'Volatility', def:'The degree of price variation over time. Higher volatility = higher risk and potential reward.' },
  { term:'Yield', def:'Income generated by an investment, usually expressed as a percentage of the investment\'s value.' },
];

function renderGlossary(filter='') {
  const items = filter ? GLOSSARY.filter(g=>g.term.toLowerCase().includes(filter)||g.def.toLowerCase().includes(filter)) : GLOSSARY;
  document.getElementById('glossary-grid').innerHTML = items.map(g => `
    <div class="glossary-item">
      <div class="glos-term">${g.term}</div>
      <div class="glos-def">${g.def}</div>
    </div>
  `).join('');
}

function filterGlossary() {
  renderGlossary(document.getElementById('glossary-search').value.toLowerCase());
}

document.addEventListener('DOMContentLoaded', () => {
  buildContextSummary();
  renderGlossary();
});
</script>
</body>
</html>