File size: 76,113 Bytes
5a7521c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d19ab6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>ClearPath β€” Debt Freedom Agent</title>
<meta name="description" content="A free planning agent that models your credit card payoff, frees up monthly cash flow, and matches you to government and nonprofit assistance programs." />
<style>
  :root{
    --ink:#0d1b23;
    --ink-2:#20323d;
    --muted:#5c7079;
    --paper:#f4f7f7;
    --card:#ffffff;
    --line:#dfe7e8;
    --brand:#0d6f66;
    --brand-ink:#0a544e;
    --brand-soft:#e6f3f1;
    --amber:#8a5a00;
    --amber-soft:#fdf3e0;
    --danger:#a02020;
    --danger-soft:#fdeceb;
    --radius:18px;
    --shadow:0 1px 2px rgba(13,27,35,.05), 0 8px 24px rgba(13,27,35,.06);
  }
  *{box-sizing:border-box}
  html,body{margin:0;padding:0}
  body{
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Inter,Helvetica,Arial,sans-serif;
    background:var(--paper); color:var(--ink);
    -webkit-font-smoothing:antialiased;
    line-height:1.5;
  }
  h1,h2,h3,h4{margin:0; line-height:1.2; letter-spacing:-.01em}
  p{margin:0}
  a{color:var(--brand-ink)}
  button{font-family:inherit}
  .wrap{max-width:760px;margin:0 auto;padding:0 16px}

  /* ---------- HERO ---------- */
  header.hero{
    position:relative;
    background:
      radial-gradient(120% 90% at 85% -10%, rgba(46,196,182,.35), transparent 60%),
      radial-gradient(100% 80% at 0% 0%, rgba(255,255,255,.12), transparent 55%),
      linear-gradient(160deg,#0b3b3a 0%, #0d2b31 55%, #0d1b23 100%);
    color:#eaf5f3;
    padding:26px 0 30px;
    overflow:hidden;
  }
  .brandrow{display:flex;align-items:center;gap:10px;margin-bottom:18px}
  .mark{
    width:32px;height:32px;border-radius:10px;flex:0 0 auto;
    background:linear-gradient(150deg,#3fd0bd,#0d8f80);
    display:grid;place-items:center;color:#052b28;font-weight:800;font-size:15px;
    box-shadow:0 6px 16px rgba(63,208,189,.28);
  }
  .brandname{font-weight:700;font-size:14px;letter-spacing:.14em;text-transform:uppercase;color:#bfe6e0}
  header.hero h1{font-size:clamp(27px,7vw,40px);font-weight:800;letter-spacing:-.03em;margin-bottom:10px}
  header.hero h1 span{color:#5ee0cb}
  .lede{color:#c2dcd8;font-size:15.5px;max-width:52ch}
  .hero-tags{display:flex;flex-wrap:wrap;gap:8px;margin-top:18px}
  .tag{
    font-size:12px;font-weight:600;color:#d6efeb;
    background:rgba(255,255,255,.09);border:1px solid rgba(255,255,255,.14);
    padding:6px 10px;border-radius:999px;
  }

  /* ---------- CARDS / FORM ---------- */
  section.block{
    background:var(--card);border:1px solid var(--line);border-radius:var(--radius);
    padding:18px;margin:14px 0;box-shadow:var(--shadow);
  }
  .blockhead{display:flex;align-items:baseline;gap:10px;margin-bottom:4px}
  .stepno{
    width:24px;height:24px;border-radius:8px;background:var(--brand-soft);color:var(--brand-ink);
    display:grid;place-items:center;font-size:12.5px;font-weight:800;flex:0 0 auto;
  }
  .block h2{font-size:18px}
  .hint{color:var(--muted);font-size:13.5px;margin:6px 0 14px}

  label.f{display:block;font-size:12.5px;font-weight:700;color:var(--ink-2);margin-bottom:5px;letter-spacing:.02em}
  .grid{display:grid;gap:12px}
  @media(min-width:560px){ .g2{grid-template-columns:1fr 1fr} .g3{grid-template-columns:1fr 1fr 1fr} }
  input,select{
    width:100%;font-size:16px;padding:12px 12px;border-radius:12px;
    border:1px solid var(--line);background:#fbfcfc;color:var(--ink);
    appearance:none;
  }
  input:focus,select:focus{outline:2px solid #9fd8d0;outline-offset:1px;border-color:#9fd8d0;background:#fff}
  select{background-image:linear-gradient(45deg,transparent 50%,#6b7d85 50%),linear-gradient(135deg,#6b7d85 50%,transparent 50%);
    background-position:calc(100% - 18px) 21px, calc(100% - 13px) 21px;background-size:5px 5px,5px 5px;background-repeat:no-repeat;padding-right:34px}
  .money{position:relative}
  .money span{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:15px}
  .money input{padding-left:26px}

  /* debt rows */
  .debtrow{
    display:grid;grid-template-columns:1.2fr 1fr 1fr;gap:8px;align-items:end;
    padding:12px;border:1px dashed var(--line);border-radius:14px;background:#fafcfc;margin-bottom:10px;
  }
  .debtrow .delrow{grid-column:1/-1;display:flex;justify-content:space-between;align-items:center;font-size:12px;color:var(--muted)}
  .debtlist{margin-bottom:12px}
  .ditem{
    display:grid;grid-template-columns:1fr auto;gap:10px;align-items:center;
    padding:10px 12px;border:1px solid var(--line);border-radius:12px;margin-bottom:8px;background:#fff;
  }
  .ditem b{font-size:14px;display:block}
  .ditem small{color:var(--muted);font-size:12.5px}
  .x{
    border:1px solid var(--line);background:#fff;color:var(--muted);
    width:30px;height:30px;border-radius:9px;font-size:16px;line-height:1;cursor:pointer;
  }
  .x:hover{color:var(--danger);border-color:#f0c9c9}

  .btn{
    display:inline-flex;align-items:center;justify-content:center;gap:8px;
    border:0;border-radius:13px;padding:14px 18px;font-weight:700;font-size:15px;cursor:pointer;
    background:var(--brand);color:#fff;box-shadow:0 6px 18px rgba(13,111,102,.22);
  }
  .btn:active{transform:translateY(1px)}
  .btn.wide{width:100%}
  .btn.ghost{background:#fff;color:var(--brand-ink);border:1px solid #bcd9d5;box-shadow:none;font-weight:600;padding:10px 14px;font-size:13.5px;border-radius:11px}
  .btn.ghost.sm{padding:8px 12px;font-size:12.5px}
  .btnrow{display:flex;flex-wrap:wrap;gap:8px}
  .err{color:var(--danger);font-size:13.5px;margin-top:10px;font-weight:600}
  .checks{display:grid;gap:8px;margin-top:6px}
  @media(min-width:520px){.checks{grid-template-columns:1fr 1fr}}
  .check{
    display:flex;gap:9px;align-items:flex-start;padding:10px 11px;border:1px solid var(--line);
    border-radius:12px;background:#fbfcfc;font-size:13.5px;cursor:pointer;line-height:1.35;
  }
  .check input{width:18px;height:18px;flex:0 0 auto;margin:1px 0 0;accent-color:var(--brand)}
  .check.on{background:var(--brand-soft);border-color:#b9ded8}

  /* ---------- DASHBOARD ---------- */
  #dash{display:none;padding-bottom:96px}
  .tabs{
    position:sticky;top:0;z-index:20;background:rgba(244,247,247,.94);
    backdrop-filter:blur(10px);border-bottom:1px solid var(--line);
    display:flex;gap:6px;overflow-x:auto;padding:8px 0;margin:0 -16px;padding-left:16px;padding-right:16px;
    scrollbar-width:none;
  }
  .tabs::-webkit-scrollbar{display:none}
  .tab{
    flex:0 0 auto;border:1px solid transparent;background:transparent;color:var(--muted);
    font-size:13.5px;font-weight:700;padding:9px 13px;border-radius:11px;cursor:pointer;white-space:nowrap;
  }
  .tab[aria-selected="true"]{background:#fff;border-color:var(--line);color:var(--ink);box-shadow:0 1px 3px rgba(13,27,35,.07)}
  .pane{display:none}
  .pane.active{display:block}

  .kpis{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:14px 0}
  .kpi{background:#fff;border:1px solid var(--line);border-radius:14px;padding:13px;box-shadow:var(--shadow)}
  .kpi .lab{font-size:11px;font-weight:800;letter-spacing:.09em;text-transform:uppercase;color:var(--muted)}
  .kpi .val{font-size:22px;font-weight:800;letter-spacing:-.02em;margin-top:4px}
  .kpi .sub{font-size:12px;color:var(--muted);margin-top:2px}
  .kpi.good .val{color:var(--brand-ink)}
  .kpi.warn .val{color:var(--danger)}

  .agentnote{
    display:flex;gap:12px;background:linear-gradient(180deg,#0e3d3b,#0d2b31);
    color:#e7f4f1;border-radius:16px;padding:16px;margin:14px 0;
  }
  .agentnote .dot{width:9px;height:9px;border-radius:50%;background:#5ee0cb;margin-top:7px;flex:0 0 auto;box-shadow:0 0 0 4px rgba(94,224,203,.16)}
  .agentnote p{font-size:14px}
  .agentnote b{color:#fff}

  .scen{border:1px solid var(--line);border-radius:14px;padding:14px;background:#fff;margin-bottom:10px}
  .scen.best{border-color:#9ed6cd;background:linear-gradient(180deg,#f2fbf9,#fff)}
  .scen .row{display:flex;justify-content:space-between;align-items:flex-start;gap:10px}
  .scen h3{font-size:15px}
  .scen .badge{font-size:11px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:var(--brand-ink);background:var(--brand-soft);padding:4px 8px;border-radius:7px}
  .metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:12px}
  .metrics div{background:#f6f9f9;border-radius:10px;padding:9px 10px}
  .metrics .m{font-size:15.5px;font-weight:800;letter-spacing:-.01em}
  .metrics .l{font-size:10.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);font-weight:700;margin-top:2px}

  .sliderbox{margin-top:6px}
  .sliderhead{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:6px}
  .sliderhead b{font-size:16px}
  input[type=range]{width:100%;accent-color:var(--brand);height:28px;padding:0;border:0;background:transparent}

  h3.sechead{font-size:16px;margin:20px 0 8px}

  /* programs */
  .pillrow{display:flex;flex-wrap:wrap;gap:10px;margin:12px 0 4px}
  .chip{
    border:1px solid var(--line);background:#fff;color:var(--ink-2);font-size:12.5px;font-weight:600;
    padding:7px 11px;border-radius:999px;cursor:pointer;
  }
  .chip:hover{border-color:#a9d4ce;color:var(--brand-ink)}
  .chip[aria-pressed="true"]{background:var(--brand);border-color:var(--brand);color:#fff}
  .cathead{
    font-size:11px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);
    margin:22px 0 10px;display:flex;align-items:center;gap:8px;
  }
  .cathead:after{content:"";flex:1;height:1px;background:var(--line)}
  .prog{
    border:1px solid var(--line);border-radius:16px;background:#fff;padding:15px;margin-bottom:10px;box-shadow:var(--shadow);
  }
  .prog .top{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}
  .prog h3{font-size:15.5px;letter-spacing:-.01em}
  .tier{font-size:10.5px;font-weight:800;letter-spacing:.07em;text-transform:uppercase;padding:4px 8px;border-radius:7px;white-space:nowrap;flex:0 0 auto}
  .tier.likely{background:var(--brand-soft);color:var(--brand-ink)}
  .tier.check{background:var(--amber-soft);color:var(--amber)}
  .tier.info{background:#eef2f5;color:#40545e}
  .src{font-size:10.5px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;color:#7b8f97;margin-top:6px}
  .why{
    font-size:13.5px;color:var(--ink-2);margin-top:9px;padding-left:11px;border-left:2px solid #cfe6e1;
  }
  .prog .links{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px;align-items:center}
  .ext{
    display:inline-flex;align-items:center;gap:6px;font-size:13px;font-weight:700;color:#fff;background:var(--brand);
    text-decoration:none;padding:9px 13px;border-radius:10px;
  }
  .ext:hover{background:var(--brand-ink)}
  .tel{font-size:13px;font-weight:700;color:var(--ink-2);text-decoration:none;border:1px solid var(--line);padding:8px 12px;border-radius:10px;background:#fbfcfc}
  .cost{font-size:12px;color:var(--muted);margin-top:10px;display:flex;gap:6px;align-items:flex-start}

  /* actions */
  ol.steps{list-style:none;padding:0;margin:0;counter-reset:s}
  ol.steps li{
    counter-increment:s;position:relative;padding:0 0 18px 42px;border-left:1px solid var(--line);margin-left:12px;
  }
  ol.steps li:last-child{border-left-color:transparent;padding-bottom:0}
  ol.steps li:before{
    content:counter(s);position:absolute;left:-13px;top:-2px;width:26px;height:26px;border-radius:50%;
    background:#fff;border:1.5px solid #b9ded8;color:var(--brand-ink);font-size:12.5px;font-weight:800;
    display:grid;place-items:center;
  }
  ol.steps li.done:before{background:var(--brand);border-color:var(--brand);color:#fff;content:"βœ“"}
  ol.steps h4{font-size:14.5px;margin-bottom:3px;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
  ol.steps p{font-size:13px;color:var(--ink-2)}
  ol.steps .when{font-size:10.5px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:var(--brand-ink);background:var(--brand-soft);padding:3px 7px;border-radius:6px}
  ol.steps a{font-size:12.5px;font-weight:700;display:inline-block;margin-top:6px}
  .tick{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);margin-top:8px;cursor:pointer}

  .script{background:#0f2a2a;color:#dff2ee;border-radius:14px;padding:15px;font-size:13.5px;line-height:1.6}
  .script .sl{font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:#7fd8c9;font-weight:800;margin-bottom:8px}
  .script q{quotes:"β€œ" "”"}

  .warn{
    background:var(--danger-soft);border:1px solid #f3cfcd;border-radius:14px;padding:14px;margin:14px 0;
  }
  .warn h4{font-size:14px;color:var(--danger);margin-bottom:4px}
  .warn p{font-size:13.5px;color:#5e2626}
  .note{background:var(--amber-soft);border:1px solid #f2dfb6;border-radius:14px;padding:14px;margin:14px 0;font-size:13.5px;color:#5b3f06}

  footer{padding:26px 0 40px;color:var(--muted);font-size:12px;text-align:center}
  footer a{color:var(--brand-ink);font-weight:600}

  /* chat */
  .fab{
    position:fixed;right:16px;bottom:calc(16px + env(safe-area-inset-bottom));z-index:60;
    border:0;border-radius:999px;background:var(--ink);color:#fff;padding:14px 18px;font-weight:700;font-size:14px;
    box-shadow:0 10px 28px rgba(13,27,35,.3);display:flex;gap:8px;align-items:center;cursor:pointer;
  }
  .fab span.i{width:8px;height:8px;border-radius:50%;background:#5ee0cb}
  .sheet{
    position:fixed;inset:0;z-index:70;background:rgba(13,27,35,.42);
    display:none;align-items:flex-end;justify-content:center;
  }
  .sheet.open{display:flex}
  .sheetpanel{
    background:#fff;width:100%;max-width:560px;max-height:88vh;border-radius:20px 20px 0 0;
    display:flex;flex-direction:column;overflow:hidden;box-shadow:0 -12px 40px rgba(0,0,0,.2);
  }
  .sheethead{display:flex;justify-content:space-between;align-items:center;padding:14px 16px;border-bottom:1px solid var(--line)}
  .sheethead b{font-size:15px}
  .sheethead small{display:block;color:var(--muted);font-size:11.5px;font-weight:500}
  .log{padding:14px 16px;overflow-y:auto;flex:1;display:flex;flex-direction:column;gap:10px;background:#fbfcfc}
  .msg{max-width:88%;padding:11px 13px;border-radius:14px;font-size:13.5px;line-height:1.5}
  .msg.bot{background:#fff;border:1px solid var(--line);align-self:flex-start;border-bottom-left-radius:5px}
  .msg.me{background:var(--brand);color:#fff;align-self:flex-end;border-bottom-right-radius:5px}
  .msg a{color:var(--brand-ink);font-weight:700}
  .msg.me a{color:#fff}
  .quick{display:flex;gap:7px;overflow-x:auto;padding:10px 16px;border-top:1px solid var(--line);background:#fff;scrollbar-width:none}
  .quick::-webkit-scrollbar{display:none}
  .quick button{
    flex:0 0 auto;border:1px solid var(--line);background:#fbfcfc;border-radius:999px;padding:8px 12px;
    font-size:12.5px;font-weight:600;color:var(--ink-2);cursor:pointer;white-space:nowrap;
  }
  .inputbar{display:flex;gap:8px;padding:10px 12px calc(12px + env(safe-area-inset-bottom));border-top:1px solid var(--line);background:#fff}
  .inputbar input{font-size:16px}
  .inputbar button{border:0;background:var(--brand);color:#fff;border-radius:11px;padding:0 16px;font-weight:700;cursor:pointer}
  .typing{font-size:12px;color:var(--muted);padding:0 16px 10px;background:#fbfcfc}
</style>
</head>
<body>

<header class="hero">
  <div class="wrap">
    <div class="brandrow">
      <div class="mark">CP</div>
      <div class="brandname">ClearPath</div>
    </div>
    <h1>Get out of card debt.<br><span>Keep your cash flow.</span></h1>
    <p class="lede">I model your payoff, find the government and nonprofit programs you may qualify for, and turn it into a 90-day plan you can actually do. Nothing leaves your browser.</p>
    <div class="hero-tags">
      <span class="tag">Official programs only</span>
      <span class="tag">Every resource has a link</span>
      <span class="tag">Free Β· no accounts Β· no upsell</span>
    </div>
  </div>
</header>

<main class="wrap" id="intake">

  <!-- STEP 1 -->
  <section class="block">
    <div class="blockhead"><div class="stepno">1</div><h2>Your credit card debts</h2></div>
    <p class="hint">Add each card. Use the statement balance, the purchase APR, and the minimum payment shown on the bill. Approximate is fine β€” you can adjust later.</p>

    <div class="debtlist" id="debtList"></div>

    <div class="debtrow" id="addRow">
      <div>
        <label class="f" for="dName">Card</label>
        <input id="dName" placeholder="Chase Visa" autocomplete="off" />
      </div>
      <div>
        <label class="f" for="dBal">Balance</label>
        <div class="money"><span>$</span><input id="dBal" inputmode="decimal" placeholder="4200" /></div>
      </div>
      <div>
        <label class="f" for="dApr">APR %</label>
        <input id="dApr" inputmode="decimal" placeholder="26.99" />
      </div>
      <div class="delrow">
        <div style="display:flex;gap:8px;align-items:end;flex:1">
          <div style="flex:1">
            <label class="f" for="dMin">Minimum payment</label>
            <div class="money"><span>$</span><input id="dMin" inputmode="decimal" placeholder="125" /></div>
          </div>
        </div>
        <button class="btn ghost sm" id="addDebt" type="button" style="margin-left:8px">+ Add card</button>
      </div>
    </div>

    <div class="btnrow" style="margin-top:12px">
      <button class="btn ghost sm" id="loadDemo" type="button">Load an example instead</button>
    </div>
    <div class="err" id="err1"></div>
  </section>

  <!-- STEP 2 -->
  <section class="block">
    <div class="blockhead"><div class="stepno">2</div><h2>Monthly money in and out</h2></div>
    <p class="hint">Take-home pay only (after tax). Essentials = rent or mortgage, food, utilities, transport, insurance, childcare, phone. Leave out the card payments β€” those are already counted above.</p>
    <div class="grid g2">
      <div>
        <label class="f" for="income">Monthly take-home income</label>
        <div class="money"><span>$</span><input id="income" inputmode="decimal" placeholder="3400" /></div>
      </div>
      <div>
        <label class="f" for="essentials">Essential living costs</label>
        <div class="money"><span>$</span><input id="essentials" inputmode="decimal" placeholder="2450" /></div>
      </div>
      <div>
        <label class="f" for="otherDebt">Other monthly debt payments <span style="font-weight:500;color:var(--muted)">(car, student, personal loans)</span></label>
        <div class="money"><span>$</span><input id="otherDebt" inputmode="decimal" placeholder="310" /></div>
      </div>
      <div>
        <label class="f" for="cash">Cash you could put toward debt today</label>
        <div class="money"><span>$</span><input id="cash" inputmode="decimal" placeholder="0" /></div>
      </div>
    </div>
    <div class="err" id="err2"></div>
  </section>

  <!-- STEP 3 -->
  <section class="block">
    <div class="blockhead"><div class="stepno">3</div><h2>Your situation</h2></div>
    <p class="hint">This is what drives the program matching. Program rules vary by state, so treat matches as leads to confirm with the agency.</p>
    <div class="grid g3">
      <div>
        <label class="f" for="state">State</label>
        <select id="state"></select>
      </div>
      <div>
        <label class="f" for="household">People in household</label>
        <select id="household">
          <option>1</option><option>2</option><option>3</option><option>4</option>
          <option>5</option><option>6</option><option>7</option><option>8</option>
        </select>
      </div>
      <div>
        <label class="f" for="credit">Credit score range</label>
        <select id="credit">
          <option value="low">Below 580</option>
          <option value="fair" selected>580–669</option>
          <option value="good">670–739</option>
          <option value="high">740+</option>
          <option value="unknown">Not sure</option>
        </select>
      </div>
    </div>
    <div class="checks" id="flagChecks" style="margin-top:14px"></div>
    <div class="err" id="err3"></div>
  </section>

  <button class="btn wide" id="runBtn" type="button" style="margin:6px 0 8px">Build my plan β†’</button>
  <p class="hint" style="text-align:center;margin-bottom:26px">Educational tool, not financial or legal advice. No credit check, no data uploaded.</p>
</main>

<main class="wrap" id="dash">
  <div class="tabs" role="tablist">
    <button class="tab" role="tab" aria-selected="true" data-pane="plan">Plan</button>
    <button class="tab" role="tab" aria-selected="false" data-pane="programs">Programs <span id="progCount" style="opacity:.6"></span></button>
    <button class="tab" role="tab" aria-selected="false" data-pane="actions">90-day actions</button>
    <button class="tab" role="tab" aria-selected="false" data-pane="rights">Rights &amp; traps</button>
  </div>

  <div class="pane active" id="pane-plan">
    <div id="planBody"></div>
  </div>

  <div class="pane" id="pane-programs">
    <div class="agentnote" style="margin-top:16px">
      <div class="dot"></div>
      <p><b>How these were picked:</b> I compare your numbers to published program rules and your situation flags. Nothing here is an approval β€” each agency makes its own decision. Every card links to the official page or a national nonprofit.</p>
    </div>
    <div class="pillrow" id="progFilters"></div>
    <div id="programsBody"></div>
  </div>

  <div class="pane" id="pane-actions">
    <div id="actionsBody"></div>
  </div>

  <div class="pane" id="pane-rights">
    <div id="rightsBody"></div>
  </div>
</main>

<footer class="wrap">
  <p><strong>ClearPath</strong> is an educational planning tool. It is not a lender, debt relief company, credit repair organization, law firm, or government agency. It does not negotiate debt or promise outcomes.</p>
  <p style="margin-top:8px">Program rules and links checked November 2026. In crisis? Call or text <strong>988</strong>. Local help: dial <strong>211</strong>.</p>
</footer>

<button class="fab" id="fab" type="button"><span class="i"></span> Ask ClearPath</button>

<div class="sheet" id="sheet" aria-hidden="true">
  <div class="sheetpanel" role="dialog" aria-modal="true" aria-label="Ask ClearPath">
    <div class="sheethead">
      <div>
        <b>Ask ClearPath</b>
        <small>Answers use your numbers. Links go to official sources.</small>
      </div>
      <button class="x" id="closeSheet" type="button" aria-label="Close">Γ—</button>
    </div>
    <div class="log" id="log"></div>
    <div class="quick" id="quick"></div>
    <div class="inputbar">
      <input id="chatIn" placeholder="e.g. a collector keeps calling" autocomplete="off" />
      <button id="sendBtn" type="button">Send</button>
    </div>
  </div>
</div>

<script>
/* ============================================================
   ClearPath β€” client-side planning agent
   No network calls, no storage. Pure in-memory state.
   ============================================================ */

const S = {
  debts: [],
  income: 0, essentials: 0, otherDebt: 0, cash: 0,
  state: "CA", household: 1, credit: "fair",
  flags: {},
  extra: 0,
  strategy: "avalanche",
  filter: "all",
  done: {},
  ran: false
};

const FLAGS = [
  ["behind", "I'm behind on at least one payment"],
  ["collector", "A debt collector is contacting me"],
  ["sued", "I've been sued, served, or threatened with garnishment"],
  ["student", "I have federal student loans"],
  ["tax", "I owe back taxes"],
  ["rent", "Rent or mortgage is a struggle"],
  ["utilities", "Utility bills are behind or shut-off notice"],
  ["medical", "I have medical bills or no health coverage"],
  ["kids", "Children under 18 at home"],
  ["veteran", "I'm a veteran or military family"],
  ["senior", "I'm 60 or older"],
  ["disability", "I have a disability"],
  ["job", "I'm unemployed or hours were cut"],
  ["unbanked", "I've been denied a checking account"]
];

const STATES = ["AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"];

/* SNAP gross monthly income limits, Oct 1 2026 – Sep 30 2027, 48 states + DC
   Source: USDA Food and Nutrition Service / FNA eligibility page */
const SNAP_LIMIT = {1:1729, 2:2345, 3:2960, 4:3575, 5:4191, 6:4806, 7:5421, 8:6037};
const SNAP_STEP = 616;

/* ---------- helpers ---------- */
const $ = id => document.getElementById(id);
const n = v => { const x = parseFloat(String(v).replace(/[^0-9.]/g,"")); return isFinite(x) ? x : 0; };
const money = v => "$" + Math.round(v).toLocaleString("en-US");
const money2 = v => "$" + v.toLocaleString("en-US",{minimumFractionDigits:2, maximumFractionDigits:2});
const pct = v => (Math.round(v*10)/10).toFixed(1) + "%";

function monthsToDate(m){
  const d = new Date();
  d.setDate(1);
  d.setMonth(d.getMonth() + m);
  return d.toLocaleDateString("en-US",{month:"short", year:"numeric"});
}
function span(m){
  if (!isFinite(m) || m >= 720) return "β€”";
  const y = Math.floor(m/12), mo = m%12;
  if (y === 0) return mo + " mo";
  if (mo === 0) return y + " yr";
  return y + " yr " + mo + " mo";
}

/* ---------- payoff engine ---------- */
function simulate(debts, extra, strategy){
  const ds = debts.map(d => ({name:d.name, bal:d.balance, apr:d.apr, min:d.min}));
  let months = 0, interest = 0, paid = 0;
  while (months < 720){
    const live = ds.filter(d => d.bal > 0.005);
    if (!live.length) break;
    const order = live.slice().sort(strategy === "snowball"
      ? (a,b) => a.bal - b.bal
      : (a,b) => b.apr - a.apr);

    for (const d of ds){
      if (d.bal <= 0.005) continue;
      const i = d.bal * d.apr / 1200;
      d.bal += i; interest += i;
      const p = Math.min(d.min, d.bal);
      d.bal -= p; paid += p;
      if (d.bal < 0.005) d.bal = 0;
    }

    let pool = extra, guard = 0;
    while (pool > 0.5 && guard++ < 200){
      const t = order.find(d => d.bal > 0.005);
      if (!t) break;
      const p = Math.min(pool, t.bal);
      t.bal -= p; pool -= p; paid += p;
      if (t.bal < 0.005) t.bal = 0;
    }
    months++;
  }
  return { months, interest, paid, impossible: months >= 720 };
}

function totals(){
  const total = S.debts.reduce((s,d) => s + d.balance, 0);
  const min = S.debts.reduce((s,d) => s + d.min, 0);
  const wApr = total > 0 ? S.debts.reduce((s,d) => s + d.apr * d.balance, 0) / total : 0;
  return { total, min, wApr };
}

/* ---------- build ---------- */
function init(){
  const st = $("state");
  st.innerHTML = STATES.map(s => `<option value="${s}"${s==="CA"?" selected":""}>${s}</option>`).join("");

  $("flagChecks").innerHTML = FLAGS.map(([k,label]) =>
    `<label class="check" id="chk-${k}"><input type="checkbox" data-flag="${k}" /><span>${label}</span></label>`
  ).join("");
  $("flagChecks").addEventListener("change", e => {
    if (e.target.dataset.flag){
      S.flags[e.target.dataset.flag] = e.target.checked;
      e.target.closest(".check").classList.toggle("on", e.target.checked);
    }
  });

  $("addDebt").addEventListener("click", addDebt);
  $("loadDemo").addEventListener("click", loadDemo);
  $("runBtn").addEventListener("click", run);
  renderDebtList();

  document.querySelectorAll(".tab").forEach(t => t.addEventListener("click", () => switchPane(t.dataset.pane)));

  $("fab").addEventListener("click", () => { $("sheet").classList.add("open"); if (!S.ran) botSay(introMsg()); });
  $("closeSheet").addEventListener("click", () => $("sheet").classList.remove("open"));
  $("sendBtn").addEventListener("click", sendChat);
  $("chatIn").addEventListener("keydown", e => { if (e.key === "Enter") sendChat(); });
  renderQuick();
}

function addDebt(){
  const name = $("dName").value.trim() || "Card";
  const balance = n($("dBal").value);
  const apr = n($("dApr").value);
  const min = n($("dMin").value);
  if (balance <= 0 || min <= 0){
    $("err1").textContent = "Add a balance and a minimum payment for this card.";
    return;
  }
  S.debts.push({ name, balance, apr: apr || 24, min });
  $("dName").value = ""; $("dBal").value = ""; $("dApr").value = ""; $("dMin").value = "";
  $("err1").textContent = "";
  renderDebtList();
}

function loadDemo(){
  S.debts = [
    { name:"Chase Visa", balance:4800, apr:27.99, min:145 },
    { name:"Capital One", balance:2300, apr:22.9, min:72 },
    { name:"Store card", balance:900, apr:19.99, min:35 }
  ];
  $("income").value = 3400;
  $("essentials").value = 2450;
  $("otherDebt").value = 310;
  $("cash").value = 0;
  renderDebtList();
}

function renderDebtList(){
  const el = $("debtList");
  if (!S.debts.length){
    el.innerHTML = `<p class="hint" style="margin:0 0 12px;padding:14px;border:1px dashed var(--line);border-radius:12px;background:#fafcfc">No cards added yet. Add one below, or load the example.</p>`;
    return;
  }
  el.innerHTML = S.debts.map((d,i) => `
    <div class="ditem">
      <div>
        <b>${escapeHtml(d.name)}</b>
        <small>${money(d.balance)} Β· ${pct(d.apr)} APR Β· ${money(d.min)}/mo minimum</small>
      </div>
      <button class="x" type="button" data-del="${i}" aria-label="Remove ${escapeHtml(d.name)}">Γ—</button>
    </div>`).join("");
  el.querySelectorAll("[data-del]").forEach(b => b.addEventListener("click", () => {
    S.debts.splice(+b.dataset.del, 1); renderDebtList();
  }));
}

function escapeHtml(s){
  return String(s).replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
}

function readForm(){
  S.income = n($("income").value);
  S.essentials = n($("essentials").value);
  S.otherDebt = n($("otherDebt").value);
  S.cash = n($("cash").value);
  S.state = $("state").value;
  S.household = +$("household").value;
  S.credit = $("credit").value;
  document.querySelectorAll("[data-flag]").forEach(c => { S.flags[c.dataset.flag] = c.checked; });
}

function run(){
  readForm();
  const e1 = $("err1"), e2 = $("err2");
  e1.textContent = ""; e2.textContent = "";
  if (!S.debts.length){
    // allow a debt-free-but-struggling path
    if (S.income > 0){
      S.debts = [];
    } else {
      e1.textContent = "Add at least one card, or enter your income to get a benefit plan.";
      return;
    }
  }
  if (S.income <= 0){
    e2.textContent = "Enter your monthly take-home income so I can size your cash flow.";
    return;
  }
  const t = totals();
  const free = S.income - S.essentials - S.otherDebt - t.min;
  S.extra = free > 0 ? Math.max(0, Math.round(free * 0.5 / 5) * 5) : 0;
  S.ran = true;

  $("intake").style.display = "none";
  $("dash").style.display = "block";
  window.scrollTo({top:0, behavior:"instant" in window ? "auto" : "auto"});
  renderAll();
}

function switchPane(id){
  document.querySelectorAll(".tab").forEach(t => t.setAttribute("aria-selected", t.dataset.pane === id ? "true" : "false"));
  document.querySelectorAll(".pane").forEach(p => p.classList.toggle("active", p.id === "pane-" + id));
  window.scrollTo({top:0});
}

/* ---------- context ---------- */
function ctx(){
  const t = totals();
  const free = S.income - S.essentials - S.otherDebt - t.min;
  const dti = S.income > 0 ? (t.min + S.otherDebt) / S.income * 100 : 0;
  const snapLimit = SNAP_LIMIT[Math.min(S.household,8)] + (S.household > 8 ? (S.household-8)*SNAP_STEP : 0);
  return { ...t, free, dti, snapLimit, income:S.income, essentials:S.essentials, otherDebt:S.otherDebt };
}

/* ---------- render: plan ---------- */
function renderAll(){
  renderPlan(); renderPrograms(); renderActions(); renderRights();
}

function renderPlan(){
  const c = ctx();
  const minOnly = simulate(S.debts, 0, "avalanche");
  const maxExtra = Math.max(25, Math.round(Math.max(c.free, 0) / 25) * 25);
  if (S.extra > maxExtra) S.extra = maxExtra;

  const av = simulate(S.debts, S.extra, "avalanche");
  const sn = simulate(S.debts, S.extra, "snowball");
  const best = av.months <= sn.months ? "avalanche" : "snowball";
  const chosen = { avalanche: av, snowball: sn };

  const monthlyInterest = c.total > 0 ? c.total * c.wApr / 1200 : 0;

  let verdict;
  if (!S.debts.length){
    verdict = "No card balances entered. Your plan is focused on <b>cash flow and benefits</b> β€” open the Programs tab, that's where the money is.";
  } else if (minOnly.impossible){
    verdict = "<b>Your minimum payments don't outrun the interest.</b> That's the emergency case β€” this is exactly when a nonprofit credit counselor or a hardship program matters most. Call one this week, not next month.";
  } else if (c.free <= 0){
    verdict = "Your essentials and minimums already eat your take-home pay. So the first move isn't a bigger payment β€” it's <b>lowering the cost of the debt and adding benefits</b>. Start with the credit counselor and the SNAP/LIHEAP checks.";
  } else if (c.dti > 40){
    verdict = "Your debt payments are <b>" + pct(c.dti) + " of take-home pay</b>, which is high. Expect a counselor to talk about a debt management plan rather than just a tighter budget.";
  } else {
    verdict = "You have about <b>" + money(c.free) + " a month</b> of room after essentials and minimums. Putting most of it on the highest-rate card is the cheapest path out.";
  }

  // DMP illustration
  let dmp = null;
  if (c.total > 0){
    const r = 0.08/12, nn = 60;
    const pmt = c.total * r / (1 - Math.pow(1+r, -nn));
    dmp = { pmt, months: 60, delta: c.min - pmt, totalPaid: pmt * nn };
  }

  const html = `
    <div class="agentnote">
      <div class="dot"></div>
      <p>${verdict}</p>
    </div>

    <div class="kpis">
      <div class="kpi"><div class="lab">Card debt</div><div class="val">${money(c.total)}</div><div class="sub">${S.debts.length} account${S.debts.length===1?"":"s"} Β· avg ${pct(c.wApr)} APR</div></div>
      <div class="kpi"><div class="lab">Minimums / month</div><div class="val">${money(c.min)}</div><div class="sub">${money(monthlyInterest)} of that is interest</div></div>
      <div class="kpi ${c.free > 0 ? "good" : "warn"}"><div class="lab">Free cash flow</div><div class="val">${money(c.free)}</div><div class="sub">After essentials, all minimums</div></div>
      <div class="kpi ${c.dti > 40 ? "warn" : ""}"><div class="lab">Debt payments</div><div class="val">${pct(c.dti)}</div><div class="sub">of take-home pay</div></div>
    </div>

    <h3 class="sechead">How fast you're out</h3>

    <div class="scen">
      <div class="row"><h3>Minimums only</h3></div>
      <div class="metrics">
        <div><div class="m">${minOnly.impossible ? "Never" : span(minOnly.months)}</div><div class="l">Time to zero</div></div>
        <div><div class="m">${minOnly.impossible ? "Growing" : money(minOnly.interest)}</div><div class="l">Interest paid</div></div>
        <div><div class="m">${minOnly.impossible ? "β€”" : monthsToDate(minOnly.months)}</div><div class="l">Debt-free</div></div>
      </div>
    </div>

    <div class="sliderbox" style="margin:18px 0 6px">
      <div class="sliderhead">
        <label class="f" for="extra" style="margin:0">Extra toward cards each month</label>
        <b id="extraOut">${money(S.extra)}</b>
      </div>
      <input type="range" id="extra" min="0" max="${maxExtra}" step="5" value="${S.extra}" />
      <p class="hint" style="margin:2px 0 0">Slide to see the trade-off. ${maxExtra} is roughly what your budget can absorb right now.</p>
    </div>

    <div class="scen best">
      <div class="row">
        <h3>Avalanche β€” highest APR first</h3>
        ${best === "avalanche" ? '<span class="badge">Cheapest</span>' : ""}
      </div>
      <div class="metrics">
        <div><div class="m">${av.impossible ? "Never" : span(av.months)}</div><div class="l">Time to zero</div></div>
        <div><div class="m">${av.impossible ? "β€”" : money(av.interest)}</div><div class="l">Interest</div></div>
        <div><div class="m">${av.impossible ? "β€”" : monthsToDate(av.months)}</div><div class="l">Debt-free</div></div>
      </div>
      <p class="why">Saves ${money(Math.max(0, minOnly.interest - av.interest))} in interest versus minimums only. Target order: ${S.debts.slice().sort((a,b)=>b.apr-a.apr).map(d=>escapeHtml(d.name)).join(" β†’ ") || "β€”"}.</p>
    </div>

    <div class="scen">
      <div class="row">
        <h3>Snowball β€” smallest balance first</h3>
        ${best === "snowball" ? '<span class="badge">Fastest</span>' : ""}
      </div>
      <div class="metrics">
        <div><div class="m">${sn.impossible ? "Never" : span(sn.months)}</div><div class="l">Time to zero</div></div>
        <div><div class="m">${sn.impossible ? "β€”" : money(sn.interest)}</div><div class="l">Interest</div></div>
        <div><div class="m">${sn.impossible ? "β€”" : monthsToDate(sn.months)}</div><div class="l">Debt-free</div></div>
      </div>
      <p class="why">Costs ${money(Math.max(0, sn.interest - av.interest))} more than avalanche, but you close an account sooner β€” many people stick with it. Pick one and automate it.</p>
    </div>

    ${dmp ? `
    <h3 class="sechead">If a debt management plan fits</h3>
    <div class="scen">
      <div class="row"><h3>Nonprofit DMP β€” illustrative</h3><span class="badge">Estimate</span></div>
      <div class="metrics">
        <div><div class="m">${money(dmp.pmt)}</div><div class="l">Est. payment / mo</div></div>
        <div><div class="m">${dmp.delta > 0 ? "+" + money(dmp.delta) : money(dmp.delta)}</div><div class="l">Cash flow change</div></div>
        <div><div class="m">60 mo</div><div class="l">Typical term</div></div>
      </div>
      <p class="why">This is math, not an offer: your ${money(c.total)} at a reduced 8% APR over 60 months. Real DMPs depend on which creditors agree, and a nonprofit may charge a modest setup or monthly fee. Get the terms in writing before you enroll β€” and confirm the creditor accepted the plan before you send money.</p>
      <div class="links"><a class="ext" href="https://www.nfcc.org/" target="_blank" rel="noopener">Talk to a nonprofit counselor β†—</a></div>
    </div>` : ""}

    <h3 class="sechead">Your next 3 moves</h3>
    <div class="btnrow" style="margin-bottom:16px">
      <button class="btn ghost" type="button" id="goPrograms">See matched programs β†’</button>
      <button class="btn ghost" type="button" id="goActions">Open 90-day plan β†’</button>
      <button class="btn ghost" type="button" id="copyPlan">Copy plan as text</button>
    </div>
    <div id="copyStatus" class="hint" style="margin-bottom:22px"></div>
  `;

  $("planBody").innerHTML = html;

  $("extra").addEventListener("input", e => {
    S.extra = +e.target.value;
    $("extraOut").textContent = money(S.extra);
    renderPlan();
  });
  $("goPrograms").addEventListener("click", () => switchPane("programs"));
  $("goActions").addEventListener("click", () => switchPane("actions"));
  $("copyPlan").addEventListener("click", copyPlan);

  $("progCount").textContent = "(" + buildPrograms(ctx()).length + ")";
}

function copyPlan(){
  const c = ctx();
  const minOnly = simulate(S.debts, 0, "avalanche");
  const av = simulate(S.debts, S.extra, "avalanche");
  const progs = buildPrograms(c).filter(p => p.tier !== "info").slice(0,8);
  const txt = [
    "CLEARPATH DEBT PLAN β€” " + new Date().toLocaleDateString(),
    "",
    "DEBT: " + money(c.total) + " across " + S.debts.length + " accounts",
    "Minimums: " + money(c.min) + "/mo | Avg APR: " + pct(c.wApr),
    "Free cash flow: " + money(c.free) + "/mo | Debt payments: " + pct(c.dti) + " of take-home",
    "",
    "PAYOFF",
    "Minimums only: " + (minOnly.impossible ? "balance grows" : span(minOnly.months) + ", " + money(minOnly.interest) + " interest"),
    "Avalanche + " + money(S.extra) + "/mo: " + (av.impossible ? "β€”" : span(av.months) + ", " + money(av.interest) + " interest, free by " + monthsToDate(av.months)),
    "",
    "PROGRAMS TO CONTACT",
    ...progs.map((p,i) => (i+1) + ". " + p.name + " β€” " + p.url + (p.phone ? " | " + p.phone : "")),
    "",
    "Generated by ClearPath (educational tool, not financial or legal advice)."
  ].join("\n");
  const done = () => { $("copyStatus").textContent = "Copied. Paste it into your notes or read it to a counselor."; };
  if (navigator.clipboard && navigator.clipboard.writeText){
    navigator.clipboard.writeText(txt).then(done).catch(() => fallbackCopy(txt));
  } else fallbackCopy(txt);
}
function fallbackCopy(txt){
  const ta = document.createElement("textarea");
  ta.value = txt; ta.style.position = "fixed"; ta.style.opacity = "0";
  document.body.appendChild(ta); ta.select();
  try { document.execCommand("copy"); $("copyStatus").textContent = "Copied."; }
  catch(e){ $("copyStatus").textContent = "Copy isn't available in this browser β€” select the text on screen instead."; }
  document.body.removeChild(ta);
}

/* ---------- program catalog ---------- */
function buildPrograms(c){
  const f = S.flags;
  const P = [];
  const add = o => P.push(o);

  /* ---- lower the payments ---- */
  add({
    id:"nfcc", cat:"Lower the payments", tier:"likely",
    name:"Nonprofit credit counseling + debt management plan",
    src:"Nonprofit Β· national",
    why:"You're carrying " + money(c.total) + " on cards at an average " + pct(c.wApr) + ". A DMP is built for this: counselors ask creditors to cut rates and fees, then you make one payment. It's the only formal option that lowers payments without new borrowing.",
    cost:"Low or no cost. Ask for the full fee schedule in writing before you enroll.",
    url:"https://www.nfcc.org/", phone:"800-388-2227"
  });
  add({
    id:"hud", cat:"Lower the payments", tier: f.rent ? "likely" : "check",
    name:"HUD-approved housing counselor (free budget + credit help)",
    src:"Federal Β· HUD network",
    why: f.rent
      ? "You flagged housing pressure. HUD-approved counselors handle budget, credit, eviction and foreclosure issues for free or nearly free, and they're separate from any lender."
      : "Free or low-cost counseling on budget, credit, renting and foreclosure β€” useful second opinion on the DMP pitch you'll hear from a nonprofit. HUD-vetted, not sales-driven.",
    cost:"Free or very low cost. Search by ZIP or call the national line.",
    url:"https://www.consumerfinance.gov/find-a-housing-counselor/", phone:"800-569-4287"
  });

  /* ---- cash flow / benefits ---- */
  add({
    id:"snap", cat:"Free up cash flow", tier: c.income <= c.snapLimit * 0.9 ? "likely" : (c.income <= c.snapLimit * 1.2 ? "check" : "check"),
    name:"SNAP food benefits",
    src:"Federal Β· state-administered",
    why:"For a household of " + S.household + ", the gross monthly income limit is <b>" + money(c.snapLimit) + "</b> (Oct 2026–Sep 2027). Your take-home is " + money(c.income) + ", which is " + (c.income <= c.snapLimit ? "under that line β€” apply and let the state run the deductions" : "above that line, but gross-vs-net, elder and disability deductions can still qualify you") + ". Groceries paid with SNAP are dollars freed up for debt.",
    cost:"Free to apply. Apply in the state where you live; most decisions within 30 days.",
    url:"https://www.fna.usda.gov/snap/recipient/eligibility", phone:"Via your state SNAP office"
  });
  add({
    id:"liheap", cat:"Free up cash flow", tier: f.utilities ? "likely" : "check",
    name:"LIHEAP energy assistance",
    src:"Federal Β· state-administered",
    why: f.utilities
      ? "You flagged a shut-off risk. LIHEAP can pay part of heating/cooling bills and has crisis help for households already disconnected. Applying also often flags you for weatherization."
      : "If your income is modest, LIHEAP can cover part of your energy bill β€” money that stops competing with your card payment.",
    cost:"Free. Crisis assistance is prioritized when heat or cooling is at risk.",
    url:"https://acf.gov/ocs/programs-services/liheap", phone:"866-674-6327"
  });
  add({
    id:"benefitfinder", cat:"Free up cash flow", tier:"likely",
    name:"USAGov Benefit Finder",
    src:"Federal Β· official screening tool",
    why:"One questionnaire across food, housing, health, utilities, disability, retirement and veterans benefits. Benefits.gov was retired β€” this is the official replacement, so skip any site still sending you there.",
    cost:"Free.",
    url:"https://www.usa.gov/benefit-finder"
  });
  add({
    id:"211", cat:"Free up cash flow", tier:"likely",
    name:"211 β€” local emergency help",
    src:"Nonprofit Β· nationwide network",
    why:"The fastest route to local rent, utility, food, transportation and one-time emergency cash. Real humans, 24/7, confidential" + (f.job ? ", and they can connect you to job and training programs." : "."),
    cost:"Free. Dial 211 or search your local agency online.",
    url:"https://211.org/", phone:"211"
  });
  add({
    id:"findhelp", cat:"Free up cash flow", tier:"check",
    name:"findhelp β€” search free services by ZIP",
    src:"Nonprofit Β· national directory",
    why:"Searchable database of food pantries, rental funds, clinics and legal clinics near you, filterable by income. Good when 211 has a wait.",
    cost:"Free.",
    url:"https://www.findhelp.org/"
  });
  add({
    id:"medicaid", cat:"Free up cash flow", tier: f.medical ? "likely" : "check",
    name:"Medicaid / Marketplace health coverage",
    src:"Federal–state",
    why: f.medical
      ? "Medical bills and coverage gaps are one of the top reasons card balances climb. Screening for Medicaid (free or near-free) or a subsidized Marketplace plan stops new medical debt from landing on a card."
      : "Worth a check: a subsidized plan or Medicaid can be cheaper than what you're paying now, and the savings are monthly cash flow.",
    cost:"Free screening. Medicaid cost depends on income; Marketplace premiums are subsidized by income.",
    url:"https://www.healthcare.gov/"
  });

  /* ---- credit & banking ---- */
  add({
    id:"acr", cat:"Credit & banking", tier:"likely",
    name:"Free credit reports (all three bureaus)",
    src:"Federal right Β· AnnualCreditReport.com",
    why:"You can pull reports weekly, free, at the only site authorized by federal law. Check for collections you don't recognize before you pay anyone β€” disputing errors is free and doesn't need a credit repair company.",
    cost:"Free. Never pay for this report.",
    url:"https://www.annualcreditreport.com/", phone:"877-322-8228"
  });
  add({
    id:"bankon", cat:"Credit & banking", tier: f.unbanked ? "likely" : "check",
    name:"Bank On certified checking account",
    src:"Nonprofit standard Β· 500+ banks & credit unions",
    why: f.unbanked
      ? "You said you've been denied an account. Bank On certified accounts are designed for people with past banking or credit trouble: no overdraft fees, low monthly cost, and they accept alternative ID. A safe account also protects your paycheck from check cashers."
      : "If your bank charges overdraft or monthly fees, a Bank On certified account is a cheap backup β€” no overdraft fees, and it works with a thin credit file.",
    cost:"Low or no monthly fee. No overdraft fees by design.",
    url:"https://joinbankon.org/accounts/"
  });
  add({
    id:"repair", cat:"Credit & banking", tier:"info",
    name:"Fix your own credit β€” free, legally",
    src:"Federal guidance Β· CFPB",
    why:"Nobody can delete accurate negative history. Disputing errors directly with the bureaus and the furnisher is free, and the law requires an investigation. Anyone charging upfront for credit repair is breaking the rule.",
    cost:"Free.",
    url:"https://www.consumerfinance.gov/ask-cfpb/how-can-i-tell-a-credit-repair-scam-from-a-reputable-credit-counselor-en-1343/"
  });

  /* ---- legal ---- */
  if (f.collector || f.sued || f.behind){
    add({
      id:"fdcpa", cat:"Legal protection", tier: f.collector || f.sued ? "likely" : "check",
      name:"Know your rights with debt collectors",
      src:"Federal law Β· CFPB",
      why:"The Fair Debt Collection Practices Act limits when and how collectors can contact you, bans threats and lies, and gives you the right to demand written verification of the debt. Nothing here requires a lawyer to start.",
      cost:"Free.",
      url:"https://www.consumerfinance.gov/consumer-tools/debt-collection/know-your-rights-when-a-debt-collector-calls/"
    });
  }
  if (f.sued || c.dti > 45 || f.behind){
    add({
      id:"lsc", cat:"Legal protection", tier: f.sued ? "likely" : "check",
      name:"Free civil legal aid near you",
      src:"Federal Β· Legal Services Corporation",
      why: f.sued
        ? "You flagged a lawsuit or garnishment threat. <b>Do not ignore a court date</b> β€” a default judgment can lead to wage garnishment. LSC-funded programs in every state handle consumer debt defense for people under roughly 125% of the poverty line."
        : "If a collector sues, or you're deciding between a DMP and bankruptcy, local legal aid gives you a free read on your exposure.",
      cost:"Free if you qualify on income.",
      url:"https://www.lsc.gov/about-lsc/what-legal-aid/i-need-legal-help"
    });
  }
  if (f.sued || c.total > S.income * 6 || f.behind){
    add({
      id:"bankruptcy", cat:"Legal protection", tier:"check",
      name:"Bankruptcy basics + fee waiver",
      src:"Federal courts",
      why:"Not a first step, but a real one to understand. Chapter 7 can wipe most unsecured card debt; filing fees can be waived below 150% of the poverty line, and you're required to take a credit counseling course first β€” which is often free or low cost.",
      cost:"Chapter 7 court fee is $338; waiver available for low income. Credit counseling course $0–$50, also waivable.",
      url:"https://www.uscourts.gov/court-programs/bankruptcy/bankruptcy-basics/chapter-7-bankruptcy-basics"
    });
    add({
      id:"upsolve", cat:"Legal protection", tier: S.income < c.snapLimit * 1.6 ? "check" : "info",
      name:"Upsolve β€” free Chapter 7 filing help",
      src:"Nonprofit Β· 501(c)(3)",
      why:"Free nonprofit tool that prepares Chapter 7 forms for simple, low-income cases β€” no attorney fee. It screens out complicated cases, and it is not your lawyer.",
      cost:"Free tool. Court fees still apply unless waived.",
      url:"https://upsolve.org/"
    });
  }

  /* ---- taxes & student loans ---- */
  if (f.tax){
    add({
      id:"irs", cat:"Tax and loans", tier:"likely",
      name:"IRS online payment plan",
      src:"Federal Β· IRS",
      why:"You can self-set an installment agreement online in minutes instead of facing a levy. If you owe $50,000 or less, you can usually get a monthly plan; setup fees are waived for low-income filers.",
      cost:"$0 setup for short-term plans; long-term $29–$69, waived or reduced for low income.",
      url:"https://www.irs.gov/payments/online-payment-agreement-application", phone:"800-829-1040"
    });
  }
  if (f.student){
    add({
      id:"idr", cat:"Tax and loans", tier:"likely",
      name:"Federal student loan income-driven repayment",
      src:"Federal Β· StudentAid.gov",
      why:"An income-driven plan can drop a federal student loan payment to a small share of discretionary income β€” often $0 β€” which frees real money for the cards. Applying is free and you never pay a company to do it.",
      cost:"Free to apply. Never pay a third party for this form.",
      url:"https://studentaid.gov/idr"
    });
  }

  /* ---- accountability ---- */
  if (f.collector || f.behind || c.dti > 40){
    add({
      id:"complaint", cat:"Legal protection", tier:"check",
      name:"File a complaint with the CFPB",
      src:"Federal regulator",
      why:"For harassment, wrong balances, ignored disputes or a card issuer that won't honor a hardship agreement. Companies generally must respond within 15 days, and the complaint is public data.",
      cost:"Free. Takes about 10 minutes online.",
      url:"https://www.consumerfinance.gov/complaint/", phone:"855-411-2372"
    });
  }

  const rank = {likely:0, check:1, info:2};
  return P.sort((a,b) => rank[a.tier] - rank[b.tier]);
}

const CATS = ["Lower the payments","Free up cash flow","Legal protection","Credit & banking","Tax and loans"];

function renderPrograms(){
  const c = ctx();
  const all = buildPrograms(c);

  // filters
  const counts = {};
  all.forEach(p => counts[p.cat] = (counts[p.cat]||0) + 1);
  $("progFilters").innerHTML =
    `<button class="chip" data-f="all" aria-pressed="${S.filter==="all"}">All ${all.length}</button>` +
    CATS.filter(k => counts[k]).map(k =>
      `<button class="chip" data-f="${k}" aria-pressed="${S.filter===k}">${k} ${counts[k]}</button>`
    ).join("");

  const list = S.filter === "all" ? all : all.filter(p => p.cat === S.filter);
  const groups = {};
  list.forEach(p => { (groups[p.cat] = groups[p.cat] || []).push(p); });

  let html = "";
  if (!list.length) html = `<p class="hint">Nothing in that category for your inputs. Switch back to All.</p>`;

  Object.keys(groups).forEach(cat => {
    html += `<div class="cathead">${cat}</div>`;
    groups[cat].forEach(p => {
      const tierLabel = p.tier === "likely" ? "Likely fit" : p.tier === "check" ? "Worth checking" : "Know the rules";
      html += `
        <div class="prog">
          <div class="top">
            <h3>${p.name}</h3>
            <span class="tier ${p.tier}">${tierLabel}</span>
          </div>
          <div class="src">${p.src}</div>
          <p class="why">${p.why}</p>
          <div class="cost">πŸ’‘ ${p.cost}</div>
          <div class="links">
            <a class="ext" href="${p.url}" target="_blank" rel="noopener">Official page β†—</a>
            ${p.phone ? `<a class="tel" href="tel:${p.phone.replace(/[^0-9]/g,"")}">Call ${p.phone}</a>` : ""}
          </div>
        </div>`;
    });
  });

  $("programsBody").innerHTML = html;
  $("progCount").textContent = "(" + all.length + ")";

  $("progFilters").querySelectorAll("[data-f]").forEach(b => b.addEventListener("click", () => {
    S.filter = b.dataset.f; renderPrograms();
  }));
}

/* ---------- actions ---------- */
function renderActions(){
  const c = ctx();
  const f = S.flags;
  const steps = [];

  steps.push({
    k:"a1", when:"Today", h:"Write down every debt and the real interest rate",
    p:"Use the statement balance, not the credit limit. Then pull all three credit reports free β€” you're entitled to them weekly, and collections you don't recognize change the whole plan.",
    link:["Open AnnualCreditReport.com","https://www.annualcreditreport.com/"]
  });
  steps.push({
    k:"a2", when:"Today", h:"Call 211 and apply for the two benefits you're most likely to get",
    p:"Dial 211 for local rent, utility and food help, then run the USAGov Benefit Finder. Every dollar covered by a benefit is a dollar that can go to the highest-rate card instead.",
    link:["USAGov Benefit Finder","https://www.usa.gov/benefit-finder"]
  });
  if (c.income <= c.snapLimit * 1.2 || f.kids){
    steps.push({
      k:"a3", when:"This week", h:"File the SNAP application in your state",
      p:"Your household size " + S.household + " limit is " + money(c.snapLimit) + " gross per month. Apply online through your state agency β€” decisions usually land within 30 days, and expedited cases can be 7 days.",
      link:["SNAP eligibility","https://www.fna.usda.gov/snap/recipient/eligibility"]
    });
  }
  if (f.utilities){
    steps.push({
      k:"a4", when:"This week", h:"Call LIHEAP before the shut-off date",
      p:"Ask specifically about <b>crisis assistance</b> β€” it moves faster when service is already off or scheduled for disconnection. Have your bill and income proof ready.",
      link:["LIHEAP","https://acf.gov/ocs/programs-services/liheap"]
    });
  }
  steps.push({
    k:"a5", when:"This week", h:"Book one nonprofit credit counseling session",
    p:"Free or low cost, one hour, and they'll build a budget and tell you whether a DMP actually lowers your payment. Ask three questions: what's the fee, which creditors have agreed, and what happens to my credit.",
    link:["Find an NFCC counselor","https://www.nfcc.org/"]
  });
  steps.push({
    k:"a6", when:"This week", h:"Call each card issuer and ask for hardship",
    p:"Issuers have programs that never appear on the website: APR reduction, fixed payment plans, and short forbearances. Use the script in the box below. Get names, dates and reference numbers.",
    script:true
  });
  if (f.collector || f.sued){
    steps.push({
      k:"a7", when:"Immediately", h:"Respond to the collector or the court β€” in writing",
      p:"Ask for written verification of the debt, and never miss a court date. A default judgment is how a card balance turns into wage garnishment. Legal aid is free if you qualify.",
      link:["Find free legal aid","https://www.lsc.gov/about-lsc/what-legal-aid/i-need-legal-help"]
    });
  }
  steps.push({
    k:"a8", when:"Week 2", h:"Automate the avalanche payment",
    p:"Set the extra amount to auto-pay on the highest-APR card the day after payday, and keep every other card on autopay for its minimum. Automation beats motivation.",
    link:null
  });
  if (f.tax) steps.push({ k:"a9", when:"Week 2", h:"Set up an IRS payment plan online", p:"Cheaper and calmer than an enforced collection action, and low-income filers get the setup fee waived.", link:["IRS payment plan","https://www.irs.gov/payments/online-payment-agreement-application"] });
  if (f.student) steps.push({ k:"a10", when:"Week 2", h:"Apply for income-driven repayment", p:"Free on StudentAid.gov. If the payment drops, redirect the difference to the highest-rate card, not to new spending.", link:["StudentAid.gov IDR","https://studentaid.gov/idr"] });
  steps.push({
    k:"a11", when:"Day 60", h:"Check what actually changed",
    p:"Did the DMP start? Did the benefits land? Did any balance go up anyway? If nothing moved, that's your signal to get a legal aid opinion on bankruptcy before the balances grow further.",
    link:["Bankruptcy basics","https://www.uscourts.gov/court-programs/bankruptcy/bankruptcy-basics/chapter-7-bankruptcy-basics"]
  });
  steps.push({
    k:"a12", when:"Day 90", h:"Protect the progress",
    p:"Build a $500 buffer before you increase card payments, so the next emergency doesn't go back on a card at 28%. Keep the oldest account open and in good standing β€” length of history is a big part of the score.",
    link:null
  });

  let html = `<div class="agentnote" style="margin-top:16px"><div class="dot"></div><p>Twelve steps, ordered by what moves money fastest. Tap a step to check it off β€” your list stays here while the tab is open.</p></div><ol class="steps">`;
  steps.forEach(s => {
    const done = S.done[s.k] ? "done" : "";
    html += `<li class="${done}" data-step="${s.k}">
      <h4>${s.h} <span class="when">${s.when}</span></h4>
      <p>${s.p}</p>
      ${s.link ? `<a href="${s.link[1]}" target="_blank" rel="noopener">${s.link[0]} β†—</a>` : ""}
      ${s.script ? scriptBox() : ""}
      <label class="tick"><input type="checkbox" data-tick="${s.k}" ${S.done[s.k]?"checked":""} /> Mark done</label>
    </li>`;
  });
  html += `</ol>`;

  html += `
    <h3 class="sechead">Two more things worth doing</h3>
    <div class="prog">
      <h3>Ask for a "hardship" rate cut in writing</h3>
      <p class="why">A written request (email or secure message) creates a record. Ask for a temporary APR reduction to a specific number, a fixed payment for 6–12 months, and waiver of late fees. If they refuse, that refusal is useful evidence in a CFPB complaint.</p>
      <div class="links"><a class="ext" href="https://www.consumerfinance.gov/complaint/" target="_blank" rel="noopener">CFPB complaint form β†—</a></div>
    </div>
    <div class="prog">
      <h3>Do not pay anyone to "fix" this</h3>
      <p class="why">Legitimate help is free or low cost: nonprofit counseling, HUD counselors, legal aid, 211. Debt settlement companies that charge before settling, tell you to stop paying creditors, or promise pennies on the dollar are the ones the CFPB warns about.</p>
      <div class="links"><a class="ext" href="https://www.consumerfinance.gov/ask-cfpb/how-can-i-tell-a-credit-repair-scam-from-a-reputable-credit-counselor-en-1343/" target="_blank" rel="noopener">How to spot the scam β†—</a></div>
    </div>`;

  $("actionsBody").innerHTML = html;
  $("actionsBody").querySelectorAll("[data-tick]").forEach(cb => cb.addEventListener("change", e => {
    S.done[e.target.dataset.tick] = e.target.checked;
    e.target.closest("li").classList.toggle("done", e.target.checked);
  }));
}

function scriptBox(){
  return `<div class="script" style="margin-top:12px">
    <div class="sl">Phone script</div>
    <q>Hi, I'm calling about my account ending in ____. My income changed and I'm at risk of missing payments β€” I want to keep this account in good standing. Can you review me for a hardship program: a lower APR, a fixed payment plan, or a short forbearance? Please send the terms in writing before I agree. Can I get a reference number for this call?</q>
  </div>`;
}

/* ---------- rights ---------- */
function renderRights(){
  $("rightsBody").innerHTML = `
    <div class="warn" style="margin-top:16px">
      <h4>There is no government program that pays off your credit cards</h4>
      <p>If a company says a "new government program" will wipe out card debt, it's a sales line the CFPB specifically warns about. Real government help is indirect: food, energy, housing, health coverage and legal aid that free up the cash you're already earning.</p>
    </div>

    <div class="prog">
      <h3>What collectors legally cannot do</h3>
      <p class="why">Under the Fair Debt Collection Practices Act: no calls before 8am or after 9pm, no calls at work once you say stop, no harassment, no lies about arrest or lawsuits, no discussing the debt with your family or employer. You can demand written verification of the debt, and you can tell them to stop contacting you β€” though that doesn't erase the debt.</p>
      <div class="links"><a class="ext" href="https://www.consumerfinance.gov/consumer-tools/debt-collection/know-your-rights-when-a-debt-collector-calls/" target="_blank" rel="noopener">CFPB collector rights β†—</a></div>
    </div>

    <div class="prog">
      <h3>Your credit repair rights</h3>
      <p class="why">Accurate negative information cannot be removed early β€” not by you, not by anyone. What you <em>can</em> do for free: dispute errors with both the bureau and the company that reported it, and they must investigate, usually within 30 days. Credit repair companies cannot charge you before services are delivered.</p>
      <div class="links"><a class="ext" href="https://www.consumerfinance.gov/ask-cfpb/how-can-i-tell-a-credit-repair-scam-from-a-reputable-credit-counselor-en-1343/" target="_blank" rel="noopener">Scam warning signs β†—</a></div>
    </div>

    <div class="prog">
      <h3>If you're sued</h3>
      <p class="why">Answer the complaint by the deadline printed on it, even if you think the debt is wrong. Ignoring it produces a default judgment, which is the legal doorway to wage garnishment and bank levies. Free legal aid exists in every state for low-income defendants.</p>
      <div class="links">
        <a class="ext" href="https://www.lsc.gov/about-lsc/what-legal-aid/i-need-legal-help" target="_blank" rel="noopener">Find legal aid β†—</a>
        <a class="tel" href="https://www.lawhelp.org/" target="_blank" rel="noopener">LawHelp.org forms</a>
      </div>
    </div>

    <div class="prog">
      <h3>Debt settlement vs. a debt management plan</h3>
      <p class="why">Settlement means paying less than you owe, usually after you stop paying β€” which adds late fees, hurts your score, and can trigger a lawsuit. A DMP means paying in full but with lower rates and one payment. The CFPB treats them very differently for good reason.</p>
      <div class="links"><a class="ext" href="https://www.consumerfinance.gov/ask-cfpb/what-is-credit-counseling-en-1451/" target="_blank" rel="noopener">CFPB: credit counseling β†—</a></div>
    </div>

    <div class="note">
      <strong>One rule that protects almost everyone:</strong> never pay an upfront fee to someone promising to reduce your debt, and never stop paying creditors because a company told you to. Both are the standard opening moves of a debt relief scam.
    </div>
  `;
}

/* ---------- chat agent ---------- */
const QUICK = [
  "Lower my payment",
  "A collector keeps calling",
  "Help with food",
  "My rent is behind",
  "Student loans",
  "Should I do bankruptcy?",
  "Is this a scam?",
  "Fix my credit score"
];

function renderQuick(){
  $("quick").innerHTML = QUICK.map(q => `<button type="button">${q}</button>`).join("");
  $("quick").querySelectorAll("button").forEach(b => b.addEventListener("click", () => ask(b.textContent)));
}

function introMsg(){
  if (!S.ran) return "Before we start: add your cards and income on the first screen and I can answer with your actual numbers. Meanwhile β€” what's the most urgent thing: the payment size, a collector, or keeping food and rent covered?";
  const c = ctx();
  return "I've got your numbers: <b>" + money(c.total) + "</b> on cards, <b>" + money(c.min) + "</b> in minimums, and about <b>" + money(c.free) + "</b> of free cash flow. Ask me anything β€” or tap a prompt below.";
}

function botSay(html){
  const log = $("log");
  const d = document.createElement("div");
  d.className = "msg bot";
  d.innerHTML = html;
  log.appendChild(d);
  log.scrollTop = log.scrollHeight;
}
function meSay(txt){
  const log = $("log");
  const d = document.createElement("div");
  d.className = "msg me";
  d.textContent = txt;
  log.appendChild(d);
  log.scrollTop = log.scrollHeight;
}

function sendChat(){
  const v = $("chatIn").value.trim();
  if (!v) return;
  $("chatIn").value = "";
  ask(v);
}

function ask(text){
  meSay(text);
  const reply = answer(text.toLowerCase());
  setTimeout(() => botSay(reply), 320);
}

function answer(q){
  const c = S.ran ? ctx() : { total:0, min:0, wApr:0, free:0, dti:0, income:S.income||0, snapLimit:SNAP_LIMIT[1] };
  const f = S.flags;
  const has = (...keys) => keys.some(k => q.includes(k));

  if (has("lower","payment","reduce","afford","hardship","struggling")){
    return "<b>Three ways to lower the payment, in order of safety.</b><br><br>1. <b>Hardship program with the issuer</b> β€” call the number on the back of the card, ask for a lower APR or a fixed payment plan, get it in writing. Free.<br>2. <b>Nonprofit DMP</b> β€” " + (c.total ? "on " + money(c.total) + " at " + pct(c.wApr) + ", a 60-month plan at a reduced rate could land near " + money(c.total*0.0166) + "–" + money(c.total*0.021) + " per month versus " + money(c.min) + " now. " : "") + "Creditors have to agree, so ask which ones already have.<br>3. <b>Benefits first</b> β€” SNAP, LIHEAP and Medicaid coverage free up cash without touching your credit.<br><br><a href='https://www.nfcc.org/' target='_blank' rel='noopener'>NFCC counselor locator β†—</a> Β· <a href='https://acf.gov/ocs/programs-services/liheap' target='_blank' rel='noopener'>LIHEAP β†—</a>";
  }
  if (has("collector","calling","harass","calls","garnish")){
    return "<b>You have more leverage than the calls suggest.</b> Under the FDCPA they can't call before 8am or after 9pm, can't call your workplace after you tell them to stop, and can't threaten arrest. Ask for the debt in writing β€” name of the original creditor, amount, and how to dispute it.<br><br>If they won't verify it, or they're abusive: <a href='https://www.consumerfinance.gov/complaint/' target='_blank' rel='noopener'>file a CFPB complaint β†—</a>. If there's a court date, that is the one thing you cannot ignore β€” <a href='https://www.lsc.gov/about-lsc/what-legal-aid/i-need-legal-help' target='_blank' rel='noopener'>free legal aid β†—</a>.";
  }
  if (has("food","grocer","snap","eat","hungry")){
    const over = c.income > c.snapLimit;
    return "<b>SNAP is the biggest lever here.</b> For " + S.household + " in your household the gross monthly limit is <b>" + money(c.snapLimit) + "</b>. " + (c.income ? "Your take-home is " + money(c.income) + ", so you're " + (over ? "above it on paper β€” but deductions for rent, childcare, elder or disability status can still qualify you. Apply anyway; the state runs the math." : "under it β€” apply this week.") : "Apply even if you think you're close; the state runs the math, not you.") + "<br><br><a href='https://www.fna.usda.gov/snap/recipient/eligibility' target='_blank' rel='noopener'>SNAP eligibility &amp; how to apply β†—</a> Β· or dial <b>211</b> for pantries today.";
  }
  if (has("rent","evict","landlord","housing","mortgage")){
    return "<b>Housing money moves faster through local channels than federal ones.</b> Dial <b>211</b> or search <a href='https://www.findhelp.org/' target='_blank' rel='noopener'>findhelp.org β†—</a> for emergency rent funds in your ZIP. A HUD-approved counselor can also negotiate with a landlord or servicer, free: <a href='https://www.consumerfinance.gov/find-a-housing-counselor/' target='_blank' rel='noopener'>find a HUD counselor β†—</a>.<br><br>Practical: apply before the notice expires, and get any agreement in writing.";
  }
  if (has("utility","electric","heat","energy","shut off","shutoff","water bill")){
    return "<b>LIHEAP, and ask for crisis assistance.</b> Crisis funds are prioritized when service is already off or scheduled for disconnection, and many states take applications year-round. Have the bill and proof of income ready.<br><br><a href='https://acf.gov/ocs/programs-services/liheap' target='_blank' rel='noopener'>LIHEAP official page β†—</a> Β· hotline <b>866-674-6327</b>. Also call the utility directly and ask for a payment arrangement β€” most have one they don't advertise.";
  }
  if (has("student","school loan","idr")){
    return "<b>Federal loans have the best relief options in consumer debt.</b> Income-driven repayment caps the payment at a share of discretionary income and can be $0. It's free to apply on StudentAid.gov β€” never pay a company for this form.<br><br><a href='https://studentaid.gov/idr' target='_blank' rel='noopener'>Income-driven repayment β†—</a><br><br>If the payment drops, send the difference to the highest-APR card, not to new spending. Private loans are different β€” those need a hardship call to the servicer.";
  }
  if (has("bankrupt","chapter","wipe","give up")){
    return "<b>Worth understanding, not a first move.</b> Chapter 7 can clear most unsecured card debt, and the $338 court fee can be waived below 150% of the poverty line. You must complete a credit counseling course first β€” usually $0–$50, also waivable.<br><br><a href='https://www.uscourts.gov/court-programs/bankruptcy/bankruptcy-basics/chapter-7-bankruptcy-basics' target='_blank' rel='noopener'>Federal courts: Chapter 7 basics β†—</a> Β· <a href='https://upsolve.org/' target='_blank' rel='noopener'>Upsolve free filing help β†—</a><br><br>Before filing, get a free legal aid opinion on what you'd lose. Some debts β€” recent taxes, student loans, support β€” don't discharge.";
  }
  if (has("scam","legit","trust","too good","guarantee")){
    return "<b>The tell is always the same: a fee up front, or a promise.</b> Nobody can legally delete accurate negative history, and no government program pays off credit cards. Companies that say otherwise are selling you something.<br><br>Legit help is free or low cost: nonprofit counseling, HUD counselors, legal aid, 211. <a href='https://www.consumerfinance.gov/ask-cfpb/how-can-i-tell-a-credit-repair-scam-from-a-reputable-credit-counselor-en-1343/' target='_blank' rel='noopener'>CFPB's warning signs β†—</a>";
  }
  if (has("credit score","credit report","fix my credit","dispute","increase score")){
    return "<b>Free and legal, in this order:</b><br>1. Pull all three reports at <a href='https://www.annualcreditreport.com/' target='_blank' rel='noopener'>AnnualCreditReport.com β†—</a> β€” weekly, free, the only federally authorized site.<br>2. Dispute anything wrong directly with the bureau <em>and</em> the company that reported it. They must investigate, usually in 30 days.<br>3. Lower utilization by paying before the statement date, not just before the due date.<br><br>There is no legal shortcut that removes accurate history early β€” <a href='https://www.consumerfinance.gov/ask-cfpb/how-can-i-tell-a-credit-repair-scam-from-a-reputable-credit-counselor-en-1343/' target='_blank' rel='noopener'>that's the scam pitch β†—</a>.";
  }
  if (has("tax","irs")){
    return "<b>Deal with the IRS before it becomes a levy.</b> You can set up an installment agreement online in about ten minutes, and if you owe $50,000 or less you'll usually be approved on the spot. Low-income filers get the setup fee waived.<br><br><a href='https://www.irs.gov/payments/online-payment-agreement-application' target='_blank' rel='noopener'>IRS online payment plan β†—</a>";
  }
  if (has("job","unemploy","income","lost my")){
    return "<b>Two tracks at once.</b> Immediate: dial <b>211</b> for local emergency funds and <a href='https://www.usa.gov/benefit-finder' target='_blank' rel='noopener'>USAGov's Benefit Finder β†—</a> for unemployment, food and health coverage. Structural: ask your card issuers for a temporary forbearance <em>before</em> you miss a payment β€” that call is much easier now than after 30 days late.<br><br>Also check <a href='https://joinbankon.org/accounts/' target='_blank' rel='noopener'>Bank On β†—</a> if fees are eating your balance.";
  }
  if (has("settle","settlement","pay less","pennies")){
    return "<b>Settlement is real but risky, and the sales version is usually a trap.</b> Legitimate settlement means paying a lump sum less than you owe β€” which requires stopping payments, triggering late fees, score damage and possible lawsuits. Companies can't charge you before they settle at least one debt.<br><br>A DMP is usually the safer version of \"pay less per month\": <a href='https://www.nfcc.org/' target='_blank' rel='noopener'>nonprofit counselors β†—</a> Β· <a href='https://www.consumerfinance.gov/ask-cfpb/what-is-credit-counseling-en-1451/' target='_blank' rel='noopener'>CFPB explainer β†—</a>";
  }
  if (has("bank account","checking","denied","chex","unbanked")){
    return "<b>You can usually get a real account even with a bad banking history.</b> Bank On certified accounts are offered by 500+ banks and credit unions with no overdraft fees and low monthly costs, and they're built for people with past account closures.<br><br><a href='https://joinbankon.org/accounts/' target='_blank' rel='noopener'>Find a certified account β†—</a> β€” it keeps your paycheck out of check-cashing fees.";
  }

  // default
  if (!S.ran){
    return "Add your cards and income first and I'll answer with real numbers. In the meantime, the two free things almost everyone should do: pull your reports at <a href='https://www.annualcreditreport.com/' target='_blank' rel='noopener'>AnnualCreditReport.com β†—</a>, and dial <b>211</b> to see what local help exists.";
  }
  const c2 = ctx();
  return "Here's what I'd do with your numbers (<b>" + money(c2.total) + "</b> on cards, <b>" + money(c2.min) + "</b> in minimums, <b>" + money(c2.free) + "</b> free cash flow):<br><br>1. One call to a nonprofit counselor this week β€” <a href='https://www.nfcc.org/' target='_blank' rel='noopener'>NFCC β†—</a><br>2. Apply for the benefits you likely qualify for β€” <a href='https://www.usa.gov/benefit-finder' target='_blank' rel='noopener'>USAGov Benefit Finder β†—</a><br>3. Automate the avalanche payment on your highest-APR card.<br><br>Ask me about collectors, food help, rent, student loans, taxes, bankruptcy or scams.";
}

/* ---------- boot ---------- */
init();
</script>
</body>
</html>