File size: 38,778 Bytes
d3ee1af
 
7f4e95a
9fd068e
f7d4e07
66e8e1d
9fd068e
 
d3ee1af
9fd068e
d3ee1af
9fd068e
d3ee1af
9fd068e
d3ee1af
61d113e
4690f5c
db82ded
2585639
 
f689170
75e9076
8e15e11
75e9076
b536db8
75e9076
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7672e20
8e15e11
 
e23c595
d4622c0
8e15e11
 
 
 
 
 
 
 
 
 
 
 
e23c595
 
7672e20
 
 
 
 
8d63bed
8e15e11
8d63bed
 
7271032
8d63bed
 
 
 
 
 
8e15e11
 
8d63bed
 
 
 
 
 
 
8e15e11
8d63bed
 
 
 
 
 
 
 
8e15e11
8d63bed
 
 
 
 
cc4a3d7
8e15e11
8d63bed
 
 
 
 
 
8e15e11
8d63bed
 
 
 
 
8e15e11
8d63bed
8e15e11
 
e23c595
638155a
8e15e11
 
 
638155a
8e15e11
 
 
 
638155a
 
d4622c0
8e15e11
 
d4622c0
 
 
8e15e11
d4622c0
006f4bc
d4622c0
 
 
 
 
 
8e15e11
d4622c0
 
 
 
7672e20
 
8e15e11
7672e20
8e15e11
d4622c0
 
 
 
 
 
 
8e15e11
 
d4622c0
 
 
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
006f4bc
 
8e15e11
 
 
 
dff0c65
 
8e15e11
 
 
dff0c65
638155a
8e15e11
 
 
 
 
 
 
dff0c65
638155a
8e15e11
 
 
 
 
dff0c65
638155a
8e15e11
 
 
 
 
 
 
dff0c65
 
8e15e11
9eaecc1
8e15e11
 
 
 
 
9eaecc1
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7672e20
 
 
 
8e15e11
7672e20
 
 
 
8e15e11
 
7672e20
 
 
 
 
 
 
 
8e15e11
d4622c0
7672e20
 
 
 
 
 
 
 
 
 
8e15e11
 
 
7672e20
 
 
 
 
 
 
 
 
 
 
8e15e11
 
7672e20
 
8e15e11
7672e20
8e15e11
 
 
7672e20
 
 
 
 
 
 
 
 
 
 
8e15e11
 
 
 
 
d4622c0
8e15e11
638155a
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638155a
8e15e11
 
 
 
7672e20
8e15e11
 
 
 
 
 
 
 
 
7672e20
8e15e11
 
 
 
 
 
 
 
 
7672e20
8e15e11
 
 
 
638155a
8e15e11
7672e20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc4a3d7
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7672e20
8e15e11
 
 
 
 
 
 
 
 
 
 
 
7672e20
 
 
 
 
8e15e11
 
 
 
9eaecc1
8e15e11
 
 
 
 
 
9eaecc1
8e15e11
 
e23c595
 
8e15e11
86f30b4
 
 
8e15e11
 
 
 
 
 
7672e20
 
86482bc
 
7672e20
 
 
 
 
 
 
 
 
 
 
 
86f30b4
7672e20
86f30b4
 
 
86482bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae082d
 
db82ded
 
 
 
 
86482bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e15e11
 
638155a
 
236a1e7
8e15e11
 
 
 
 
 
 
e23c595
638155a
8e15e11
 
0b5bfa0
8e15e11
638155a
 
8e15e11
 
 
 
e23c595
638155a
 
8e15e11
638155a
8e15e11
 
 
 
 
 
 
 
 
 
 
b536db8
 
8e15e11
 
 
 
 
 
 
 
 
 
9eaecc1
8e15e11
e23c595
86f30b4
 
 
 
8e15e11
9eaecc1
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86f30b4
8e15e11
 
 
 
86f30b4
8e15e11
 
 
 
 
 
 
 
9eaecc1
8e15e11
 
 
 
86f30b4
 
 
 
8e15e11
9eaecc1
8e15e11
 
 
 
9eaecc1
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7672e20
8e15e11
 
 
 
 
638155a
b536db8
e23c595
 
75e9076
 
 
 
66e8e1d
3cf50bf
66e8e1d
8e15e11
75e9076
8e15e11
75e9076
51874b6
75e9076
8e15e11
75e9076
66e8e1d
8e15e11
 
 
 
 
75e9076
 
86f30b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e15e11
 
 
006f4bc
8e15e11
 
 
 
 
 
 
 
006f4bc
8e15e11
 
 
 
3d6ab80
8e15e11
 
 
 
 
 
 
 
 
7672e20
8e15e11
 
 
 
 
3d6ab80
8e15e11
7672e20
8e15e11
 
 
 
 
 
 
7672e20
8e15e11
 
 
 
 
 
 
7672e20
8e15e11
 
 
3d6ab80
8e15e11
86f30b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e15e11
 
 
 
 
 
 
 
 
 
006f4bc
23b17f7
8e15e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d4e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc4a3d7
 
f7d4e07
 
 
 
 
 
 
 
7f4e95a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e15e11
 
 
 
 
 
 
 
7f4e95a
8e15e11
7f4e95a
8e15e11
 
 
7f4e95a
8e15e11
7f4e95a
8e15e11
 
 
7f4e95a
8e15e11
7f4e95a
8e15e11
 
 
 
 
7f4e95a
 
 
86482bc
8e15e11
86482bc
8e15e11
 
 
23b17f7
8e15e11
 
86482bc
 
 
 
8e15e11
 
 
 
 
b0ad1de
8e15e11
b0ad1de
8e15e11
 
 
b0ad1de
7672e20
 
 
 
 
8e15e11
 
f7d4e07
 
 
 
 
7f4e95a
 
 
 
 
 
f7d4e07
8e15e11
66e8e1d
638155a
 
 
 
7672e20
 
86f30b4
9eaecc1
86f30b4
 
75e9076
2585639
 
 
8e15e11
75e9076
638155a
75e9076
9fd068e
480ebcd
7271032
236a1e7
7271032
8e15e11
7271032
 
 
236a1e7
7271032
8e15e11
7271032
 
 
75e9076
8e15e11
61d113e
db82ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61d113e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2585639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e15e11
4690f5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75e9076
8e15e11
638155a
8e15e11
 
f491fd4
7271032
66e8e1d
8e15e11
75e9076
 
8e15e11
 
 
 
 
8d63bed
75e9076
 
7271032
8e15e11
 
 
 
 
 
7672e20
 
8e15e11
7672e20
 
cba140a
 
8e15e11
 
f7d4e07
cba140a
8e15e11
61d113e
86482bc
 
8e15e11
db82ded
 
 
 
4690f5c
86482bc
 
4690f5c
8e15e11
 
86482bc
 
 
61d113e
2585639
 
 
 
 
8e15e11
 
 
 
75e9076
8e15e11
7f4e95a
75e9076
7672e20
 
 
86f30b4
cba140a
 
61d113e
cba140a
 
8e15e11
cba140a
 
db82ded
6fc0bed
db82ded
 
 
 
86482bc
61d113e
 
 
 
 
2585639
 
 
 
 
 
4690f5c
 
 
 
 
 
cba140a
 
f7d4e07
cba140a
66e8e1d
49f15ae
811d8ba
9773d76
f689170
9fd068e
8e15e11
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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
print("APP STARTED", flush=True)

import html
import gradio as gr
import pandas as pd
import spaces

from app.db.repo import init_db
print("IMPORT 1 OK", flush=True)
from app.controller.campaign_controller import on_campaign_select
print("IMPORT 2 OK", flush=True)
from app.controller.session_loader import load_google_ads_data
print("IMPORT 3 OK", flush=True)
from app.ads1.ads_analyst import run_ads_analyst_card
print("IMPORT 4 OK", flush=True)
from app.ads1.search_term_optimizer import run_search_term_optimizer
from app.ads1.keyword_inspector import run_keyword_inspector
from app.ads1.budget_optimizer import run_budget_optimizer
from app.ads1.growth_finder import run_growth_finder
from app.ads1.campaign_doctor import run_campaign_doctor

# ==================================================
# ROMER / ADVISOR DASHBOARD THEME
# ==================================================

CSS = """
@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@400;520;600;700&family=Inter:wght@400;500;600&family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap');

:root {
    --custom-bg: #070708;
    --custom-divider: #232426;
    --custom-card-bg: #101112;
    --custom-sidebar: #0d0e0f;
    --custom-panel: #111214;
    --custom-text-muted: #9A9DA3;
    --custom-btn-primary: #5E6BFF;
    --on-surface: #e5e2e3;
    --on-surface-variant: #c6c5d8;
    --secondary: #50d8e9;
    --tertiary: #ffb689;
    --primary: #bec2ff;
}

html,
body,
.gradio-container {
    background: var(--custom-bg) !important;
    color: var(--on-surface) !important;
    font-family: Inter, sans-serif !important;
    color-scheme: dark !important;
}

.gradio-container {
    max-width: 100% !important;
    padding: 0 !important;
}

.main,
.contain {
    max-width: none !important;
}

footer,
.api-docs,
.built-with {
    display: none !important;
}

.gradio-container,
.gradio-container * {
    color: var(--on-surface);
}

/* ================================
   HEADER
================================ */

#advisor-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 80px;
    width: 100%;
    background: var(--custom-bg);
    border-bottom: 1px solid var(--custom-divider);
    z-index: 50;
}

#advisor-header .header-inner {
    max-width: 1728px;
    height: 100%;
    margin: 0 auto;
    padding: 0 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

#advisor-header .brand {
    display: flex;
    align-items: center;
    gap: 8px;
}

#advisor-header .avatar {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    border: 1px solid var(--custom-text-muted);
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: Manrope, sans-serif;
    font-weight: 700;
    font-size: 14px;
    color: var(--on-surface);
}

#advisor-header .title {
    font-family: Manrope, sans-serif;
    font-size: 24px;
    line-height: 1.2;
    font-weight: 700;
    letter-spacing: 0;
    color: var(--on-surface);
}

/* ================================
   HERO
================================ */

#advisor-shell {
    max-width: 1728px;
    margin: 80px auto 0;
    padding: 0 32px 56px;
}

.hero-section {
    position: relative;
    padding: 128px 0 80px;
}

.hero-inner {
    max-width: 1516px;
    margin: 0 auto;
    width: 100%;
}

.hero-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 40px;
}

.hero-title {
    font-family: Manrope, sans-serif;
    font-size: 76px !important;
    line-height: 1.1 !important;
    letter-spacing: 0;
    font-weight: 520 !important;
    color: var(--on-surface) !important;
    max-width: 1000px;
    margin-bottom: 16px;
}

.hero-subtitle {
    font-family: Inter, sans-serif;
    font-size: 19px;
    line-height: 1.6;
    color: var(--custom-text-muted) !important;
    margin-bottom: 24px;
}

/* ================================
   DASHBOARD SHELL
================================ */

#dashboard-shell {
    width: 100%;
    min-height: 620px;
    display: flex;
    overflow: hidden;
    position: relative;
    background: var(--custom-card-bg);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    box-shadow: 0 25px 50px rgba(0, 0, 0, 0.45), inset 0 1px 0 rgba(255, 255, 255, 0.10);
}

#dashboard-shell > .form,
#dashboard-shell > .block,
#dashboard-shell > div {
    border: 0 !important;
}

.dashboard-row {
    gap: 0 !important;
    width: 100%;
}

.campaign-sidebar {
    flex: 0 0 256px !important;
    min-width: 256px !important;
    max-width: 256px !important;
    background: var(--custom-sidebar);
    border-right: 1px solid var(--custom-divider);
    padding: 16px !important;
}

.center-workspace {
    background: #0a0a0b;
    padding: 24px !important;
    gap: 24px !important;
    min-width: 0;
}

.right-panel {
    flex: 0 0 320px !important;
    min-width: 320px !important;
    max-width: 320px !important;
    background: var(--custom-panel);
    border-left: 1px solid var(--custom-divider);
    padding: 16px !important;
}

.panel-label {
    color: #ffffff !important;
    font-size: 10px;
    line-height: 1;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    font-weight: 700;
    opacity: 1;
    margin: 0 0 24px;
    padding: 0 16px;
}

/* ================================
   GRADIO COMPONENT RESET
================================ */

.campaign-sidebar .block,
.center-workspace .block,
.right-panel .block {
    background: transparent !important;
    border: 0 !important;
    box-shadow: none !important;
}

.campaign-radio,
.campaign-radio > div,
.campaign-radio fieldset,
.campaign-radio .wrap {
    background: transparent !important;
    border: 0 !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
}

.campaign-radio .container,
.campaign-radio .options,
.campaign-radio [role="radiogroup"] {
    display: flex !important;
    flex-direction: column !important;
    gap: 4px !important;
    overflow: visible !important;
    max-height: none !important;
}

.campaign-radio label {
    display: flex !important;
    align-items: center !important;
    gap: 12px !important;
    width: 100% !important;
    min-height: 36px !important;
    margin: 0 !important;
    padding: 8px 12px !important;
    border: 1px solid transparent !important;
    border-radius: 6px !important;
    background: transparent !important;
    color: var(--custom-text-muted) !important;
    font-size: 14px !important;
    line-height: 1.35 !important;
    cursor: pointer !important;
}

.campaign-radio label::before {
    content: "grid_view";
    font-family: "Material Symbols Outlined";
    font-size: 18px;
    line-height: 1;
    color: rgba(154, 157, 163, 0.55);
    flex: 0 0 auto;
}

.campaign-radio label:hover,
.campaign-radio label:has(input:checked) {
    background: rgba(255, 255, 255, 0.04) !important;
    border-color: rgba(255, 255, 255, 0.05) !important;
    color: var(--on-surface) !important;
}

.campaign-radio label:has(input:checked)::before {
    color: var(--secondary);
}

.campaign-radio input {
    display: none !important;
}

.campaign-radio span {
    color: inherit !important;
    white-space: normal !important;
}

/* ================================
   KPI / CHART / CARDS
================================ */

.kpi-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
}

.kpi-card {
    background: var(--custom-card-bg);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    padding: 20px;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.10);
}

.kpi-top {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 12px;
}

.kpi-label {
    color: #ffffff !important;
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    font-weight: 700;
    opacity: 0.6;
}

.kpi-status {
    font-size: 9px;
    color: rgba(255, 255, 255, 0.68) !important;
    text-transform: uppercase;
    letter-spacing: 0;
    white-space: nowrap;
}

.kpi-value {
    font-family: Manrope, sans-serif;
    font-size: 24px;
    line-height: 1.2;
    color: #ffffff !important;
    font-weight: 700;
}

.kpi-note {
    margin-top: 12px;
    font-size: 11px;
    font-weight: 600;
}

.note-sky {
    color: #50d8e9 !important;
}

.note-brown {
    color: #c88a5a !important;
}

.note-olive {
    color: #a9b75f !important;
}

.note-violet {
    color: #bec2ff !important;
}

.signal-card {
    background: var(--custom-card-bg);
    border: 1px solid var(--custom-divider);
    border-radius: 8px;
    padding: 16px;
    height: 220px;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.10);
    display: flex;
    flex-direction: column;
}

.signal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.signal-title {
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: #ffffff !important;
}

.signal-box {
    position: relative;
    flex: 1;
    overflow: hidden;
    border-radius: 6px;
    background: rgba(7, 7, 8, 0.5);
    border: 1px solid rgba(255, 255, 255, 0.02);
}

.grid-lines,
.vertical-lines {
    position: absolute;
    inset: 0;
    pointer-events: none;
}

.grid-lines {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 8px 0;
    opacity: 0.12;
}

.grid-lines span {
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.vertical-lines {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
}

.vertical-lines span {
    border-right: 1px solid rgba(255, 255, 255, 0.05);
}

.signal-card svg {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 80%;
}

.ai-row {
    gap: 12px !important;
    align-items: stretch !important;
}

.ai-card-html,
.ai-button-card {
    background: var(--custom-card-bg) !important;
    border: 1px solid var(--custom-divider) !important;
    border-radius: 8px !important;
    padding: 16px !important;
    min-height: 116px !important;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08) !important;
}

.ai-row > *,
.ai-row .block {
    align-self: stretch !important;
}

.ai-card-html h3 {
    margin: 0 0 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    color: #ffffff !important;
    font-size: 14px;
    font-weight: 700;
}

.ai-card-html p {
    margin: 0;
    color: #ffffff !important;
    font-size: 14px;
    line-height: 1.5;
}

.ai-button-card {
    background: var(--custom-card-bg) !important;
    border: 1px solid var(--custom-divider) !important;
    border-radius: 8px !important;
    color: var(--on-surface) !important;
    text-align: left !important;
    font-size: 14px !important;
    font-weight: 700 !important;
    transition: border-color 0.15s ease, transform 0.15s ease, background 0.15s ease;
    white-space: pre-line !important;
    margin: 0 !important;
    height: 116px !important;
    position: relative !important;
    overflow: hidden !important;
}

.ai-button-card button,
button.ai-button-card {
    height: 100% !important;
    min-height: 116px !important;
    margin: 0 !important;
    padding: 16px !important;
    align-items: flex-start !important;
    justify-content: flex-start !important;
    text-align: left !important;
    white-space: pre-line !important;
    background: var(--custom-card-bg) !important;
    color: var(--on-surface) !important;
    border: 1px solid var(--custom-divider) !important;
    border-radius: 8px !important;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08) !important;
    line-height: 1.55 !important;
    position: relative !important;
    font-size: 14px !important;
    font-weight: 700 !important;
}

.ai-button-card button::after,
button.ai-button-card::after {
    content: "";
    position: absolute;
    left: 16px;
    right: 16px;
    top: 48px;
    height: 1px;
    background: rgba(255, 255, 255, 0.05);
}

.ai-button-card button::before,
button.ai-button-card::before {
    position: absolute;
    left: 16px;
    right: 16px;
    top: 64px;
    color: #ffffff !important;
    font-size: 14px;
    font-weight: 400;
    line-height: 1.5;
}

.ads-analyst-card button::before,
button.ads-analyst-card::before {
    content: "Campaign insights.";
}

.budget-optimizer-card button::before,
button.budget-optimizer-card::before {
    content: "Where to adjust spend?";
}

.keyword-inspector-card button::before,
button.keyword-inspector-card::before {
    content: "Winning versus wasting keywords.";
}

.search-term-cleaner-card button::before,
button.search-term-cleaner-card::before {
    content: "Optimize search terms.";
}

.ai-button-card:hover,
.ai-button-card:hover button,
button.ai-button-card:hover {
    border-color: rgba(94, 107, 255, 0.7) !important;
    background: #141519 !important;
    transform: translateY(-1px);
}

.clickable-card {
    cursor: pointer;
    transition: border-color 0.15s ease,
                transform 0.15s ease,
                background 0.15s ease;
}

.clickable-card:hover {
    border-color: rgba(94, 107, 255, 0.7) !important;
    background: #141519 !important;
    transform: translateY(-1px);
}

.snapshot {
    background: var(--custom-card-bg);
    border: 1px solid var(--custom-divider);
    border-radius: 8px;
    padding: 16px;
    color: var(--on-surface);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08);
}

.snapshot h3 {
    margin: 0 0 8px;
    font-size: 14px;
    font-weight: 700;
}

.snapshot p {
    margin: 0;
    color: var(--custom-text-muted);
    font-size: 14px;
}

#ads-output {
    margin-top: 0;
    padding: 16px;
    min-height: 140px;
    border: 1px solid var(--custom-divider);
    border-radius: 8px;
    background: var(--custom-card-bg);
    color: var(--on-surface);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08);
}

#ads-output,
#ads-output * {
    color: var(--on-surface) !important;
}

.advisor-intel-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    padding: 0 4px 20px;
    margin-bottom: 8px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    font-size: 14px;
    font-weight: 700;
    color: #ffffff !important;
}

.advisor-intel-title * {
    color: #ffffff !important;
}

.advisor-intel-title .material-symbols-outlined {
    color: #ffffff !important;
    font-size: 20px;
}

.pulse-dot {
    width: 6px;
    height: 6px;
    border-radius: 999px;
    background: var(--secondary);
    display: inline-block;
}

.intel-section {
    margin-top: 28px;
}

.intel-label {
    color: #c7c9d1 !important;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    opacity: 1;
    margin-bottom: 12px;
}

.intel-box {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    padding: 16px;
    color: #ffffff !important;
    font-size: 14px;
    line-height: 1.5;
}

.intel-box * {
    color: #ffffff !important;
}

.text-primary {
    color: #ffffff !important;
    font-weight: 700;
}

.text-secondary {
    color: #ffffff !important;
    font-weight: 600;
}

@media (max-width: 1200px) {
    #dashboard-shell,
    .dashboard-row {
        flex-direction: column !important;
    }

    .campaign-sidebar,
    .right-panel {
        flex: auto !important;
        min-width: 100% !important;
        max-width: 100% !important;
        border-left: 0;
    }

    .campaign-sidebar {
        border-right: 0;
        border-bottom: 1px solid var(--custom-divider);
    }

    .right-panel {
        border-top: 1px solid var(--custom-divider);
    }
}

@media (max-width: 800px) {
    #advisor-shell {
        padding: 0 16px 32px;
    }

    #advisor-header .header-inner {
        padding: 0 16px;
    }

    .hero-section {
        padding: 80px 0 48px;
    }

    .hero-title {
        font-size: 42px !important;
    }

    .kpi-grid {
        grid-template-columns: 1fr;
    }
}
"""


# ==================================================
# INIT
# ==================================================

def startup():
    try:
        init_db()
        print("DB initialized successfully", flush=True)
    except Exception as e:
        print("DB failed:", e, flush=True)


# ==================================================
# HTML HELPERS
# ==================================================

def format_money(value):
    try:
        return f"£{float(value):,.2f}"
    except (TypeError, ValueError):
        return "£0.00"


def format_number(value):
    try:
        return f"{float(value):,.0f}"
    except (TypeError, ValueError):
        return "0"


def format_percent(value):
    try:
        numeric = float(value)
        if abs(numeric) <= 1:
            numeric *= 100
        return f"{numeric:.2f}%"
    except (TypeError, ValueError):
        return "0.00%"


def build_hero_html(spend, leads, cpl, count):
    return f"""
    <section class="hero-section">
        <div class="hero-inner">
            <div class="hero-row">
                <div>
                    <h1 class="hero-title">AI-powered Google Ads optimization</h1>
                    <p class="hero-subtitle">
                        Spend {format_money(spend)} | Leads {leads} | Avg CPL {format_money(cpl)} | Campaigns {count}
                    </p>
                </div>
                <div></div>
            </div>
        </div>
    </section>
    """


def build_kpi_html(spend, leads, cpl, count):
    return f"""
    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">Spend</div>
                <div class="kpi-status">[SYNC: ACTIVE]</div>
            </div>
            <div class="kpi-value">{format_money(spend)}</div>
            <div class="kpi-note note-sky">Live Google Ads data</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">Leads</div>
                <div class="kpi-status">[QUEUE: {leads}]</div>
            </div>
            <div class="kpi-value">{leads}</div>
            <div class="kpi-note note-brown">Tracked conversions</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">CPL</div>
                <div class="kpi-status">[HEARTBEAT: OK]</div>
            </div>
            <div class="kpi-value">{format_money(cpl)}</div>
            <div class="kpi-note note-olive">Cost per lead</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">Campaigns</div>
                <div class="kpi-status">[LOAD: OPT]</div>
            </div>
            <div class="kpi-value">{count}</div>
            <div class="kpi-note note-violet">Available for analysis</div>
        </div>
    </div>
    """


def build_campaign_kpi_html(campaign_df):
    if campaign_df is None or campaign_df.empty:
        return build_kpi_html(0, 0, 0, 0)

    spend = campaign_df["cost"].sum() if "cost" in campaign_df else 0
    clicks = campaign_df["clicks"].sum() if "clicks" in campaign_df else 0
    conversions = campaign_df["conversions"].sum() if "conversions" in campaign_df else 0
    cpl = spend / conversions if conversions else 0

    if "ctr" in campaign_df:
        ctr = campaign_df["ctr"].mean()
    else:
        impressions = campaign_df["impressions"].sum() if "impressions" in campaign_df else 0
        ctr = clicks / impressions if impressions else 0

    return f"""
    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">Spend</div>
                <div class="kpi-status">[CAMPAIGN]</div>
            </div>
            <div class="kpi-value">{format_money(spend)}</div>
            <div class="kpi-note note-sky">Selected campaign spend</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">Clicks</div>
                <div class="kpi-status">[TRAFFIC]</div>
            </div>
            <div class="kpi-value">{format_number(clicks)}</div>
            <div class="kpi-note note-brown">Campaign traffic</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">CPL</div>
                <div class="kpi-status">[EFFICIENCY]</div>
            </div>
            <div class="kpi-value">{format_money(cpl)}</div>
            <div class="kpi-note note-olive">{format_number(conversions)} leads recorded</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-top">
                <div class="kpi-label">CTR</div>
                <div class="kpi-status">[RESPONSE]</div>
            </div>
            <div class="kpi-value">{format_percent(ctr)}</div>
            <div class="kpi-note note-violet">Click-through rate</div>
        </div>
    </div>
    """


SIGNAL_FLOW_HTML = """
<div class="signal-card">
    <div class="signal-header">
        <div>
            <span class="signal-title">Signal Flow</span>
            <span class="kpi-status"> [LATENCY: 12ms]</span>
        </div>
        <div class="kpi-status">
            <span style="color: var(--primary);">Revenue</span>
            <span style="margin-left: 16px; color: var(--custom-text-muted);">Goal</span>
        </div>
    </div>
    <div class="signal-box">
        <div class="grid-lines"><span></span><span></span><span></span><span></span></div>
        <div class="vertical-lines"><span></span><span></span><span></span><span></span><span></span><span></span></div>
        <svg preserveAspectRatio="none" viewBox="0 0 100 100">
            <defs>
                <linearGradient id="gradient-flow-v3" x1="0%" x2="0%" y1="0%" y2="100%">
                    <stop offset="0%" stop-color="#5E6BFF" stop-opacity="0.15"></stop>
                    <stop offset="100%" stop-color="#5E6BFF" stop-opacity="0"></stop>
                </linearGradient>
                <filter height="140%" id="glow" width="140%" x="-20%" y="-20%">
                    <feGaussianBlur result="blur" stdDeviation="1.5"></feGaussianBlur>
                    <feComposite in="SourceGraphic" in2="blur" operator="over"></feComposite>
                </filter>
            </defs>
            <path d="M0,80 C20,78 35,85 50,65 C65,45 80,30 100,25 L100,100 L0,100 Z" fill="url(#gradient-flow-v3)"></path>
            <path d="M0,80 C20,78 35,85 50,65 C65,45 80,30 100,25" fill="none" filter="url(#glow)" stroke="#5E6BFF" stroke-linecap="round" stroke-width="1"></path>
            <circle cx="20" cy="78" fill="#5E6BFF" r="1"></circle>
            <circle cx="50" cy="65" fill="white" r="1.5" stroke="#5E6BFF" stroke-width="0.5"></circle>
            <circle cx="80" cy="30" fill="#5E6BFF" r="1"></circle>
        </svg>
        <div style="position: absolute; bottom: 4px; right: 8px; color: rgba(154,157,163,0.35); font-size: 9px;">t: 127.4s</div>
        <div style="position: absolute; top: 8px; left: 8px; color: rgba(154,157,163,0.35); font-size: 9px;">y: $V</div>
    </div>
</div>
"""


def build_signal_flow_html(dfs=None):
    if not dfs or "hourly" not in dfs or dfs["hourly"] is None or dfs["hourly"].empty:
        return """
        <div class="signal-card">
            <div class="signal-header">
                <div>
                    <span class="signal-title">Traffic Trend</span>
                    <span class="kpi-status"> [WAITING]</span>
                </div>
            </div>
            <div class="signal-box" style="display:flex;align-items:center;justify-content:center;color:var(--custom-text-muted);font-size:14px;">
                Waiting for Google Ads API data streaming...
            </div>
        </div>
        """

    hourly_df = dfs["hourly"].copy()
    required_columns = {"date", "clicks", "cost"}
    if not required_columns.issubset(hourly_df.columns):
        return """
        <div class="signal-card">
            <div class="signal-header">
                <div>
                    <span class="signal-title">Traffic Trend</span>
                    <span class="kpi-status"> [DATA CHECK]</span>
                </div>
            </div>
            <div class="signal-box" style="display:flex;align-items:center;justify-content:center;color:var(--custom-text-muted);font-size:14px;">
                Hourly data is missing date, clicks, or cost columns.
            </div>
        </div>
        """

    hourly_df["date"] = pd.to_datetime(hourly_df["date"], errors="coerce").dt.date
    hourly_df["clicks"] = pd.to_numeric(hourly_df["clicks"], errors="coerce").fillna(0)
    hourly_df["cost"] = pd.to_numeric(hourly_df["cost"], errors="coerce").fillna(0)
    hourly_df = hourly_df.dropna(subset=["date"])

    df_daily = (
        hourly_df.groupby("date", as_index=False)
        .agg({"clicks": "sum", "cost": "sum"})
        .sort_values("date")
        .tail(14)
        .reset_index(drop=True)
    )

    if df_daily.empty:
        return build_signal_flow_html(None)

    total_days = len(df_daily)
    total_clicks = int(df_daily["clicks"].sum())
    total_cost = float(df_daily["cost"].sum())

    if (
        "campaigns" in dfs
        and dfs["campaigns"] is not None
        and not dfs["campaigns"].empty
        and "conversions" in dfs["campaigns"].columns
    ):
        total_tours = int(dfs["campaigns"]["conversions"].fillna(0).sum())
    else:
        total_tours = int(total_clicks * 0.06)

    max_clicks = df_daily["clicks"].max()
    max_clicks = max_clicks if max_clicks > 0 else 1

    points = []
    for idx, row in df_daily.iterrows():
        x = (idx / (total_days - 1)) * 100 if total_days > 1 else 50
        y = 100 - ((row["clicks"] / max_clicks) * 75 + 15)
        points.append((x, y))

    line_path = "M " + " L ".join(f"{x:.1f},{y:.1f}" for x, y in points)
    first_x = points[0][0]
    last_x = points[-1][0]
    area_path = f"{line_path} L {last_x:.1f},100 L {first_x:.1f},100 Z"

    peak_idx = int(df_daily["clicks"].idxmax())
    dot_indices = sorted({0, peak_idx, total_days - 1})
    dots_html = "".join(
        f'<circle cx="{points[i][0]:.1f}" cy="{points[i][1]:.1f}" fill="#5E6BFF" r="1.8" stroke="white" stroke-width="0.6"></circle>'
        for i in dot_indices
        if i < len(points)
    )

    return f"""
    <div class="signal-card">
        <div class="signal-header">
            <div>
                <span class="signal-title">Traffic Trend</span>
                <span class="kpi-status"></span>
            </div>
            <div class="kpi-status">
                <span style="color: var(--primary);">{format_number(total_clicks)} Clicks</span>
                <span style="margin-left: 16px; color: var(--secondary);">{format_number(total_tours)} Tours Booked</span>
                <span style="margin-left: 16px; color: var(--custom-text-muted);">{format_money(total_cost)} Spent</span>
            </div>
        </div>
        <div class="signal-box">
            <div class="grid-lines"><span></span><span></span><span></span><span></span></div>
            <div class="vertical-lines"><span></span><span></span><span></span><span></span><span></span><span></span></div>
            <svg preserveAspectRatio="none" viewBox="0 0 100 100">
                <defs>
                    <linearGradient id="gradient-flow-daily" x1="0%" x2="0%" y1="0%" y2="100%">
                        <stop offset="0%" stop-color="#5E6BFF" stop-opacity="0.25"></stop>
                        <stop offset="100%" stop-color="#5E6BFF" stop-opacity="0"></stop>
                    </linearGradient>
                    <filter height="140%" id="glow-daily" width="140%" x="-20%" y="-20%">
                        <feGaussianBlur result="blur" stdDeviation="1"></feGaussianBlur>
                        <feComposite in="SourceGraphic" in2="blur" operator="over"></feComposite>
                    </filter>
                </defs>
                <path d="{area_path}" fill="url(#gradient-flow-daily)"></path>
                <path d="{line_path}" fill="none" filter="url(#glow-daily)" stroke="#5E6BFF" stroke-linecap="round" stroke-width="1.2"></path>
                {dots_html}
            </svg>
            <div style="position: absolute; bottom: 6px; right: 10px; color: #ffffff !important; font-size: 10px; font-weight: 500;">Last 14 days</div>
            <div style="position: absolute; top: 6px; left: 10px; color: #ffffff !important; font-size: 10px; font-weight: 500;">Daily Clicks (Last 14 Days)</div>
        </div>
    </div>
    """


SIGNAL_FLOW_HTML = build_signal_flow_html()


def build_right_panel_html(doctor_result=None):
    doctor_result = doctor_result or {}

    def campaign_block(key, fallback_name, fallback_reason):
        item = doctor_result.get(key) or {}
        name = html.escape(str(item.get("name") or fallback_name))
        reason = html.escape(str(item.get("reason") or fallback_reason))
        return f'<span class="text-primary">{name}</span><br>{reason}'

    best_html = campaign_block(
    "best_campaign",
    "Awaiting campaign data",
    "Top performer will appear here after data loads.",
    )

    worst_html = campaign_block(
        "budget_drain",
        "Awaiting campaign data",
        "Lowest-performing campaign will appear here.",
    )

    scale_html = campaign_block(
        "scale_candidate",
        "Awaiting campaign data",
        "Best growth opportunity will appear here.",
    )

    return f"""
<div class="advisor-intel-title">
    <div style="display:flex;align-items:center;gap:10px;">
        <span class="material-symbols-outlined">bolt</span>
        Advisor Intelligence
    </div>
    <span class="pulse-dot"></span>
</div>
<div class="intel-section">
    <div class="intel-label">Best Campaign</div>
    <div class="intel-box">
        {best_html}
    </div>
</div>
<div class="intel-section">
    <div class="intel-label">Budget Drain</div>
    <div class="intel-box">
        {worst_html}
    </div>
</div>
<div class="intel-section">
    <div class="intel-label">Scalable Candidate</div>
    <div class="intel-box">
        {scale_html}
    </div>
</div>
"""


RIGHT_PANEL_HTML = build_right_panel_html()


def ai_card(title, body, onclick=""):
    return f"""
    <div class="ai-card-html clickable-card" onclick="{onclick}">
        <h3>{title}</h3>
        <p>{body}</p>
    </div>
    """


def ai_button_card(title, body):
    return f"{title}\n{body}"


# ==================================================
# DATA
# ==================================================

def initial_data_load():
    print("STARTING DATA LOAD", flush=True)
    dfs = load_google_ads_data()
    print("GOOGLE ADS DATA LOADED", flush=True)
    from app.ui.dashboard import get_dashboard_data

    spend, leads, cpl, count, formatted_df = get_dashboard_data()
    print("DASHBOARD DATA LOADED", flush=True)
    campaign_choices = (
        formatted_df["Campaign"].dropna().astype(str).tolist()
        if "Campaign" in formatted_df.columns
        else []
    )
    hero_html = build_hero_html(spend, leads, cpl, count)
    kpi_html = build_kpi_html(spend, leads, cpl, count)
    try:
        signal_flow_html = build_signal_flow_html(dfs)
    except Exception as e:
        print(f"SIGNAL FLOW CHART FAILED: {e}", flush=True)
        signal_flow_html = build_signal_flow_html()
    try:
        doctor_result = run_campaign_doctor(dfs)
    except Exception as e:
        print(f"CAMPAIGN DOCTOR FAILED: {e}", flush=True)
        doctor_result = None
    right_panel_html = build_right_panel_html(doctor_result)
    return dfs, gr.update(choices=campaign_choices, value=None), hero_html, kpi_html, signal_flow_html, right_panel_html


# ==================================================
# CAMPAIGN SELECT
# ==================================================

def campaign_selected(campaign_name, full_state):
    if not campaign_name:
        return None, gr.update()

    campaign_state = on_campaign_select(full_state, campaign_name)
    return campaign_state, build_campaign_kpi_html(campaign_state.get("campaign_df"))

# def load_campaign_doctor(dfs):
#     result = run_campaign_doctor(dfs)
#     return update_right_panel(result)

# ==================================================
# ADS ANALYST
# ==================================================

@spaces.GPU(duration=120)
def run_ads_card(state):
    try:
        if not state:
            return "Select a campaign first."

        dfs = state.get("full_dfs")
        campaign_name = state.get("campaign_name")

        if dfs is None or campaign_name is None:
            return "Campaign state is not properly initialized."

        return run_ads_analyst_card(dfs, campaign_name=campaign_name)

    except Exception as e:
        return f"Analysis failed: {e}"
    
@spaces.GPU(duration=120)
def run_budget_card(state):
    try:
        if not state:
            return "Select a campaign first."

        dfs = state.get("full_dfs")
        campaign_name = state.get("campaign_name")

        if dfs is None or campaign_name is None:
            return "Campaign state is not properly initialized."

        return run_budget_optimizer(dfs, campaign_name=campaign_name)

    except Exception as e:
        return f"Analysis failed: {e}"
    
@spaces.GPU(duration=120)
def run_search_term_optimizer_card(state):
    try:
        if not state:
            return "Select a campaign first."

        dfs = state.get("full_dfs")
        campaign_name = state.get("campaign_name")

        if dfs is None or campaign_name is None:
            return "Campaign state is not properly initialized."

        return run_search_term_optimizer(dfs, campaign_name=campaign_name)

    except Exception as e:
        return f"Search term optimization failed: {e}"
    
@spaces.GPU(duration=120)
def run_growth_finder_card(state):
    try:
        if not state:
            return "Select a campaign first."

        dfs = state.get("full_dfs")
        campaign_name = state.get("campaign_name")

        if dfs is None or campaign_name is None:
            return "Campaign state is not properly initialized."

        return run_growth_finder(dfs, campaign_name=campaign_name)

    except Exception as e:
        return f"Search term optimization failed: {e}"

@spaces.GPU(duration=120)
def run_keyword_inspector_card(state):
    try:
        if not state:
            return "Select a campaign first."

        dfs = state.get("full_dfs")
        campaign_name = state.get("campaign_name")

        if dfs is None or campaign_name is None:
            return "Campaign state is not properly initialized."

        return run_keyword_inspector(dfs, campaign_name=campaign_name)

    except Exception as e:
        return f"Search term optimization failed: {e}"

# ==================================================
# UI
# ==================================================

with gr.Blocks(fill_height=True, fill_width=True, css=CSS) as demo:
    full_state = gr.State()
    campaign_state = gr.State()

    gr.HTML("""
    <div id="advisor-header">
        <div class="header-inner">
            <div class="brand">
                <div class="avatar">A</div>
                <div class="title">Advisor</div>
            </div>
        </div>
    </div>
    """)

    with gr.Column(elem_id="advisor-shell"):
        hero_html = gr.HTML()

        with gr.Row(elem_id="dashboard-shell", elem_classes=["dashboard-row"]):
            with gr.Column(elem_classes=["campaign-sidebar"]):
                gr.HTML('<div class="panel-label">Campaigns</div>')
                campaign_picker = gr.Radio(
                    choices=[],
                    show_label=False,
                    container=False,
                    elem_classes=["campaign-radio"],
                )

            with gr.Column(scale=1, elem_classes=["center-workspace"]):
                kpi_html = gr.HTML()
                signal_flow_html = gr.HTML(SIGNAL_FLOW_HTML)

                with gr.Row(elem_classes=["ai-row"]):
                    analyze_ads_card = gr.Button(
                        value="Ads Analyst",
                        elem_classes=["ai-button-card", "ads-analyst-card"],
                    )
                    budget_optimizer_card = gr.Button(
                        value="Budget Optimizer",
                        elem_classes=["ai-button-card", "budget-optimizer-card"],
                    )
                    keyword_inspector_card = gr.Button(
                        value="Keyword Inspector",
                        elem_classes=["ai-button-card", "keyword-inspector-card"],
                    )

                with gr.Row(elem_classes=["ai-row"]):
                    search_term_cleaner_card = gr.Button(
                        value="Search Term Cleaner",
                        elem_classes=["ai-button-card", "search-term-cleaner-card"],
                    )
                    growth_finder_card = gr.Button(
                        value="Growth Finder",
                        elem_classes=["ai-button-card", "growth-finder-card"],
                    )
                    
                ads_output = gr.Markdown(
                    value="Select a campaign and click Ads Analyst.",
                    elem_id="ads-output",
                )

            with gr.Column(elem_classes=["right-panel"]):
                right_panel_html = gr.HTML(RIGHT_PANEL_HTML)

    campaign_picker.change(
        fn=campaign_selected,
        inputs=[campaign_picker, full_state],
        outputs=[campaign_state, kpi_html],
    )

    analyze_ads_card.click(
        fn=run_ads_card,
        inputs=campaign_state,
        outputs=ads_output,
    )

    budget_optimizer_card.click(
        fn=run_budget_card,
        inputs=campaign_state,
        outputs=ads_output,
    )

    search_term_cleaner_card.click(
        fn=run_search_term_optimizer_card,
        inputs=campaign_state,
        outputs=ads_output,
    )

    growth_finder_card.click(
        fn=run_growth_finder_card,
        inputs=campaign_state,
        outputs=ads_output,
    )

    keyword_inspector_card.click(
        fn=run_keyword_inspector_card,
        inputs=campaign_state,
        outputs=ads_output,
    )

    demo.load(
        fn=initial_data_load,
        outputs=[full_state, campaign_picker, hero_html, kpi_html, signal_flow_html, right_panel_html],
    )

    demo.load(fn=startup)

demo.queue()

if __name__ == "__main__":
    demo.launch()