File size: 62,537 Bytes
9095085
 
 
84c5f94
9095085
 
7630609
9095085
 
7630609
9095085
 
7630609
9095085
 
84c5f94
 
 
 
 
 
 
 
7630609
84c5f94
7630609
 
 
 
 
 
9095085
 
7630609
84c5f94
9095085
 
7630609
6795a21
7630609
 
 
 
 
 
6795a21
7630609
 
6795a21
 
7630609
 
6795a21
7630609
 
9095085
 
6795a21
7630609
 
 
 
 
 
 
 
 
 
 
 
 
9095085
 
6795a21
7630609
 
 
 
 
 
 
9095085
 
6795a21
 
 
 
 
8fe1fed
6795a21
 
 
9095085
 
 
 
f57f6c4
9095085
 
f57f6c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9095085
 
 
6795a21
9095085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6795a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9095085
 
 
 
6795a21
 
9095085
11d808e
6795a21
11d808e
 
6795a21
 
 
 
11d808e
 
7630609
 
 
 
11d808e
7630609
 
 
 
 
 
 
 
 
 
 
 
9095085
 
 
bd920df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d808e
9095085
396465d
 
 
 
 
 
 
 
9095085
396465d
 
 
 
 
 
9095085
 
0ab0741
 
 
 
 
 
396465d
 
 
 
 
 
 
 
9095085
11d808e
9095085
 
 
 
11d808e
 
9095085
 
 
7630609
 
 
 
 
f57f6c4
9095085
 
396465d
 
f57f6c4
 
 
 
 
 
 
396465d
 
9095085
 
 
 
 
 
 
 
 
 
396465d
 
 
 
9095085
 
 
396465d
 
9095085
 
 
 
396465d
 
9095085
 
 
 
 
396465d
 
 
 
9095085
 
 
 
396465d
 
9095085
 
 
 
 
 
 
 
 
396465d
 
 
 
9095085
 
 
 
0ab0741
 
 
 
 
 
396465d
 
9095085
 
 
 
396465d
 
9095085
 
 
 
396465d
 
 
 
 
9095085
6795a21
 
 
396465d
8fe1fed
6795a21
 
8fe1fed
6795a21
 
9e2a43d
6795a21
 
9e2a43d
 
 
6795a21
 
 
 
9e2a43d
6795a21
9e2a43d
 
 
 
 
 
 
 
 
 
 
9095085
6795a21
9095085
6795a21
 
9095085
 
 
6795a21
 
11d808e
6795a21
396465d
 
 
9095085
 
11d808e
 
9095085
396465d
 
 
9095085
 
6795a21
928cf68
 
9095085
 
f57f6c4
9095085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d808e
9095085
11d808e
 
 
 
 
 
9095085
c32db91
11d808e
 
 
 
 
 
 
 
9095085
 
11d808e
 
 
 
 
 
9095085
 
11d808e
 
 
 
 
 
9095085
 
6795a21
928cf68
9095085
f57f6c4
9095085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce5f3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fe1fed
ce5f3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6795a21
9095085
6795a21
 
 
 
 
 
9095085
 
 
f57f6c4
6795a21
 
9095085
 
c32db91
9095085
 
 
75ecc2d
 
 
9095085
 
 
7630609
6795a21
7630609
6795a21
7630609
 
 
9095085
 
6795a21
 
 
 
9095085
6795a21
 
 
9095085
 
 
 
6795a21
9095085
 
 
9e2a43d
9095085
11d808e
 
9095085
 
11d808e
 
9095085
 
 
11d808e
 
9095085
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6795a21
9095085
9e2a43d
6795a21
 
 
9095085
7630609
6795a21
9095085
11d808e
6795a21
7630609
 
6795a21
7630609
6795a21
7630609
 
6795a21
7630609
 
 
6795a21
 
7630609
 
 
 
 
6795a21
f2314d2
 
 
 
 
 
 
 
 
6795a21
f2314d2
6795a21
7630609
6795a21
7630609
 
6795a21
 
 
8fe1fed
6795a21
 
 
 
 
 
 
7630609
 
6795a21
 
 
 
 
 
 
 
 
 
7630609
 
6795a21
 
7630609
6795a21
 
 
8fe1fed
6795a21
7630609
6795a21
 
 
 
 
 
 
 
 
7630609
 
6795a21
 
7630609
 
6795a21
7630609
 
75ecc2d
6795a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ecc2d
6795a21
 
75ecc2d
6795a21
 
75ecc2d
6795a21
 
 
8fe1fed
6795a21
 
 
75ecc2d
ddc8c5c
 
21b7b35
 
 
 
 
 
 
 
 
 
6795a21
21b7b35
 
 
 
 
 
 
 
 
ddc8c5c
21b7b35
 
ddc8c5c
 
21b7b35
 
 
 
ddc8c5c
 
 
 
 
21b7b35
 
 
 
 
ddc8c5c
21b7b35
 
 
 
 
 
ddc8c5c
 
21b7b35
6795a21
21b7b35
ddc8c5c
 
21b7b35
 
ddc8c5c
 
 
21b7b35
ddc8c5c
 
21b7b35
 
 
 
 
 
 
 
 
 
 
ddc8c5c
21b7b35
 
 
 
6795a21
f57f6c4
 
 
 
 
 
21b7b35
 
 
ddc8c5c
6795a21
 
ddc8c5c
6795a21
ddc8c5c
6795a21
ddc8c5c
 
6795a21
21b7b35
 
ddc8c5c
21b7b35
 
 
6795a21
 
 
ddc8c5c
6795a21
ddc8c5c
 
21b7b35
6795a21
21b7b35
6795a21
21b7b35
6795a21
21b7b35
 
 
 
 
 
 
6795a21
21b7b35
 
 
 
 
6795a21
21b7b35
6795a21
21b7b35
6795a21
21b7b35
 
 
 
 
 
 
 
 
 
 
 
 
 
6795a21
 
 
 
 
 
 
 
 
21b7b35
 
6795a21
21b7b35
6795a21
21b7b35
6795a21
 
21b7b35
 
 
 
 
 
6795a21
21b7b35
 
 
 
 
 
6795a21
 
21b7b35
6795a21
21b7b35
6795a21
21b7b35
 
6795a21
21b7b35
 
ddc8c5c
6795a21
21b7b35
ddc8c5c
21b7b35
 
 
 
 
 
6795a21
 
 
 
 
ddc8c5c
21b7b35
ddc8c5c
 
21b7b35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddc8c5c
21b7b35
 
ddc8c5c
 
 
 
 
 
 
 
 
 
 
7630609
6795a21
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
import streamlit as st
import json
import datetime
import os
import pandas as pd
import plotly.graph_objects as go
import requests

# ---------------------------------------------------------------------------
# Google Sheets Backend (public sheet, no credentials)
# ---------------------------------------------------------------------------

SHEET_CSV_TMPL = "https://docs.google.com/spreadsheets/d/{sheet_id}/gviz/tq?tqx=out:csv"


def _get_secret(key, default=""):
    """Read from st.secrets (local/Streamlit Cloud) or env vars (HuggingFace Spaces)."""
    try:
        return st.secrets.get(key, os.environ.get(key, default))
    except FileNotFoundError:
        return os.environ.get(key, default)


def _get_sheet_id():
    url = _get_secret("sheet_url")
    if not url:
        return None
    parts = url.split("/d/")
    if len(parts) < 2:
        return None
    return parts[1].split("/")[0]


def _get_apps_script_url():
    return _get_secret("apps_script_url")


@st.cache_data(ttl=30)
def load_plans() -> dict:
    sheet_id = _get_sheet_id()
    if not sheet_id:
        return {}
    try:
        csv_url = SHEET_CSV_TMPL.format(sheet_id=sheet_id)
        df = pd.read_csv(csv_url)
        plans = {}
        for _, row in df.iterrows():
            try:
                data = json.loads(row["data_json"])
                plans[row["name"]] = normalize_plan(data)
            except (json.JSONDecodeError, KeyError):
                continue
        return plans
    except Exception:
        return {}


def save_plan(name: str, data: dict):
    url = _get_apps_script_url()
    if not url:
        raise ValueError("Apps Script URL not configured in secrets")
    payload = {
        "action": "save",
        "name": name,
        "author": data.get("author", ""),
        "timestamp": data.get("timestamp", ""),
        "data_json": json.dumps(data),
    }
    resp = requests.post(url, json=payload, timeout=15)
    if resp.status_code != 200:
        raise ValueError(f"Apps Script returned {resp.status_code}")


def delete_plan(name: str):
    url = _get_apps_script_url()
    if not url:
        raise ValueError("Apps Script URL not configured in secrets")
    payload = {"action": "delete", "name": name}
    resp = requests.post(url, json=payload, timeout=15)
    if resp.status_code != 200:
        raise ValueError(f"Apps Script returned {resp.status_code}")


def normalize_plan(data):
    """Ensure loaded data works as a plan regardless of version (backward compat)."""
    if "version" not in data:
        data["version"] = 1
        data.setdefault("months_employed", data.get("inputs", {}).get("months_employed", 12))
        data.setdefault("attainment_levels", [50, 75, 100, 150, 200])
    return data


# ---------------------------------------------------------------------------
# Commission engine
# ---------------------------------------------------------------------------

def calc_commission_attainment(revenue, quota, tiers, retroactive=False):
    """Tiered attainment-based commission.
    tiers: list of (upper_attainment_pct | None, rate_pct).
    If retroactive=False (marginal): each rate applies only to revenue in that band.
    If retroactive=True: the highest tier reached applies to ALL revenue."""
    if retroactive:
        applicable_rate = tiers[0][1]
        for upper_pct, rate in tiers:
            if upper_pct is None:
                applicable_rate = rate
                break
            if revenue <= upper_pct * quota / 100:
                applicable_rate = rate
                break
            applicable_rate = rate
        last_upper = tiers[-2][0] if tiers[-1][0] is None else tiers[-1][0]
        if tiers[-1][0] is None and revenue > last_upper * quota / 100:
            applicable_rate = tiers[-1][1]
        return revenue * (applicable_rate / 100)
    else:
        commission = 0.0
        prev_boundary = 0.0
        for upper_pct, rate in tiers:
            if upper_pct is None:
                if revenue > prev_boundary * quota / 100:
                    commission += (revenue - prev_boundary * quota / 100) * (rate / 100)
                break
            boundary_rev = upper_pct * quota / 100
            if revenue <= prev_boundary * quota / 100:
                break
            taxable = min(revenue, boundary_rev) - (prev_boundary * quota / 100)
            if taxable > 0:
                commission += taxable * (rate / 100)
            prev_boundary = upper_pct
        return commission


def calc_commission_deal_rate(deals, deal_rate_tiers, attainment_pct, accel_tiers):
    """Deal-size-based commission with attainment accelerators."""
    multiplier = 1.0
    for upper_pct, mult in accel_tiers:
        if upper_pct is None or attainment_pct <= upper_pct:
            multiplier = mult
            break
    total = 0.0
    deal_results = []
    for deal in deals:
        acv = deal["acv"]
        split_pct = deal.get("split_pct", 100) / 100
        rate = 0.0
        for min_acv, max_acv, r in deal_rate_tiers:
            if acv >= min_acv and (max_acv is None or acv <= max_acv):
                rate = r / 100
                break
        payout = acv * rate * multiplier * split_pct
        clawback = deal.get("clawback_pct", 0) / 100
        net_payout = payout * (1 - clawback)
        total += net_payout
        deal_results.append({
            "Deal": deal.get("name", ""),
            "ACV": acv,
            "Rate": f"{rate*100:.0f}%",
            "Multiplier": f"{multiplier:.1f}x",
            "Split": f"{split_pct*100:.0f}%",
            "Gross Payout": round(payout, 2),
            "Clawback": f"{clawback*100:.0f}%",
            "Net Payout": round(net_payout, 2),
        })
    return total, deal_results


def calc_ramp_adjusted_quota(annual_quota, ramp_pcts, months_employed=12):
    monthly_quota = annual_quota / 12
    total = 0.0
    for m in range(min(months_employed, 12)):
        if m < len(ramp_pcts):
            total += monthly_quota * (ramp_pcts[m] / 100)
        else:
            total += monthly_quota
    return total


def compute_projection(params, commission_mode, retroactive, attainment_pct, months_employed=12):
    """Compute full results for a plan at a given attainment level."""
    annual_quota = params.get("annual_quota", 0)
    base_salary = params.get("base_salary", 0)
    draw_amount = params.get("draw_amount", 0)
    draw_months_val = params.get("draw_months", 0)
    draw_recoverable = params.get("draw_recoverable", False)
    ramp_pcts = params.get("ramp_pcts", [])
    cogs_pct = params.get("cogs_pct", 20.0)
    other_cost = params.get("other_cost_per_rep", 0)

    effective_quota = calc_ramp_adjusted_quota(annual_quota, ramp_pcts, months_employed)
    # Revenue = attainment % of full annual quota (not ramp-adjusted)
    actual_revenue = annual_quota * attainment_pct / 100

    # Commission
    if commission_mode == "Attainment-based rates":
        tiers = params.get("commission_tiers", [])
        commission = calc_commission_attainment(actual_revenue, annual_quota, tiers, retroactive)
    else:
        deal_rate_tiers = params.get("deal_rate_tiers", [])
        accel_tiers = params.get("accel_tiers", [])
        avg_rate = 0.0
        for mn, mx, rt in deal_rate_tiers:
            if mx is None or actual_revenue / max(1, 12) <= mx:
                avg_rate = rt
                break
        mult = 1.0
        for upper, m in accel_tiers:
            if upper is None or attainment_pct <= upper:
                mult = m
                break
        commission = actual_revenue * (avg_rate / 100) * mult

    # Draw
    active_draw_months = min(int(draw_months_val), months_employed)
    draw_paid = draw_amount * (active_draw_months / max(int(draw_months_val), 1)) if draw_months_val > 0 else 0
    if draw_recoverable:
        total_variable = max(commission, draw_paid)
    else:
        total_variable = commission + draw_paid

    prorated_base = base_salary * (months_employed / 12)
    total_comp = prorated_base + total_variable

    # Company economics
    gross_profit = actual_revenue * (1 - cogs_pct / 100)
    total_cost_of_rep = total_comp + other_cost * (months_employed / 12)
    net_after_rep = gross_profit - total_cost_of_rep
    roi_on_rep = (actual_revenue / total_cost_of_rep) if total_cost_of_rep > 0 else 0

    return {
        "actual_revenue": round(actual_revenue, 2),
        "effective_quota": round(effective_quota, 2),
        "attainment_pct": round(attainment_pct, 1),
        "commission": round(commission, 2),
        "draw_paid": round(draw_paid, 2),
        "total_variable": round(total_variable, 2),
        "total_comp": round(total_comp, 2),
        "gross_profit": round(gross_profit, 2),
        "total_cost_of_rep": round(total_cost_of_rep, 2),
        "net_after_rep": round(net_after_rep, 2),
        "roi_on_rep": round(roi_on_rep, 2),
    }


# ---------------------------------------------------------------------------
# App
# ---------------------------------------------------------------------------

st.set_page_config(page_title="Sales Comp Plan Builder", layout="wide")
st.title("Sales Comp Plan Builder")

st.markdown("""
Model different compensation plans and compare them side by side.

**How to use:**
1. **Set plan parameters** in the sidebar (base salary, quota, commission structure, ramp, draw, etc.)
2. **Explore what-if scenarios** in the Plan Builder tab with any revenue number
3. **Save the plan** and it auto-generates projections at 75%, 100%, 150%, 200% attainment
4. **Compare plans** side by side in the Compare tab
""")

# Check config
sheet_ok = bool(_get_sheet_id())
script_ok = bool(_get_apps_script_url())
if not sheet_ok or not script_ok:
    with st.expander("Admin: backend setup required", expanded=False):
        st.warning("Add these to `.streamlit/secrets.toml` (local) or Streamlit Cloud Secrets:")
        st.code('''sheet_url = "https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit"
apps_script_url = "https://script.google.com/macros/s/YOUR_SCRIPT_ID/exec"''', language="toml")
        st.markdown("""
**Quick setup (5 min):**
1. Create a Google Sheet with headers in row 1: `name | author | timestamp | data_json`
2. Share it as **"Anyone with the link" β†’ Editor**
3. Open **Extensions β†’ Apps Script**, paste the script from `apps_script.js` in this repo
4. Deploy as **Web App** β†’ Execute as **Me** β†’ Access **Anyone**
5. Copy the sheet URL and web app URL into secrets
        """)

# ---- Sidebar: Plan Parameters ----

st.sidebar.header("Plan Parameters")

# --- Load a saved plan into the sidebar ---
saved_plans = load_plans() if sheet_ok else {}
load_options = ["β€” New plan β€”"] + list(saved_plans.keys())
load_choice = st.sidebar.selectbox("Load a saved plan", load_options, key="load_plan",
                                    help="Select a saved plan to load its parameters into the sidebar for editing")
if load_choice != "β€” New plan β€”" and load_choice in saved_plans:
    if st.sidebar.button("Load into sidebar"):
        plan = saved_plans[load_choice]
        p = plan.get("params", {})
        # Set session state for all sidebar widgets
        st.session_state["base"] = p.get("base_salary", 150_000)
        st.session_state["quota"] = p.get("annual_quota", 1_250_000)
        st.session_state["draw"] = p.get("draw_amount", 0)
        st.session_state["draw_months"] = p.get("draw_months", 12)
        st.session_state["draw_rec"] = p.get("draw_recoverable", False)
        st.session_state["cogs_pct"] = p.get("cogs_pct", 20.0)
        st.session_state["other_cost"] = p.get("other_cost_per_rep", 20_000)
        # Commission mode
        st.session_state["comm_mode"] = plan.get("commission_mode", "Attainment-based rates")
        st.session_state["retroactive"] = plan.get("retroactive", False)
        # Ramp
        ramp = p.get("ramp_pcts", [])
        st.session_state["ramp_months"] = len(ramp)
        for i, pct in enumerate(ramp):
            st.session_state[f"ramp_{i}"] = int(pct)
        # Commission tiers
        tiers = p.get("commission_tiers") or []
        if tiers:
            st.session_state["num_tiers"] = len(tiers)
            for i, tier in enumerate(tiers):
                if tier[0] is not None:
                    st.session_state[f"at_u_{i}"] = int(tier[0])
                st.session_state[f"at_r_{i}"] = float(tier[1])
        # Deal-size tiers
        deal_tiers = p.get("deal_rate_tiers") or []
        if deal_tiers:
            st.session_state["num_deal_tiers"] = len(deal_tiers)
            for i, tier in enumerate(deal_tiers):
                st.session_state[f"dt_mn_{i}"] = int(tier[0])
                if tier[1] is not None:
                    st.session_state[f"dt_mx_{i}"] = int(tier[1])
                st.session_state[f"dt_rt_{i}"] = float(tier[2])
        # Accelerators
        accels = p.get("accel_tiers") or []
        if accels:
            st.session_state["num_accels"] = len(accels)
            for i, tier in enumerate(accels):
                if tier[0] is not None:
                    st.session_state[f"ac_u_{i}"] = int(tier[0])
                st.session_state[f"ac_m_{i}"] = float(tier[1])
        # Months employed
        st.session_state["months_emp"] = plan.get("months_employed", 12)
        # Author
        st.session_state["author"] = plan.get("author", "")
        st.rerun()

st.sidebar.caption("Adjust these to model different comp plan structures. Changes update results instantly.")


def _default(key, fallback):
    """Return {} if key is already in session_state (widget will use that), else set value=fallback."""
    if key in st.session_state:
        return {}
    return {"value": fallback}


with st.sidebar.expander("Compensation Structure", expanded=True):
    base_salary = st.number_input("Base Salary ($)", step=5_000, key="base",
                                   help="Annual base salary before any variable compensation",
                                   **_default("base", 150_000))
    annual_quota = st.number_input("Annual Quota ($)", step=50_000, key="quota",
                                    help="Full-year revenue target at 100% attainment",
                                    **_default("quota", 1_250_000))

with st.sidebar.expander("Draw", expanded=False):
    st.caption(
        "A **draw** is guaranteed cash paid to the rep regardless of deals closed β€” "
        "a safety net while pipeline is still building. "
        "**Recoverable** = deducted from future commissions (an advance). "
        "**Non-recoverable** = paid on top of whatever they earn."
    )
    draw_amount = st.number_input("Draw total ($)", step=5_000, key="draw",
                                   help="Total draw amount spread over the draw period",
                                   **_default("draw", 50_000))
    draw_months = st.number_input("Draw duration (months)", step=1, key="draw_months",
                                   **_default("draw_months", 12))
    draw_recoverable = st.checkbox("Recoverable", key="draw_rec",
                                    help="If recoverable, draw is deducted from earned commissions. If non-recoverable, it's paid on top.",
                                    **_default("draw_rec", False))

st.sidebar.divider()
commission_mode = st.sidebar.radio(
    "Commission model",
    ["Attainment-based rates", "Deal-size rates + accelerators"],
    key="comm_mode",
    help="**Attainment-based:** Commission rate changes at quota attainment thresholds (e.g. 4% up to 100%, 5% from 100-125%). "
         "**Deal-size + accelerators:** Flat commission rate per deal based on ACV size, with a multiplier that kicks in at higher attainment levels.",
)

# -- Attainment-based tiers --
att_tiers = []
deal_rate_tiers = []
accel_tiers = []
avg_rate = 0.0

retroactive_mode = False
if commission_mode == "Attainment-based rates":
    with st.sidebar.expander("Commission Tiers (attainment)", expanded=True):
        retroactive_mode = st.toggle("Retroactive rates", key="retroactive",
                                      **_default("retroactive", False),
                                      help="**Marginal** (off): each rate applies only to revenue in that band. "
                                           "**Retroactive** (on): once a threshold is crossed, the higher rate applies to ALL revenue from dollar one. "
                                           "Retroactive is much more expensive for the company.")
        if retroactive_mode:
            st.caption("Retroactive β€” highest tier reached applies to ALL revenue")
        else:
            st.caption("Marginal β€” each rate applies only to revenue in that band")
        num_tiers = st.number_input("Number of tiers", 1, 8, key="num_tiers",
                                     **_default("num_tiers", 4))
        att_defaults = [(100, 4.0), (125, 5.0), (150, 6.0), (None, 7.0)]
        for i in range(int(num_tiers)):
            c1, c2 = st.columns(2)
            is_last = i == int(num_tiers) - 1
            d_upper = att_defaults[i][0] if i < len(att_defaults) and not is_last else None
            d_rate = att_defaults[i][1] if i < len(att_defaults) else 5.0
            if is_last:
                c1.text(f"Tier {i+1}: above prior")
                upper = None
            else:
                upper = c1.number_input(f"Tier {i+1} upper %", step=5, key=f"at_u_{i}",
                                         **_default(f"at_u_{i}", d_upper or 100))
            rate = c2.number_input(f"Tier {i+1} rate %", step=0.5, format="%.1f", key=f"at_r_{i}",
                                    **_default(f"at_r_{i}", d_rate))
            att_tiers.append((upper, rate))
else:
    with st.sidebar.expander("Deal-Size Commission Rates", expanded=True):
        num_deal_tiers = st.number_input("Number of deal-size tiers", 1, 6, key="num_deal_tiers",
                                          **_default("num_deal_tiers", 3))
        deal_defaults = [(0, 29_999, 20.0), (30_000, 100_000, 40.0), (100_001, None, 40.0)]
        for i in range(int(num_deal_tiers)):
            c1, c2, c3 = st.columns(3)
            d = deal_defaults[i] if i < len(deal_defaults) else (0, None, 40.0)
            mn = c1.number_input(f"Tier {i+1} min ACV", step=5_000, key=f"dt_mn_{i}",
                                  **_default(f"dt_mn_{i}", d[0]))
            is_last = i == int(num_deal_tiers) - 1
            if is_last:
                mx = None
                c2.text("Uncapped")
            else:
                mx = c2.number_input(f"Tier {i+1} max ACV", step=5_000, key=f"dt_mx_{i}",
                                      **_default(f"dt_mx_{i}", d[1] or 100_000))
            rt = c3.number_input(f"Tier {i+1} rate %", step=1.0, format="%.1f", key=f"dt_rt_{i}",
                                  **_default(f"dt_rt_{i}", d[2]))
            deal_rate_tiers.append((mn, mx, rt))

    with st.sidebar.expander("Attainment Accelerators", expanded=True):
        st.caption("Multiplier applied to deal commission based on annual attainment")
        num_accels = st.number_input("Number of accelerator tiers", 1, 6, key="num_accels",
                                      **_default("num_accels", 3))
        accel_defaults = [(99, 1.0), (124, 1.3), (None, 1.5)]
        for i in range(int(num_accels)):
            c1, c2 = st.columns(2)
            d = accel_defaults[i] if i < len(accel_defaults) else (None, 1.0)
            is_last = i == int(num_accels) - 1
            if is_last:
                c1.text("Above prior")
                upper = None
            else:
                upper = c1.number_input(f"Accel {i+1} up to %", step=5, key=f"ac_u_{i}",
                                         **_default(f"ac_u_{i}", d[0] or 100))
            mult = c2.number_input(f"Accel {i+1} multiplier", step=0.1, format="%.1f", key=f"ac_m_{i}",
                                    **_default(f"ac_m_{i}", d[1]))
            accel_tiers.append((upper, mult))

# -- Ramp --
with st.sidebar.expander("Ramp Schedule", expanded=False):
    st.caption(
        "A **ramp** reduces the rep's quota target during early months β€” "
        "they have a lower bar to hit, making it easier to reach attainment "
        "while getting up to speed. Unlike a draw, the rep still has to close "
        "deals to earn variable comp. Set each month's quota as a % of full quota."
    )
    ramp_months = st.number_input("Ramp months", 0, 12, key="ramp_months",
                                   **_default("ramp_months", 9))
    ramp_pcts = []
    ramp_defaults = [0, 0, 25, 25, 50, 50, 75, 75, 75]
    for i in range(int(ramp_months)):
        d = ramp_defaults[i] if i < len(ramp_defaults) else 75
        pct = st.number_input(f"Month {i+1} quota %", step=5, key=f"ramp_{i}",
                               **_default(f"ramp_{i}", d))
        ramp_pcts.append(pct)

# -- Company economics --
with st.sidebar.expander("Company Economics", expanded=False):
    cogs_pct = st.number_input("COGS (% of revenue)", step=5.0, format="%.1f", key="cogs_pct",
                               **_default("cogs_pct", 20.0))
    other_cost_per_rep = st.number_input("Other cost per rep ($)", step=5_000, key="other_cost",
                                          help="Annual cost for benefits, tools, travel, etc. β€” pro-rated if less than 12 months",
                                          **_default("other_cost", 20_000))

# -- Projection settings --
with st.sidebar.expander("Projection Settings", expanded=False):
    st.caption("Attainment levels used when auto-generating plan projections.")
    attainment_str = st.text_input("Attainment levels (%)", key="att_levels",
                                   **_default("att_levels", "50, 75, 100, 150, 200"))
    attainment_levels = [int(x.strip()) for x in attainment_str.split(",") if x.strip().isdigit()]
    if not attainment_levels:
        attainment_levels = [50, 75, 100, 150, 200]

# ---- Main tabs (deeplink via ?tab=builder|deals|compare) ----

TAB_KEYS = ["builder", "deals", "compare"]
TAB_LABELS = ["1. Plan Builder", "2. Per-Deal Calculator", "3. Compare Plans"]
TAB_MAP = dict(zip(TAB_KEYS, TAB_LABELS))

qp = st.query_params
initial_tab = qp.get("tab", "builder")
# backward compat for old ?tab=scenario links
if initial_tab == "scenario":
    initial_tab = "builder"
if initial_tab not in TAB_KEYS:
    initial_tab = "builder"

active_tab = st.radio(
    "Navigate",
    TAB_KEYS,
    index=TAB_KEYS.index(initial_tab),
    format_func=lambda k: TAB_MAP[k],
    horizontal=True,
    key="active_tab",
    label_visibility="collapsed",
)
st.query_params["tab"] = active_tab

# ===================== TAB 1: Plan Builder =====================

if active_tab == "builder":
    st.caption("Configure the plan in the sidebar, then explore any revenue number below. Save the plan to auto-generate projections.")
    col_in, col_out = st.columns([1, 1.5])

    with col_in:
        st.subheader("What-If Calculator")
        author = st.text_input("Plan author", key="author",
                                placeholder="e.g. 'Founder', 'VP Sales'",
                                help="A generic label for who created this plan β€” avoid real names")
        months_employed = st.slider("Months in plan year", 1, 12, key="months_emp",
                                     help="Set to less than 12 for mid-year hires β€” ramp schedule adjusts the quota automatically",
                                     **_default("months_emp", 12))

        effective_quota = calc_ramp_adjusted_quota(annual_quota, ramp_pcts, months_employed)
        st.metric("Effective Quota (ramp-adjusted)", f"${effective_quota:,.0f}",
                  help="Annual quota reduced by the ramp schedule for months where quota is below 100%")

        actual_revenue = st.number_input("Total Revenue Closed ($)", step=50_000, key="rev",
                                          help="Actual or projected closed revenue for the period",
                                          **_default("rev", 1_250_000))
        attainment_pct = (actual_revenue / effective_quota * 100) if effective_quota > 0 else 0

    # Commission uses full annual quota for tier boundaries
    commission_quota = annual_quota

    # --- Commission calc ---
    if commission_mode == "Attainment-based rates":
        commission = calc_commission_attainment(actual_revenue, commission_quota, att_tiers, retroactive_mode)
    else:
        for mn, mx, rt in deal_rate_tiers:
            if mx is None or actual_revenue / max(1, 12) <= mx:
                avg_rate = rt
                break
        mult = 1.0
        for upper, m in accel_tiers:
            if upper is None or attainment_pct <= upper:
                mult = m
                break
        commission = actual_revenue * (avg_rate / 100) * mult

    # --- Draw ---
    active_draw_months = min(int(draw_months), months_employed)
    draw_paid = draw_amount * (active_draw_months / max(int(draw_months), 1))
    if draw_recoverable:
        total_variable = max(commission, draw_paid)
    else:
        total_variable = commission + draw_paid

    prorated_base = base_salary * (months_employed / 12)
    total_comp = prorated_base + total_variable

    # Company economics
    gross_profit = actual_revenue * (1 - cogs_pct / 100)
    total_cost_of_rep = total_comp + other_cost_per_rep * (months_employed / 12)
    net_after_rep = gross_profit - total_cost_of_rep
    roi_on_rep = (actual_revenue / total_cost_of_rep) if total_cost_of_rep > 0 else 0

    with col_out:
        st.subheader("Results")

        st.markdown("**What the seller earns**")
        m1, m2, m3 = st.columns(3)
        m1.metric("Quota Attainment", f"{attainment_pct:.1f}%",
                  help="Revenue closed / effective quota")
        m2.metric("Commission Earned", f"${commission:,.0f}",
                  help="Variable pay from the commission structure")
        m3.metric("Total Compensation", f"${total_comp:,.0f}",
                  help="Base + draw + commission = total cash to the seller")

        r1, r2, r3 = st.columns(3)
        r1.metric("Base Salary", f"${prorated_base:,.0f}",
                  help="Pro-rated if less than 12 months")
        r2.metric("Draw Paid", f"${draw_paid:,.0f}",
                  help="Guaranteed draw pro-rated for months employed")
        r3.metric("Total Variable", f"${total_variable:,.0f}",
                  help="Commission + draw (or the greater of the two if recoverable)")

        st.markdown("**What it costs the company**")
        c1, c2, c3, c4 = st.columns(4)
        c1.metric("Revenue", f"${actual_revenue:,.0f}")
        c2.metric("COGS", f"${actual_revenue * cogs_pct / 100:,.0f}",
                  help="Cost of goods sold β€” set the % in sidebar")
        c3.metric("Gross Profit", f"${gross_profit:,.0f}",
                  help="Revenue minus COGS")
        c4.metric("Net After Rep Cost", f"${net_after_rep:,.0f}",
                  help="Gross profit minus total cost of the rep (comp + overhead)")

        d1, d2, d3 = st.columns(3)
        d1.metric("Total Rep Cost", f"${total_cost_of_rep:,.0f}",
                  help="Total comp + benefits/tools/travel overhead")
        d2.metric("Rep Cost as % of Revenue", f"{total_cost_of_rep / actual_revenue * 100:.1f}%" if actual_revenue > 0 else "N/A",
                  help="How much of each revenue dollar goes to the rep")
        d3.metric("Revenue ROI on Rep", f"{roi_on_rep:.1f}x",
                  help="Revenue generated per dollar spent on the rep")

        st.markdown("**Commission Curve**")
        st.caption("How commission scales with attainment β€” the red dot is your current what-if.")
        rev_pts = [commission_quota * x / 100 for x in range(0, 201, 5)]
        if commission_mode == "Attainment-based rates":
            comm_pts = [calc_commission_attainment(r, commission_quota, att_tiers, retroactive_mode) for r in rev_pts]
        else:
            comm_pts = []
            for r in rev_pts:
                att = (r / effective_quota * 100) if effective_quota > 0 else 0
                m_ = 1.0
                for up, ml in accel_tiers:
                    if up is None or att <= up:
                        m_ = ml
                        break
                comm_pts.append(r * (avg_rate / 100) * m_)
        att_pts = [r / effective_quota * 100 if effective_quota > 0 else 0 for r in rev_pts]

        total_comp_pts = [prorated_base + draw_paid + c for c in comm_pts]

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=att_pts, y=comm_pts, mode="lines", name="Commission",
                                  line=dict(color="#2563eb", width=3)))
        fig.add_trace(go.Scatter(x=att_pts, y=total_comp_pts, mode="lines", name="Total Comp",
                                  line=dict(color="#16a34a", width=2, dash="dot")))
        fig.add_trace(go.Scatter(x=[attainment_pct], y=[commission], mode="markers", name="You",
                                  marker=dict(size=12, color="#dc2626")))
        fig.update_layout(xaxis_title="Quota Attainment %", yaxis_title="$",
                          height=350, margin=dict(l=0, r=0, t=30, b=0))
        st.plotly_chart(fig, use_container_width=True)

    # --- Live projections table ---
    st.divider()
    st.subheader("Plan Projections")
    st.caption("Auto-generated from current sidebar settings. Updates live as you change parameters.")

    current_params = {
        "base_salary": base_salary, "annual_quota": annual_quota,
        "draw_amount": draw_amount, "draw_months": int(draw_months),
        "draw_recoverable": draw_recoverable, "ramp_pcts": ramp_pcts,
        "cogs_pct": cogs_pct, "other_cost_per_rep": other_cost_per_rep,
        "commission_tiers": att_tiers if commission_mode == "Attainment-based rates" else None,
        "deal_rate_tiers": deal_rate_tiers if commission_mode != "Attainment-based rates" else None,
        "accel_tiers": accel_tiers if commission_mode != "Attainment-based rates" else None,
    }

    proj_rows = []
    for level in attainment_levels:
        proj = compute_projection(current_params, commission_mode, retroactive_mode, level, months_employed)
        proj_rows.append({
            "Attainment": f"{level}%",
            "Revenue": f"${proj['actual_revenue']:,.0f}",
            "Base Salary": f"${base_salary * (months_employed / 12):,.0f}",
            "Commission": f"${proj['commission']:,.0f}",
            "Draw": f"${proj['draw_paid']:,.0f}",
            "Total Comp": f"${proj['total_comp']:,.0f}",
            "Gross Profit": f"${proj['gross_profit']:,.0f}",
            "Net After Rep": f"${proj['net_after_rep']:,.0f}",
            "ROI": f"{proj['roi_on_rep']:.1f}x",
        })
    st.dataframe(pd.DataFrame(proj_rows), use_container_width=True, hide_index=True)

    # Live agreement preview
    with st.expander("Agreement Preview", expanded=False):
        prev_lines = []
        prev_lines.append("SALES COMPENSATION PLAN")
        prev_lines.append("=" * 60)
        prev_lines.append("")
        proj_100 = compute_projection(current_params, commission_mode, retroactive_mode, 100, months_employed)
        prev_lines.append(f"  ${base_salary:,.0f}".ljust(22) + f"~${proj_100['total_comp']:,.0f}".ljust(22))
        prev_lines.append("  Base Salary".ljust(22) + "OTE".ljust(22))
        prev_lines.append("")
        prev_lines.append("1. COMPENSATION OVERVIEW")
        prev_lines.append("")
        prev_lines.append(f"  Base Salary: ${base_salary:,.0f} / year paid semi-monthly")
        if draw_amount > 0:
            rec_lbl = "recoverable" if draw_recoverable else "non-recoverable"
            prev_lines.append(f"  Draw: ${draw_amount:,.0f} {rec_lbl} over {int(draw_months)} months (~${draw_amount / max(int(draw_months), 1):,.0f}/mo)")
        prev_lines.append(f"  OTE: ${proj_100['total_comp']:,.0f} (base + variable at 100% attainment)")
        prev_lines.append(f"  Commissions are uncapped.")
        prev_lines.append("")
        prev_lines.append("2. COMMISSION STRUCTURE")
        prev_lines.append("")
        if commission_mode == "Attainment-based rates" and att_tiers:
            if retroactive_mode:
                prev_lines.append("  Retroactive β€” highest tier reached applies to ALL revenue.")
            else:
                prev_lines.append("  Marginal β€” each rate applies only to revenue in that band.")
            prev_lines.append("")
            prev_lines.append(f"  {'Attainment Level':<24} {'Commission Rate':<18}")
            prev_lines.append(f"  {'-' * 22:<24} {'-' * 16:<18}")
            for i, tier in enumerate(att_tiers):
                upper_val, rate_val = tier[0], tier[1]
                if upper_val is None:
                    prev_upper = int(att_tiers[i-1][0])
                    prev_lines.append(f"  {prev_upper}%+{'':<19} {rate_val:.1f}%")
                elif i == 0:
                    prev_lines.append(f"  0% – {int(upper_val)}%{'':<14} {rate_val:.1f}%")
                else:
                    prev_upper = int(att_tiers[i-1][0])
                    prev_lines.append(f"  {prev_upper}% – {int(upper_val)}%{'':<12} {rate_val:.1f}%")
        prev_lines.append("")
        ramp_list_preview = ramp_pcts
        if ramp_list_preview:
            prev_lines.append("3. QUOTA RAMP SCHEDULE")
            prev_lines.append("")
            monthly_q = annual_quota / 12
            ramp_groups_p = []
            idx_p = 0
            while idx_p < len(ramp_list_preview):
                pct_p = ramp_list_preview[idx_p]
                start_p = idx_p + 1
                while idx_p + 1 < len(ramp_list_preview) and ramp_list_preview[idx_p + 1] == pct_p:
                    idx_p += 1
                end_p = idx_p + 1
                ramp_groups_p.append((start_p, end_p, pct_p))
                idx_p += 1
            for start_p, end_p, pct_p in ramp_groups_p:
                ml = f"{start_p}–{end_p}" if start_p != end_p else str(start_p)
                tgt = monthly_q * pct_p / 100
                prev_lines.append(f"  {ml:<10} {int(pct_p)}% quota   ${tgt:,.0f}/mo")
            if len(ramp_list_preview) < 12:
                prev_lines.append(f"  {len(ramp_list_preview)+1}–12     100% quota  ${monthly_q:,.0f}/mo")
            prev_lines.append("")
            section_n = 4
        else:
            section_n = 3
        prev_lines.append(f"{section_n}. ILLUSTRATIVE EARNINGS SCENARIOS")
        prev_lines.append("")
        prev_lines.append(f"  {'Attainment':<14} {'Revenue':<16} {'Commission':<16} {'Total Comp':<16} {'Net After Rep'}")
        prev_lines.append(f"  {'-'*12:<14} {'-'*14:<16} {'-'*14:<16} {'-'*14:<16} {'-'*14}")
        for level in attainment_levels:
            proj = compute_projection(current_params, commission_mode, retroactive_mode, level, months_employed)
            prev_lines.append(f"  {level}%{'':<10} ${proj['actual_revenue']:,.0f}{'':<4} ${proj['commission']:,.0f}{'':<6} ${proj['total_comp']:,.0f}{'':<6} ${proj['net_after_rep']:,.0f}")
        st.code("\n".join(prev_lines), language=None)

    # --- Save plan ---
    st.divider()
    st.subheader("Save This Plan")
    st.caption("Save the plan configuration. Projections at each attainment level are generated automatically.")

    # Build plan data (config only, no baked-in results)
    plan_data = {
        "version": 2,
        "author": author,
        "timestamp": datetime.datetime.now().isoformat(),
        "commission_mode": commission_mode,
        "retroactive": retroactive_mode,
        "months_employed": months_employed,
        "attainment_levels": attainment_levels,
        "params": {
            "base_salary": base_salary, "annual_quota": annual_quota,
            "draw_amount": draw_amount,
            "draw_months": int(draw_months), "draw_recoverable": draw_recoverable,
            "ramp_pcts": ramp_pcts, "cogs_pct": cogs_pct,
            "other_cost_per_rep": other_cost_per_rep,
            "commission_tiers": att_tiers if commission_mode == "Attainment-based rates" else None,
            "deal_rate_tiers": deal_rate_tiers if commission_mode != "Attainment-based rates" else None,
            "accel_tiers": accel_tiers if commission_mode != "Attainment-based rates" else None,
        },
    }

    st.warning(
        "**Privacy:** Saved plans are stored in a shared Google Sheet. "
        "Do NOT use real names, company names, or any identifying information "
        "in plan names or the author field. Use generic labels "
        "(e.g. 'Plan A - aggressive', 'Option 2 - conservative').",
        icon="πŸ”’",
    )
    scol1, scol2 = st.columns(2)
    with scol1:
        plan_name = st.text_input("Plan name", key="save_name",
                                   placeholder="e.g. 'plan-a-aggressive'")
        if st.button("Save Plan", type="primary"):
            if plan_name.strip():
                try:
                    save_plan(plan_name.strip(), plan_data)
                    st.success(f"Saved '{plan_name.strip()}'")
                    load_plans.clear()
                    st.rerun()
                except Exception as e:
                    st.error(f"Failed to save: {e}")
            else:
                st.warning("Enter a plan name")

# ===================== TAB 2: Per-Deal Calculator =====================

if active_tab == "deals":
    st.subheader("Per-Deal Payout Calculator")
    st.caption("See exactly what the seller earns on each individual deal. "
               "Useful for modeling specific pipeline deals or understanding payout ranges by deal size.")

    if commission_mode == "Attainment-based rates":
        st.info("This tab requires **Deal-size rates + accelerators** mode. "
                "Switch the commission model in the sidebar to enable it.")
    else:
        current_attainment = st.number_input("Current annual attainment %", value=100.0, step=5.0,
                                              key="deal_attainment",
                                              help="Determines which accelerator multiplier applies β€” "
                                                   "e.g. above 100% attainment, deals may pay at 1.3x")

        st.markdown("**Enter deals:**")
        num_deals = st.number_input("Number of deals", 1, 50, 3, key="num_deals")
        deals = []
        for i in range(int(num_deals)):
            with st.expander(f"Deal {i+1}", expanded=(i < 3)):
                dc1, dc2, dc3, dc4 = st.columns(4)
                name = dc1.text_input("Name", value=f"Deal {i+1}", key=f"deal_name_{i}")
                acv = dc2.number_input("ACV ($)", value=60_000, step=5_000, key=f"deal_acv_{i}")
                split = dc3.number_input("Your split %", value=100, step=10, key=f"deal_split_{i}")
                claw = dc4.number_input("Clawback %", value=0, step=10, key=f"deal_claw_{i}",
                                         help="% clawed back (e.g. 90-day churn)")
                deals.append({"name": name, "acv": acv, "split_pct": split, "clawback_pct": claw})

        total_deal_comm, deal_details = calc_commission_deal_rate(
            deals, deal_rate_tiers, current_attainment, accel_tiers
        )

        st.markdown("**Deal Payouts**")
        st.dataframe(pd.DataFrame(deal_details), use_container_width=True, hide_index=True)
        st.metric("Total Commission from Deals", f"${total_deal_comm:,.0f}")

# ===================== TAB 3: Compare Plans =====================

if active_tab == "compare":
    st.subheader("Compare Plans")
    st.caption("Each plan auto-generates projections at multiple attainment levels. "
               "Compare different plan structures to see how they perform across scenarios.")

    if not sheet_ok:
        st.warning("Configure your Google Sheet URL in secrets to enable plan saving.")
    else:
        if st.button("Refresh from Google Sheets"):
            load_plans.clear()
            st.rerun()

        plans = load_plans()

        if plans:
            col_a, col_b = st.columns(2)
            with col_b:
                to_delete = st.selectbox("Delete a plan", [""] + list(plans.keys()), key="del_sel")
                if st.button("Delete"):
                    if to_delete:
                        try:
                            delete_plan(to_delete)
                            load_plans.clear()
                            st.success(f"Deleted '{to_delete}'")
                            st.rerun()
                        except Exception as e:
                            st.error(f"Failed to delete: {e}")

            all_names = list(plans.keys())
            tc1, tc2 = st.columns([3, 1])
            with tc2:
                if st.button("Clear all"):
                    st.session_state["compare_sel"] = []
                    st.rerun()
                if st.button("Select all"):
                    st.session_state["compare_sel"] = all_names
                    st.rerun()
            with tc1:
                selected = st.multiselect("Filter plans", all_names,
                                           default=all_names, key="compare_sel")

            if selected:
                # Build comparison table with projections at each attainment level
                rows = []
                for name in selected:
                    plan = plans[name]
                    p = plan.get("params", {})
                    months = plan.get("months_employed", 12)
                    levels = plan.get("attainment_levels", [50, 75, 100, 150, 200])
                    retro = plan.get("retroactive", False)
                    mode = plan.get("commission_mode", "Attainment-based rates")

                    row = {
                        "Plan": name,
                        "Author": plan.get("author", ""),
                        "Mode": mode + (" (retro)" if retro else ""),
                        "Base": f"${p.get('base_salary', 0):,.0f}",
                        "Quota": f"${p.get('annual_quota', 0):,.0f}",
                    }

                    for level in levels:
                        proj = compute_projection(p, mode, retro, level, months)
                        row[f"{level}% Comm"] = f"${proj['commission']:,.0f}"
                        row[f"{level}% Total"] = f"${proj['total_comp']:,.0f}"
                        row[f"{level}% Net"] = f"${proj['net_after_rep']:,.0f}"

                    rows.append(row)

                st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)

                # Chart: total comp at each attainment level per plan
                st.markdown("**Total Compensation by Attainment**")
                fig = go.Figure()
                # Use the union of all attainment levels across selected plans
                all_levels = sorted(set(
                    lvl for name in selected
                    for lvl in plans[name].get("attainment_levels", [50, 75, 100, 150, 200])
                ))
                for name in selected:
                    plan = plans[name]
                    p = plan.get("params", {})
                    months = plan.get("months_employed", 12)
                    retro = plan.get("retroactive", False)
                    mode = plan.get("commission_mode", "Attainment-based rates")
                    comps = []
                    for level in all_levels:
                        proj = compute_projection(p, mode, retro, level, months)
                        comps.append(proj["total_comp"])
                    fig.add_trace(go.Bar(
                        name=name,
                        x=[f"{l}%" for l in all_levels],
                        y=comps,
                    ))
                fig.update_layout(barmode="group", height=400,
                                  xaxis_title="Attainment", yaxis_title="Total Comp ($)",
                                  margin=dict(l=0, r=0, t=30, b=0))
                st.plotly_chart(fig, use_container_width=True)

                # Net after rep chart
                st.markdown("**Net After Rep Cost by Attainment**")
                fig2 = go.Figure()
                for name in selected:
                    plan = plans[name]
                    p = plan.get("params", {})
                    months = plan.get("months_employed", 12)
                    retro = plan.get("retroactive", False)
                    mode = plan.get("commission_mode", "Attainment-based rates")
                    nets = []
                    for level in all_levels:
                        proj = compute_projection(p, mode, retro, level, months)
                        nets.append(proj["net_after_rep"])
                    fig2.add_trace(go.Bar(
                        name=name,
                        x=[f"{l}%" for l in all_levels],
                        y=nets,
                    ))
                fig2.update_layout(barmode="group", height=400,
                                   xaxis_title="Attainment", yaxis_title="Net After Rep ($)",
                                   margin=dict(l=0, r=0, t=30, b=0))
                st.plotly_chart(fig2, use_container_width=True)

                # --- Plan detail view ---
                st.divider()
                st.markdown("**Plan Details**")
                st.caption("Select a plan to view agreement-ready compensation terms.")
                detail_name = st.selectbox("View details for", [""] + selected, key="detail_sel")
                if detail_name and detail_name in plans:
                    s = plans[detail_name]
                    p = s.get("params", {})
                    months = s.get("months_employed", 12)
                    retro = s.get("retroactive", False)
                    mode = s.get("commission_mode", "Attainment-based rates")
                    levels = s.get("attainment_levels", [50, 75, 100, 150, 200])

                    # Compute 100% projection for OTE reference
                    proj_100 = compute_projection(p, mode, retro, 100, months)

                    # Build agreement text
                    lines = []
                    deal_types = p.get("deal_types")
                    illustrative = p.get("illustrative_scenarios")
                    policies = p.get("policies")
                    equity = p.get("equity")

                    lines.append("SALES COMPENSATION PLAN")
                    lines.append("=" * 60)
                    lines.append("")

                    # Header summary
                    lines.append(f"  ${p.get('base_salary', 0):,.0f}".ljust(22) + f"~${proj_100['total_comp']:,.0f}".ljust(22))
                    lines.append("  Base Salary".ljust(22) + "OTE".ljust(22))
                    draw_amt = p.get("draw_amount", 0)
                    if draw_amt > 0 or equity:
                        line_l = f"  ${draw_amt:,.0f}" if draw_amt > 0 else ""
                        line_r = f"  {equity.get('pct', '')}%" if equity else ""
                        lines.append(line_l.ljust(22) + line_r.ljust(22))
                        line_l2 = f"  Draw ({p.get('draw_months', 0)} mo.)" if draw_amt > 0 else ""
                        line_r2 = f"  Equity (Options)" if equity else ""
                        lines.append(line_l2.ljust(22) + line_r2.ljust(22))
                    lines.append("")

                    # 1. Compensation Overview
                    lines.append("1. COMPENSATION OVERVIEW")
                    lines.append("")
                    lines.append("  Base Salary")
                    lines.append(f"    β€’ ${p.get('base_salary', 0):,.0f} / year paid semi-monthly")
                    lines.append(f"    β€’ Full benefits eligibility from day 1")
                    lines.append("")

                    if draw_amt > 0:
                        draw_mo = p.get("draw_months", 0)
                        rec_label = "recoverable" if p.get("draw_recoverable", False) else "non-recoverable"
                        monthly_draw = draw_amt / max(draw_mo, 1)
                        lines.append("  Signing Draw")
                        lines.append(f"    β€’ ${draw_amt:,.0f} {rec_label} draw")
                        lines.append(f"    β€’ Paid over {draw_mo} months in equal installments ~${monthly_draw:,.0f}/mo.")
                        if not p.get("draw_recoverable", False):
                            lines.append(f"    β€’ Not subject to clawback β€” protects ramp period")
                        lines.append("")

                    if equity:
                        lines.append("  Equity Grant")
                        lines.append(f"    β€’ {equity.get('pct', '')}% of company in stock options")
                        lines.append(f"    β€’ {equity.get('vesting', '4-year vest with 1-year cliff')}")
                        lines.append(f"    β€’ Strike price = FMV at grant date")
                        lines.append("")

                    lines.append("  On-Target Earnings (OTE)")
                    lines.append(f"    β€’ ${p.get('base_salary', 0):,.0f} base + ~${proj_100['commission']:,.0f} variable = ~${proj_100['total_comp']:,.0f} OTE")
                    lines.append(f"    β€’ Uncapped β€” no ceiling on commissions")
                    lines.append("")

                    # 2. Commission Structure
                    lines.append("2. COMMISSION STRUCTURE")
                    lines.append("")

                    comm_tiers = p.get("commission_tiers")
                    deal_tiers_data = p.get("deal_rate_tiers")
                    accel_t = p.get("accel_tiers")

                    if deal_types:
                        lines.append("  Commission is paid on all closed-won deals. Rates vary by deal type:")
                        lines.append("")
                        lines.append(f"  {'Deal Type':<14} {'ACV Range':<22} {'Rate':<10} {'Per-Deal Range':<20} {'Notes'}")
                        lines.append(f"  {'-'*13:<14} {'-'*20:<22} {'-'*8:<10} {'-'*18:<20} {'-'*20}")
                        for dt in deal_types:
                            acv_range = f"${dt['acv_min']:,.0f} – ${dt['acv_max']:,.0f}" if dt.get('acv_max') else f"${dt['acv_min']:,.0f}+"
                            payout_lo = dt['acv_min'] * dt['rate'] / 100
                            payout_hi = (dt.get('acv_max', dt['acv_min']) * dt['rate'] / 100) if dt.get('acv_max') else 0
                            payout_range = f"${payout_lo:,.0f} – ${payout_hi:,.0f}" if payout_hi else f"${payout_lo:,.0f}+"
                            lines.append(f"  {dt['name']:<14} {acv_range:<22} {dt['rate']:.0f}%{'':<7} {payout_range:<20} {dt.get('notes', '')}")
                        lines.append("")
                        lines.append("  Timing: Commissions earned upon fully-executed contract and first invoice")
                        lines.append("  issued. Paid on the first payroll cycle of the following month.")
                        lines.append("  Churn within 90 days triggers a proportional clawback.")
                    elif comm_tiers:
                        is_retro = retro
                        if is_retro:
                            lines.append("  Commission rates are applied retroactively. Once a higher attainment")
                            lines.append("  threshold is crossed, that rate applies to ALL revenue from dollar one.")
                        else:
                            lines.append("  Commission rates are applied on a marginal basis. Each rate applies")
                            lines.append("  only to revenue earned within that attainment band.")
                        lines.append("")
                        lines.append(f"  {'Attainment Level':<24} {'Commission Rate':<18}")
                        lines.append(f"  {'-' * 22:<24} {'-' * 16:<18}")
                        for i, tier in enumerate(comm_tiers):
                            upper_val, rate_val = tier[0], tier[1]
                            if upper_val is None:
                                prev_upper = int(comm_tiers[i-1][0])
                                lines.append(f"  {prev_upper}%+{'':<19} {rate_val:.1f}%")
                            elif i == 0:
                                lines.append(f"  0% – {int(upper_val)}%{'':<14} {rate_val:.1f}%")
                            else:
                                prev_upper = int(comm_tiers[i-1][0])
                                lines.append(f"  {prev_upper}% – {int(upper_val)}%{'':<12} {rate_val:.1f}%")
                    elif deal_tiers_data:
                        lines.append("  Commission is calculated as a percentage of deal ACV based on deal size.")
                        lines.append("")
                        lines.append(f"  {'Deal ACV Range':<28} {'Commission Rate':<18}")
                        lines.append(f"  {'-' * 26:<28} {'-' * 16:<18}")
                        for tier in deal_tiers_data:
                            mn_v, mx_v, rt_v = tier[0], tier[1], tier[2]
                            if mx_v is None:
                                lines.append(f"  ${mn_v:,.0f}+{'':<19} {rt_v:.1f}%")
                            else:
                                lines.append(f"  ${mn_v:,.0f} – ${mx_v:,.0f}{'':<8} {rt_v:.1f}%")

                    lines.append("")

                    # Deal Targets (if present in legacy data)
                    deal_targets = p.get("deal_targets")
                    section_num = 3
                    if deal_targets:
                        lines.append(f"{section_num}. ANNUAL QUOTA & DEAL TARGETS")
                        lines.append("")
                        lines.append(f"  On-target quota is ${p.get('annual_quota', 0):,.0f} ACV.")
                        lines.append("")
                        lines.append(f"  {'Segment':<14} {'# Deals':<10} {'Avg ACV':<14} {'Total ACV':<14} {'Rate':<8} {'Commission'}")
                        lines.append(f"  {'-'*13:<14} {'-'*8:<10} {'-'*12:<14} {'-'*12:<14} {'-'*6:<8} {'-'*12}")
                        total_deals = 0
                        total_acv = 0
                        total_comm_dt = 0
                        for dt in deal_targets:
                            t_acv = dt['num_deals'] * dt['avg_acv']
                            t_comm = t_acv * dt['rate'] / 100
                            total_deals += dt['num_deals']
                            total_acv += t_acv
                            total_comm_dt += t_comm
                            lines.append(f"  {dt['segment']:<14} {dt['num_deals']:<10} ${dt['avg_acv']:,.0f}{'':<6} ${t_acv:,.0f}{'':<6} {dt['rate']:.0f}%{'':<5} ${t_comm:,.0f}")
                        lines.append(f"  {'Total':<14} {total_deals:<10} {'β€”':<14} ${total_acv:,.0f}{'':<6} {'β€”':<8} ~${total_comm_dt:,.0f}")
                        lines.append("")
                        section_num += 1

                    # Ramp
                    ramp_list = p.get("ramp_pcts", [])
                    if ramp_list:
                        lines.append(f"{section_num}. QUOTA RAMP SCHEDULE")
                        lines.append("")
                        lines.append(f"  Commission rates remain constant throughout the ramp. Only the quota")
                        lines.append(f"  hurdle changes, giving time to build pipeline without sacrificing")
                        lines.append(f"  earnings on early deals closed.")
                        lines.append("")
                        monthly_quota = p.get('annual_quota', 0) / 12
                        lines.append(f"  {'Month':<10} {'Quota %':<12} {'Monthly Target':<18} {'Ann. Run Rate':<16} {'Notes'}")
                        lines.append(f"  {'-'*8:<10} {'-'*10:<12} {'-'*16:<18} {'-'*14:<16} {'-'*20}")
                        ramp_groups = []
                        idx = 0
                        while idx < len(ramp_list):
                            pct_val = ramp_list[idx]
                            start = idx + 1
                            while idx + 1 < len(ramp_list) and ramp_list[idx + 1] == pct_val:
                                idx += 1
                            end = idx + 1
                            ramp_groups.append((start, end, pct_val))
                            idx += 1
                        ramp_notes = {0: "Onboarding, no quota", 25: "First demos, early pipeline",
                                      50: "Close first deals", 75: "Full funnel operating", 100: "Full quota in effect"}
                        for start, end, pct_val in ramp_groups:
                            month_label = f"{start}–{end}" if start != end else str(start)
                            target = monthly_quota * pct_val / 100
                            run_rate = target * 12
                            note = ramp_notes.get(int(pct_val), "")
                            lines.append(f"  {month_label:<10} {int(pct_val)}%{'':<9} ${target:,.0f}{'':<8} ${run_rate:,.0f}{'':<6} {note}")
                        if len(ramp_list) < 12:
                            month_label = f"{len(ramp_list)+1}–12"
                            lines.append(f"  {month_label:<10} 100%{'':<8} ${monthly_quota:,.0f}{'':<8} ${monthly_quota*12:,.0f}{'':<6} Full quota in effect")
                        lines.append("")
                        section_num += 1

                    # Accelerators (for deal-size mode)
                    if accel_t:
                        lines.append(f"{section_num}. ACCELERATORS & OVERACHIEVEMENT")
                        lines.append("")
                        lines.append(f"  {'Attainment':<18} {'Rate / Multiplier':<22} {'Notes'}")
                        lines.append(f"  {'-'*16:<18} {'-'*20:<22} {'-'*20}")
                        for i, tier in enumerate(accel_t):
                            upper_val, mult_val = tier[0], tier[1]
                            if upper_val is None:
                                prev_upper = int(accel_t[i-1][0])
                                lines.append(f"  {prev_upper}%+{'':<14} {mult_val:.1f}x multiplier")
                            elif i == 0:
                                lines.append(f"  0% – {int(upper_val)}%{'':<9} {mult_val:.1f}x (base rate)")
                            else:
                                prev_upper = int(accel_t[i-1][0])
                                lines.append(f"  {prev_upper}% – {int(upper_val)}%{'':<7} {mult_val:.1f}x multiplier")
                        lines.append("")
                        section_num += 1

                    # Illustrative earnings β€” auto-generated from projections
                    lines.append(f"{section_num}. ILLUSTRATIVE EARNINGS SCENARIOS")
                    lines.append("")
                    if illustrative:
                        lines.append(f"  {'Scenario':<22} {'Deal Mix':<20} {'Total ACV':<14} {'Commission':<14} {'Total Cash':<14} {'Notes'}")
                        lines.append(f"  {'-'*20:<22} {'-'*18:<20} {'-'*12:<14} {'-'*12:<14} {'-'*12:<14} {'-'*20}")
                        for sc in illustrative:
                            lines.append(f"  {sc['label']:<22} {sc.get('deal_mix', 'β€”'):<20} ${sc['acv']:,.0f}{'':<4} ${sc['commission']:,.0f}{'':<4} ${sc['total_cash']:,.0f}{'':<4} {sc.get('notes', '')}")
                    else:
                        lines.append(f"  {'Attainment':<16} {'Revenue':<16} {'Commission':<16} {'Total Comp':<16} {'Net After Rep'}")
                        lines.append(f"  {'-'*14:<16} {'-'*14:<16} {'-'*14:<16} {'-'*14:<16} {'-'*14}")
                        for level in levels:
                            proj = compute_projection(p, mode, retro, level, months)
                            lines.append(f"  {level}%{'':<12} ${proj['actual_revenue']:,.0f}{'':<4} ${proj['commission']:,.0f}{'':<6} ${proj['total_comp']:,.0f}{'':<6} ${proj['net_after_rep']:,.0f}")
                    lines.append("")
                    section_num += 1

                    # Policies
                    lines.append(f"{section_num}. KEY POLICIES & TERMS")
                    lines.append("")
                    if policies:
                        for key, val in policies.items():
                            lines.append(f"  {key:<24} {val}")
                    else:
                        lines.append("  Commission Earned     Upon fully-executed contract and recognized revenue.")
                        lines.append("  Commission Paid       First payroll cycle following the month of close.")
                        lines.append("  Clawback              Proportional if customer churns within 90 days.")
                        lines.append("  Split Deals           Agreed upfront in writing; default 50/50.")
                        lines.append("  Plan Changes          Company may update at each FY with 30 days notice.")
                        if draw_amt > 0:
                            lines.append(f"  Draw Period           {p.get('draw_months', 0)} months from start. Ceases if employment ends.")
                        if equity:
                            lines.append(f"  Equity Vesting        {equity.get('vesting', '4-year vest, 1-year cliff')}.")
                        lines.append("  Territory             As assigned by Company. May be refined as team grows.")
                    lines.append("")
                    section_num += 1

                    # Acknowledgment
                    lines.append(f"{section_num}. ACKNOWLEDGMENT & ACCEPTANCE")
                    lines.append("")
                    lines.append("  By signing below, both parties agree to the terms of this")
                    lines.append("  Sales Compensation Plan.")
                    lines.append("")
                    lines.append("  ________________________________________")
                    lines.append("  Account Executive Signature        Date")
                    lines.append("")
                    lines.append("  ________________________________________")
                    lines.append("  Authorized Signatory               Date")

                    agreement_text = "\n".join(lines)

                    st.code(agreement_text, language=None)

                    st.download_button(
                        label="Download as text file",
                        data=agreement_text,
                        file_name=f"comp-plan-{detail_name.replace(' ', '-').lower()}.txt",
                        mime="text/plain",
                    )
        else:
            st.info("No saved plans yet. Save one from the Plan Builder tab.")