File size: 47,251 Bytes
77461d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf01f35
 
00e34a2
77461d0
00e34a2
 
bf01f35
77461d0
 
bf01f35
00e34a2
bf01f35
 
77461d0
bf01f35
00e34a2
bf01f35
 
 
77461d0
bf01f35
77461d0
bf01f35
77461d0
bf01f35
77461d0
 
 
 
bf01f35
77461d0
 
 
bf01f35
77461d0
bf01f35
77461d0
 
 
 
 
 
 
00e34a2
77461d0
 
 
 
 
 
bf01f35
77461d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "marimo>=0.23.1",
#     "numpy==2.4.4",
#     "pandas==3.0.2",
#     "svgwrite>=1.4.3",
#     "openpyxl>=3.1.0",
#     "cairosvg==2.9.0",
# ]
# ///

import marimo

__generated_with = "0.23.0"
app = marimo.App(
    width="full",
    css_file="/usr/local/_marimo/custom.css",
    auto_download=["html"],
)


@app.cell
def _():
    import math
    from pathlib import Path

    import marimo as mo
    import numpy as np
    import pandas as pd
    import svgwrite


    return Path, math, mo, np, pd, svgwrite


@app.cell
def _(mo):
    mo.md(r"""
    <style>
        /* Main container for the whole notebook UI */
        .coffee-sites-notebook {
            /* Color variables (used throughout for consistency) */
            --bg: #f7f4ee;
            --card: #fffdf9;
            --ink: #1f2937;
            --muted: #6b7280;
            --line: #d8d1c3;
            --accent: #6f4e37;
            --shadow: 0 10px 28px rgba(17, 24, 39, 0.08);

            /* Default text color and font */
            color: var(--ink);
            font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        /* Shared style for hero (top banner) and cards */
        .coffee-sites-notebook .hero,
        .coffee-sites-notebook .card {
            background: var(--card); /* white-ish background */
            border: 1px solid rgba(111, 78, 55, 0.14); /* subtle border */
            border-radius: 18px; /* rounded corners */
            box-shadow: var(--shadow); /* soft shadow */
        }

        /* Top banner styling */
        .coffee-sites-notebook .hero {
            padding: 1.35rem 1.5rem; /* space inside */
            margin-bottom: 1rem; /* space below */
            /* Gradient background */
            background: linear-gradient(135deg, rgba(111,78,55,0.08), rgba(217,180,74,0.12) 55%, rgba(90,169,230,0.08));
        }

        /* Small label above title */
        .coffee-sites-notebook .eyebrow {
            display: inline-block;
            margin-bottom: 0.55rem;
            padding: 0.25rem 0.6rem;
            border-radius: 999px; /* pill shape */
            font-size: 0.78rem;
            font-weight: 700;
            letter-spacing: 0.04em;
            text-transform: uppercase; /* ALL CAPS */
            color: #6f4e37;
            background: rgba(111, 78, 55, 0.1);
        }

        /* Remove default spacing above headings and paragraphs */
        .coffee-sites-notebook h1,
        .coffee-sites-notebook h2,
        .coffee-sites-notebook h3,
        .coffee-sites-notebook p {
            margin-top: 0;
        }

        /* Main title styling */
        .coffee-sites-notebook .hero h1 {
            font-size: 1.9rem;
            line-height: 1.15;
            margin-bottom: 0.4rem;
        }

        /* Description text */
        .coffee-sites-notebook .hero p {
            margin-bottom: 0;
            max-width: 72ch; /* limits line width for readability */
            color: var(--muted); /* softer color */
            line-height: 1.55;
        }

        /* Bullet list styling */
        .coffee-sites-notebook .hero ul {
            margin: 0.85rem 0 0 1rem;
            color: var(--ink);
        }

        /* Section title styling */
        .coffee-sites-notebook .section-title {
            font-size: 1.05rem;
            font-weight: 700;
            margin: 0 0 0.8rem 0;
            color: var(--accent);
        }

        /* Grid layout for stats */
        .coffee-sites-notebook .stat-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); /* responsive grid */
            gap: 0.8rem;
            margin: 0.35rem 0 1rem 0;
        }

        /* Individual stat card */
        .coffee-sites-notebook .stat {
            padding: 0.95rem 1rem;
        }

        /* Stat label (small text) */
        .coffee-sites-notebook .stat-label {
            font-size: 0.78rem;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            color: var(--muted);
            margin-bottom: 0.25rem;
        }

        /* Stat main number */
        .coffee-sites-notebook .stat-value {
            font-size: 1.35rem;
            font-weight: 750;
            color: var(--ink);
        }

        /* Extra note under stat */
        .coffee-sites-notebook .stat-note {
            margin-top: 0.15rem;
            color: var(--muted);
            font-size: 0.86rem;
        }

        /* Frame around the SVG figure */
        .coffee-sites-notebook .figure-frame {
            background: #fff;
            border: 1px solid rgba(31, 41, 55, 0.08);
            border-radius: 20px;
            padding: 1rem;
            overflow-x: auto; /* scroll if too wide */
        }

        /* Helper text style */
        .coffee-sites-notebook .helper {
            color: var(--muted);
            font-size: 0.93rem;
            line-height: 1.5;
        }

        /* Code style formatting for file paths */
        .coffee-sites-notebook .download-note code {
            background: rgba(17, 24, 39, 0.05);
            padding: 0.12rem 0.35rem;
            border-radius: 6px;
        }

        /* ===== SVG chart styling ===== */

        .coffee-sites-svg {
            max-width: 100%;
            height: auto;
            display: block;
        }

        /* Horizontal row lines */
        .coffee-sites-svg .row-line {
            stroke: #ece7de;
            stroke-width: 1;
        }

        /* Panel background */
        .coffee-sites-svg .panel-card {
            fill: #fffdfa;
            stroke: #e1d7c9;
            stroke-width: 1;
        }

        /* Panel header background */
        .coffee-sites-svg .panel-cap {
            fill: #f3ece1;
        }

        /* Grid and axis lines */
        .coffee-sites-svg .axis-line,
        .coffee-sites-svg .grid-line {
            vector-effect: non-scaling-stroke;
        }

        .coffee-sites-svg .grid-line {
            stroke: #d9d2c6;
            stroke-width: 0.9;
            stroke-dasharray: 4 4; /* dashed lines */
        }

        .coffee-sites-svg .axis-line {
            stroke: #6b6257;
            stroke-width: 1.2;
        }

        /* Interactive elements (bars + bubbles) */
        .coffee-sites-svg .yield-bar,
        .coffee-sites-svg .csi-bar,
        .coffee-sites-svg .bio-bubble {
            transition: opacity 160ms ease, transform 160ms ease, stroke-width 160ms ease;
            cursor: pointer; /* shows it's interactive */
        }

        /* Hover effect */
        .coffee-sites-svg .yield-bar:hover,
        .coffee-sites-svg .csi-bar:hover,
        .coffee-sites-svg .bio-bubble:hover {
            opacity: 1;
            stroke: #111827;
            stroke-width: 1.2;
        }

        .coffee-sites-svg text {
            user-select: none; /* prevents selecting text */
        }

        /* Tooltip (hover popup) */
        .coffee-tooltip {
            position: fixed;
            z-index: 9999;
            pointer-events: none;
            opacity: 0; /* hidden by default */
            transform: translate(12px, 12px);
            transition: opacity 120ms ease;
            background: rgba(17, 24, 39, 0.96);
            color: white;
            padding: 0.55rem 0.7rem;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.18);
            font-size: 0.84rem;
            line-height: 1.35;
            max-width: 280px;
            white-space: pre-line;
            font-family: Inter, "Segoe UI", Arial, sans-serif;
        }
    </style>

    <!-- Main container -->
    <div class="coffee-sites-notebook">

        <!-- Top banner -->
        <div class="hero">

            <!-- Small label -->
            <div class="eyebrow">Marimo · SVG · HTML/CSS</div>

            <!-- Title -->
            <h1>Coffee sites visualization</h1>

            <!-- Description -->
            <p>
                This marimo notebook shows our visualization for the coffeesites
            </p>

            <!-- Explanation of panels -->
            <ul>
                <li><strong>Panel 1:</strong> yield bars for 2017, 2018, 2019, and mean yield</li>
                <li><strong>Panel 2:</strong> coffee structure index bar per site</li>
                <li><strong>Panel 3:</strong> biodiversity circles with <em>x = standardized richness</em> and <em>size = abundance</em></li>
            </ul>

        </div>
    </div>
    """)
    return


@app.cell
def _(Path, mo):
    # ===== Input/output paths for Hugging Face Spaces =====
    # Primary location requested for local runs in this environment.
    DATA_FILENAME = "merged_species_dataset.xlsx"
    default_candidates = [
        Path("data") / DATA_FILENAME,
        Path.cwd() / DATA_FILENAME,  
        Path(__file__).resolve().parent / DATA_FILENAME,
    ]

    # Automatically use the first existing dataset path. If none exists, keep
    # data/data_species_merged.xlsx as the displayed default so the error
    # message clearly shows the expected file location.
    default_file = next((p for p in default_candidates if p.exists()), default_candidates[0])

    # Write generated figures to a local outputs folder. This works both in
    # /data and in Hugging Face Spaces.
    output_dir = Path("outputs")
    output_dir.mkdir(exist_ok=True)
    default_stem = output_dir / "coffee_sites_visualisation_marimo"

    # Keep the path visible but pre-filled automatically.
    data_path = mo.ui.text(
        value=str(default_file),
        label="Excel dataset path",
        full_width=True,
    )

    export_png = mo.ui.checkbox(
        value=False,
        label="Also export PNG (optional; requires cairosvg)",
    )

    output_stem = mo.ui.text(
        value=str(default_stem),
        label="Output file stem",
        full_width=True,
    )

    mo.vstack(
        [
            mo.md(
                '<div class="coffee-sites-notebook"><div class="card" style="padding: 1rem 1.1rem;">'
                '<div class="section-title">Inputs</div>'
                '<div class="helper">The notebook automatically looks for <code>data_species_merged.xlsx</code> in <code>data</code>, the current working directory, and the app folder. For Hugging Face Spaces, place the Excel file next to this Python file or keep the shown path if you mount data there.</div>'
                '</div></div>'
            ),
            data_path,
            mo.hstack(
                [export_png, output_stem],
                justify="start",
                gap=1.5,
            ),
        ]
    )
    return data_path, export_png, output_stem


@app.cell
def _():
    # ===== DATA setup =====

    YEAR_COLUMNS = ["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]
    MEAN_COLUMN = "Mean_CC_Yield"
    CSI_COLUMN = "Coffee structure index"
    SITE_COLUMN = "Site_ID"

    SPECIES_GROUPS = [ # This is a list of dictionaries for the biodiversity panel
        {
            "name": "Woody",
            "richness_col": "Woody_Spps",
            "abundance_col": "Woody_abundance",
            "sum_col": "woody_amount",
            "x_col": "woody_x",
            "color": "#3B7A57",
        },
        {
            "name": "Herbaceous",
            "richness_col": "Veg_Spps",
            "abundance_col": "Herbaceous_abundance",
            "sum_col": "herbaceous_amount",
            "x_col": "herbaceous_x",
            "color": "#5AA9E6",
        },
        {
            "name": "Bryophyte",
            "richness_col": "Bryo_Spps",
            "abundance_col": "Bryophyte_frequency",
            "sum_col": "bryophyte_amount",
            "x_col": "bryophyte_x",
            "color": "#D9B44A",
        },
    ]

    # ===== COLOR PALETTE FOR THE VISUALIZATION ===== 

    PALETTE = {
        "text": "#1F2937",
        "muted": "#6B7280",
        "axis": "#5D554B",
        "grid": "#D9D2C6",
        "background": "#F7F4EE",
        "card": "#FFFDF9",
        "card_cap": "#F3ECE1",
        "row": "#ECE7DE",
        "year_2017": "#C9D6EA",
        "year_2018": "#93B5E1",
        "year_2019": "#4E79A7",
        "mean": "#1F2937",
        "csi": "#D97B66",
        "accent": "#6F4E37",
    }
    return (
        CSI_COLUMN,
        MEAN_COLUMN,
        PALETTE,
        SITE_COLUMN,
        SPECIES_GROUPS,
        YEAR_COLUMNS,
    )


@app.cell
def _(Path, data_path, mo, pd):
    # ====== DATA loading ======
    xlsx_path = Path(data_path.value)
    if not xlsx_path.exists():
        mo.stop(
            True,
            mo.md(
                f'<div class="coffee-sites-notebook"><div class="card" style="padding:1rem 1.1rem;">'
                f'<div class="section-title">Dataset not found</div>'
                f'<div class="helper">The file <code>{xlsx_path}</code> does not exist. Update the input path above and rerun.</div>'
                f'</div></div>'
            ),
        )

    site_df = pd.read_excel(xlsx_path, sheet_name="site_level_merged")
    long_df = pd.read_excel(xlsx_path, sheet_name="all_data_long")
    return long_df, site_df, xlsx_path


@app.cell
def _(long_df, mo, site_df):
    mo.accordion(
        {
            "Data preview": mo.vstack(
                [
                    mo.md(
                        f'<div class="coffee-sites-notebook helper">'
                        f'<strong>Loaded rows:</strong> {len(site_df)} site-level rows and {len(long_df)} long-table rows.'
                        f'</div>'
                    ),
                    mo.hstack([site_df.head(), long_df.head()], widths=[1, 1]),
                ]
            )
        }
    )
    return


@app.cell
def _(
    CSI_COLUMN,
    MEAN_COLUMN,
    SITE_COLUMN,
    SPECIES_GROUPS,
    YEAR_COLUMNS,
    long_df,
    math,
    pd,
    site_df,
):
    def build_plot_table(site_df: pd.DataFrame, long_df: pd.DataFrame) -> pd.DataFrame:
        df = site_df.copy() 

        # we group the data by site and then sum abundance values per site gving a summary row per side with 
        # the total abundance values
        abundance_table = long_df.groupby(SITE_COLUMN).agg(
            woody_amount=("Woody_abundance", "sum"),
            herbaceous_amount=("Herbaceous_abundance", "sum"),
            bryophyte_amount=("Bryophyte_frequency", "sum"),
        )
        # Merge the summed abundance values into the site-level table
        # left_on=SITE_COLUMN means use the Site_ID column from df
        # right_index=True means use the index of abundance_table (the grouped site IDs)
        # how="left" means keep all rows from df even if some sites have missing abundance data
        df = df.merge(abundance_table, left_on=SITE_COLUMN, right_index=True, how="left")

        # Build a list of all columns that should be treated as numeric
        # This includes yearly yields, mean yield, CSI, richness columns, and the new abundance-sum columns
        numeric_cols = YEAR_COLUMNS + [MEAN_COLUMN, CSI_COLUMN] + [
            g["richness_col"] for g in SPECIES_GROUPS
        ] + [g["sum_col"] for g in SPECIES_GROUPS]

        # Convert all those columns to numeric values
        # errors="coerce" means invalid values are turned into NaN instead of crashing
        for col in numeric_cols:    
            df[col] = pd.to_numeric(df[col], errors="coerce")

        # For each species group, create a standardized richness value between 0 and 1.
        # This is used to place biodiversity bubbles horizontally in the chart.
        # Bubble size is now controlled by abundance instead.
        for group in SPECIES_GROUPS:
            series = df[group["richness_col"]] # Get the richness values for this species group
            min_val = series.min() # Find the minimum and maximum richness across all sites
            max_val = series.max()
            # If values are missing, or all values are the same,
            # place everything at 0.5 (so in the middle of the axis) to avoid division errors
            if pd.isna(min_val) or pd.isna(max_val) or math.isclose(min_val, max_val):
                df[group["x_col"]] = 0.5
            else:
                # Standardize richness to the range 0–1 using min-max normalization
                df[group["x_col"]] = (series - min_val) / (max_val - min_val)
        # Sort sites from highest to lowest mean yield
        # reset_index(drop=True) gives the table a clean new row index
        df = df.sort_values(MEAN_COLUMN, ascending=False).reset_index(drop=True)
        return df

    plot_df = build_plot_table(site_df, long_df)
    return (plot_df,)


@app.cell
def _(MEAN_COLUMN, SITE_COLUMN, SPECIES_GROUPS, mo, plot_df):
    # ===== CALCULATE SUMMARY STATISTICS =====

    n_sites = len(plot_df) # Total number of sites
    yield_min = float(plot_df[MEAN_COLUMN].min()) # Minimum mean yield across all sites
    yield_max = float(plot_df[MEAN_COLUMN].max()) # Maximum mean yield across all sites

    # Find the largest species richness value across ALL species groups
    # For each group, take its richness column, find its max, then take the overall max
    richest = max(float(plot_df[g["richness_col"]].max()) for g in SPECIES_GROUPS)

    # Get the site with the highest mean yield
    # plot_df is already sorted (highest first), so we take the first row
    # If there are no sites, show a dash instead
    top_site = str(plot_df.iloc[0][SITE_COLUMN]) if n_sites else "—"

    # ===== BUILD HTML FOR DISPLAY =====
    # Create an HTML string using f-string formatting
    # This inserts the calculated values directly into the HTML
    stats_html = f"""
    <div class="coffee-sites-notebook">
        <div class="stat-grid">
            <div class="card stat">
                <div class="stat-label">Sites</div>
                <div class="stat-value">{n_sites}</div>
                <div class="stat-note">Sorted by mean coffee yield</div>
            </div>
            <div class="card stat">
                <div class="stat-label">Top site</div>
                <div class="stat-value">{top_site}</div>
                <div class="stat-note">Highest mean yield in the figure</div>
            </div>
            <div class="card stat">
                <div class="stat-label">Mean yield range</div>
                <div class="stat-value">{yield_min:,.0f}–{yield_max:,.0f}</div>
                <div class="stat-note">Across site-level means</div>
            </div>
            <div class="card stat">
                <div class="stat-label">Largest richness</div>
                <div class="stat-value">{richest:,.0f}</div>
                <div class="stat-note">Maximum species richness encoded by bubble size</div>
            </div>
        </div>
    </div>
    """
    mo.Html(stats_html) # Needed to render the HTML in the marimo notebook
    return


@app.cell
def _(math, pd):
    def scale_linear(value: float, domain: tuple[float, float], rng: tuple[float, float]) -> float:
        # Unpack the input range (domain) → the range of your data
        d0, d1 = domain

        # Unpack the output range → the range on the screen (so the pixel positions)
        r0, r1 = rng

        # If the value is missing (NaN), return NaN
        # This prevents errors later when plotting
        if pd.isna(value):
            return float("nan")

        # If the input range has no variation (min == max),
        # avoid division by zero by placing the value in the middle of the output range
        if math.isclose(d0, d1):
            return (r0 + r1) / 2

        # Perform linear scaling (min-max normalization + stretching to new range)
        return r0 + (value - d0) * (r1 - r0) / (d1 - d0)

    return (scale_linear,)


@app.cell
def _(
    CSI_COLUMN,
    MEAN_COLUMN,
    PALETTE,
    SITE_COLUMN,
    SPECIES_GROUPS,
    YEAR_COLUMNS,
    np,
    pd,
    scale_linear,
    svgwrite,
):
    class CoffeeSiteFigure:
        # this class is used for building the full SVG figure
        def __init__(self, df: pd.DataFrame):
            self.df = df
            self.font = 'Inter, "Segoe UI", Arial, sans-serif' # Fonts used in the SVG text
            self.tooltip_font = 'Inter, "Segoe UI", Arial, sans-serif'


            self.margin = {"top": 110, "right": 44, "bottom": 118, "left": 104} # Margins around the full 
                                                                               # figure (top, right, bottom, 
                                                                               # left)

            self.row_h = 18 # Vertical size of each site row
            self.site_gap = 10 # Vertical gap between rows
            self.panel_gap = 28 # Horizontal gap between the 3 panels
            self.site_label_gap = 12 # Space between site labels and the first panel
            self.year_bar_h = 3.4 # Heights of the year bars  
            self.mean_bar_h = 4.2 # Mean bar in panel 1

            self.panel1_w = 340 # Width of panel 1
            self.panel2_w = 190 # Width of panel 2
            self.panel3_w = 390 # Width of panel 3

            # Total figure width:
            # left margin + panel 1 + gap + panel 2 + gap + panel 3 + right margin
            self.width = (
                self.margin["left"]
                + self.panel1_w
                + self.panel_gap
                + self.panel2_w
                + self.panel_gap
                + self.panel3_w
                + self.margin["right"]
            )

            # x-position where each panel begins
            self.x1 = self.margin["left"]
            self.x2 = self.x1 + self.panel1_w + self.panel_gap
            self.x3 = self.x2 + self.panel2_w + self.panel_gap

            # y-position for the panel header area
            self.y0 = self.margin["top"]

            # Top axis labels should sit below each panel title/subtitle,
            # not above the panel header. The data rows start lower so the
            # top axis does not overlap the first site row.
            self.top_axis_label_y = self.y0 + 22
            self.top_axis_line_y = self.y0 + 29
            self.data_y0 = self.y0 + 38

            # Height occupied by all site rows
            self.rows_h = len(df) * (self.row_h + self.site_gap) - self.site_gap

            # Bottom of the plotting area
            self.plot_bottom = self.data_y0 + self.rows_h

            # Total figure height:
            # plot bottom + bottom margin
            self.height = self.plot_bottom + self.margin["bottom"]

            # Data ranges used for scaling values onto the chart
            self.yield_min = 0
            self.yield_max = float(np.nanmax(df[YEAR_COLUMNS + [MEAN_COLUMN]].to_numpy()))

            # Fixed CSI scale used in panel 2
            self.csi_min = 1
            self.csi_max = 3

            # Minimum and maximum bubble radius for biodiversity points
            self.size_min = 4
            self.size_max = 12

            # Collect the abundance-total columns for all species groups
            abundance_cols = [g["sum_col"] for g in SPECIES_GROUPS]

            # Find the overall minimum and maximum abundance values across all groups.
            # These values now control biodiversity bubble size.
            self.abundance_min = float(df[abundance_cols].min().min())
            self.abundance_max = float(df[abundance_cols].max().max())

        # Return the vertical center position for a site row
        def site_y(self, idx: int) -> float:
            return self.data_y0 + idx * (self.row_h + self.site_gap) + self.row_h / 2

        # Convert a yield value into an x-position inside panel 1
        def yield_x(self, value: float) -> float:
            return scale_linear(value, (self.yield_min, self.yield_max), (self.x1, self.x1 + self.panel1_w))

        # Convert a CSI value into an x-position inside panel 2
        def csi_x(self, value: float) -> float:
            return scale_linear(value, (self.csi_min, self.csi_max), (self.x2, self.x2 + self.panel2_w))

        # Convert a standardized biodiversity value (0 to 1) into an x-position inside panel 3
        def bio_x(self, value: float) -> float:
            return scale_linear(value, (0, 1), (self.x3, self.x3 + self.panel3_w))

        # Convert an abundance value into a bubble radius
        def bubble_r(self, value: float) -> float:
            return scale_linear(value, (self.abundance_min, self.abundance_max), (self.size_min, self.size_max))

        # Attach a tooltip/title to an SVG element --> shows up later on hover
        def _add_title(self, element, text: str):
            element.set_desc(title=text)
            return element

        # Main drawing method: creates the SVG and calls all sub-drawing methods
        def draw(self, output_svg):
            # Create an SVG drawing object with the full figure size
            dwg = svgwrite.Drawing(str(output_svg), size=(self.width, self.height))

            # Set the viewbox so the SVG scales properly
            dwg.viewbox(0, 0, self.width, self.height)

            # Add a CSS class so the SVG can be styled from the notebook CSS
            dwg.attribs["class"] = "coffee-sites-svg"

            # Embed the SVG styling directly in the exported SVG.
            # This is important because downloaded SVG/PNG files cannot rely on
            # the notebook page CSS. Without these embedded styles, some SVG
            # viewers render class-based fills as black.
            dwg.defs.add(
                dwg.style(
                    """
                    .coffee-sites-svg .row-line {
                        stroke: #ECE7DE;
                        stroke-width: 1;
                    }
                    .coffee-sites-svg .panel-card {
                        fill: #FFFDFA;
                        stroke: #E1D7C9;
                        stroke-width: 1;
                    }
                    .coffee-sites-svg .panel-cap {
                        fill: #F3ECE1;
                    }
                    .coffee-sites-svg .grid-line {
                        stroke: #D9D2C6;
                        stroke-width: 0.9;
                        stroke-dasharray: 4 4;
                        vector-effect: non-scaling-stroke;
                    }
                    .coffee-sites-svg .axis-line {
                        stroke: #5D554B;
                        stroke-width: 1.2;
                        vector-effect: non-scaling-stroke;
                    }
                    .coffee-sites-svg .yield-bar,
                    .coffee-sites-svg .csi-bar,
                    .coffee-sites-svg .bio-bubble {
                        cursor: pointer;
                    }
                    """
                )
            )

            # Draw a full solid background rectangle so exported SVG/PNG files
            # never fall back to a transparent or black background.
            dwg.add(
                dwg.rect(
                    insert=(0, 0),
                    size=(self.width, self.height),
                    fill=PALETTE["background"],
                    stroke="none",
                )
            )

            # Draw the different parts of the figure in order
            self._draw_shell(dwg)
            self._draw_title(dwg)
            self._draw_panel_headers(dwg)
            self._draw_reference_grid(dwg)
            self._draw_vertical_axes(dwg)
            self._draw_sites(dwg)
            self._draw_legends(dwg)
            self._draw_footer(dwg)

            dwg.save()

        # Draw background cards & panels behind the 3 chart sections
        def _draw_shell(self, dwg):
            # Keep one shared geometry for all three panels so their backgrounds,
            # header bands, and plot areas line up exactly.
            panel_top = self.y0 - 36
            panel_bottom = self.plot_bottom + 18
            panel_h = panel_bottom - panel_top

            # Header band height is tall enough to contain title, subtitle,
            # top-axis labels, and the top-axis line.
            # It uses only top-rounded corners; the bottom edge is straight,
            # which avoids uneven curved overlaps between the panel header boxes.
            header_h = (self.top_axis_line_y + 8) - panel_top
            corner_r = 16

            panels = [
                (self.x1 - 14, self.panel1_w + 28),
                (self.x2 - 14, self.panel2_w + 28),
                (self.x3 - 14, self.panel3_w + 28),
            ]

            for x, w in panels:
                # Main rounded panel body
                dwg.add(
                    dwg.rect(
                        insert=(x, panel_top),
                        size=(w, panel_h),
                        rx=corner_r,
                        ry=corner_r,
                        class_="panel-card",
                    )
                )

                # Top header band with rounded top corners only and a straight bottom.
                cap_path = dwg.path(
                    d=(
                        f"M {x},{panel_top + header_h} "
                        f"L {x},{panel_top + corner_r} "
                        f"Q {x},{panel_top} {x + corner_r},{panel_top} "
                        f"L {x + w - corner_r},{panel_top} "
                        f"Q {x + w},{panel_top} {x + w},{panel_top + corner_r} "
                        f"L {x + w},{panel_top + header_h} Z"
                    ),
                    class_="panel-cap",
                )
                dwg.add(cap_path)

        # Draw the big figure title at the top
        def _draw_title(self, dwg):
            dwg.add(
                dwg.text(
                    "Coffee sites: yield, structure, and biodiversity",
                    insert=(self.margin["left"], 38),
                    font_size=24,
                    font_family=self.font,
                    font_weight=700,
                    fill=PALETTE["text"],
                )
            )

        # Draw section headers above the 3 panels
        def _draw_panel_headers(self, dwg):
            headers = [
                (self.x1, self.panel1_w, "Yield per site", "2017, 2018, 2019, and mean"),
                (self.x2, self.panel2_w, "Coffee structure index", "Single bar per site"),
                (self.x3, self.panel3_w, "Biodiversity", "x = standardized richness · size = abundance"),
            ]
            for x, w, title, subtitle in headers:
                # Header title
                dwg.add(
                    dwg.text(
                        title,
                        insert=(x, self.y0 - 16),
                        font_size=13,
                        font_family=self.font,
                        font_weight=700,
                        fill=PALETTE["text"],
                    )
                )
                # Header subtitle
                dwg.add(
                    dwg.text(
                        subtitle,
                        insert=(x, self.y0 - 2),
                        font_size=10.5,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )
                # Thin separator line under header
                dwg.add(
                    dwg.line(
                        start=(x, self.y0 + 8),
                        end=(x + w, self.y0 + 8),
                        stroke=PALETTE["grid"],
                        stroke_width=1,
                    )
                )

        # Draw the vertical baseline axis for each panel
        def _draw_vertical_axes(self, dwg):
            y1 = self.top_axis_line_y

            # Extend the vertical axes slightly below the plotting rows.
            # This moves the arrowheads out of the data area so they do not
            # overlap the last site row.
            axis_extension = 16
            y2 = self.plot_bottom + axis_extension

            for x in [self.x1, self.x2, self.x3]:
                dwg.add(dwg.line(start=(x, y1), end=(x, y2), class_="axis-line"))
                dwg.add(
                    dwg.polygon(
                        points=[(x - 4, y2 - 8), (x + 4, y2 - 8), (x, y2)],
                        fill=PALETTE["axis"],
                    )
                )

        # Draw vertical reference/grid lines and tick labels in each panel
        def _draw_reference_grid(self, dwg):
            # Top axis baselines, placed below the panel title/subtitle
            for x, w in [
                (self.x1, self.panel1_w),
                (self.x2, self.panel2_w),
                (self.x3, self.panel3_w),
            ]:
                dwg.add(
                    dwg.line(
                        start=(x, self.top_axis_line_y),
                        end=(x + w, self.top_axis_line_y),
                        class_="axis-line",
                    )
                )

            # Panel 1: yield ticks
            for tick in np.linspace(self.yield_min, self.yield_max, 5):
                x = self.yield_x(float(tick))
                dwg.add(dwg.line(start=(x, self.top_axis_line_y), end=(x, self.plot_bottom), class_="grid-line"))
                # Bottom axis label
                dwg.add(
                    dwg.text(
                        f"{tick:,.0f}",
                        insert=(x, self.plot_bottom + 30),
                        text_anchor="middle",
                        font_size=10,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )

                # Top axis label
                dwg.add(
                    dwg.text(
                        f"{tick:,.0f}",
                        insert=(x, self.top_axis_label_y),
                        text_anchor="middle",
                        font_size=10,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )

            # Panel 2: CSI ticks
            for tick in [1, 2, 3]:
                x = self.csi_x(tick)
                dwg.add(dwg.line(start=(x, self.top_axis_line_y), end=(x, self.plot_bottom), class_="grid-line"))
                # Bottom axis label
                dwg.add(
                    dwg.text(
                        str(tick),
                        insert=(x, self.plot_bottom + 30),
                        text_anchor="middle",
                        font_size=10,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )

                # Top axis label
                dwg.add(
                    dwg.text(
                        str(tick),
                        insert=(x, self.top_axis_label_y),
                        text_anchor="middle",
                        font_size=10,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )

            # Panel 3: biodiversity axis labels
            for tick, label in zip([0, 0.5, 1.0], ["low", "mid", "high"]):
                x = self.bio_x(tick)
                dwg.add(dwg.line(start=(x, self.top_axis_line_y), end=(x, self.plot_bottom), class_="grid-line"))
                # Bottom axis label
                dwg.add(
                    dwg.text(
                        label,
                        insert=(x, self.plot_bottom + 30),
                        text_anchor="middle",
                        font_size=10,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )

                # Top axis label
                dwg.add(
                    dwg.text(
                        label,
                        insert=(x, self.top_axis_label_y),
                        text_anchor="middle",
                        font_size=10,
                        font_family=self.font,
                        fill=PALETTE["muted"],
                    )
                )

        # Draw all site rows: labels, yield bars, CSI bars, and biodiversity bubbles
        def _draw_sites(self, dwg):
            # Colors for the 3 yearly yield bars
            year_colors = [PALETTE["year_2017"], PALETTE["year_2018"], PALETTE["year_2019"]]
            bar_offsets = [-5.5, -1.7, 2.1, 6.2] # Small vertical offsets so the four bars do not overlap

            # Loop through each site row in the dataframe
            for i, row in self.df.iterrows():
                # Vertical position for this site
                y = self.site_y(i)
                # Horizontal row separator line
                dwg.add(
                    dwg.line(
                        start=(self.x1 - 10, y),
                        end=(self.x3 + self.panel3_w + 8, y),
                        class_="row-line",
                    )
                )

                # Site label shown to the left of the first panel
                dwg.add(
                    dwg.text(
                        str(row[SITE_COLUMN]),
                        insert=(self.x1 - self.site_label_gap, y + 3.6),
                        text_anchor="end",
                        font_size=10.5,
                        font_family=self.font,
                        font_weight=600,
                        fill=PALETTE["text"],
                    )
                )

                # Gather yearly yield values plus mean yield
                values = [row[c] for c in YEAR_COLUMNS] + [row[MEAN_COLUMN]]

                # Colors, heights, and text labels for those 4 bars
                colors = year_colors + [PALETTE["mean"]]
                heights = [self.year_bar_h, self.year_bar_h, self.year_bar_h, self.mean_bar_h]
                labels = ["2017", "2018", "2019", "Mean"]

                 # Draw each yield bar
                for v, color, h, off, label in zip(values, colors, heights, bar_offsets, labels):
                    if pd.isna(v):
                        continue
                    x_end = self.yield_x(float(v))

                    # Draw horizontal bar from left axis to scaled x-position
                    rect = dwg.rect(
                        insert=(self.x1, y + off - h / 2),
                        size=(max(0, x_end - self.x1), h),
                        fill=color,
                        rx=1.6,
                        ry=1.6,
                        class_="yield-bar",
                        opacity=0.94,
                    )

                    # Add tooltip text
                    self._add_title(rect, f"Site {row[SITE_COLUMN]} · {label} yield: {float(v):,.2f}")
                    dwg.add(rect)

                # Draw the CSI bar
                csi = row[CSI_COLUMN]
                if not pd.isna(csi):
                    x_end = self.csi_x(float(csi))
                    rect = dwg.rect(
                        insert=(self.x2, y - 3.9),
                        size=(max(0, x_end - self.x2), 7.8),
                        fill=PALETTE["csi"],
                        rx=2,
                        ry=2,
                        class_="csi-bar",
                        opacity=0.92,
                    )
                    self._add_title(rect, f"Site {row[SITE_COLUMN]} · Coffee structure index: {float(csi):.2f}")
                    dwg.add(rect)

                # Draw biodiversity bubbles for the 3 species groups
                # All biodiversity circles for a site are aligned on the same horizontal row.
                for group in SPECIES_GROUPS:
                    richness = row[group["richness_col"]]
                    abundance = row[group["sum_col"]]
                    x_std = row[group["x_col"]]

                    # Skip missing values
                    if pd.isna(richness) or pd.isna(abundance) or pd.isna(x_std):
                        continue

                    # Draw one circle for this group
                    bubble = dwg.circle(
                        center=(self.bio_x(float(x_std)), y),
                        r=self.bubble_r(float(abundance)),
                        fill=group["color"],
                        fill_opacity=0.78,
                        stroke="white",
                        stroke_width=1,
                        class_="bio-bubble",
                    )

                    # Add tooltip text with more detail
                    self._add_title(
                        bubble,
                        (
                            f"Site {row[SITE_COLUMN]} · {group['name']}\n"
                            f"Standardized richness: {float(x_std):.2f}\n"
                            f"Richness: {float(richness):.0f}\n"
                            f"Abundance: {float(abundance):,.0f}"
                        ),
                    )
                    dwg.add(bubble)

        # Draw the legends at the bottom of the figure
        def _draw_legends(self, dwg):
            # Give the legend a little more vertical space so labels do not overlap.
            # Row 1: year legend + biodiversity group legend.
            # Row 2: bubble-size key for the biodiversity panel.
            legend_y = self.height - 72
            bubble_key_y = self.height - 46

            # Legend for yearly yield colors + mean
            for idx, (color, label) in enumerate([
                (PALETTE["year_2017"], "2017"),
                (PALETTE["year_2018"], "2018"),
                (PALETTE["year_2019"], "2019"),
                (PALETTE["mean"], "Mean"),
            ]):
                x = self.x1 + idx * 62
                dwg.add(dwg.rect(insert=(x, legend_y - 10), size=(18, 8), fill=color, rx=2, ry=2))
                dwg.add(
                    dwg.text(
                        label,
                        insert=(x + 24, legend_y - 3),
                        font_size=10.5,
                        font_family=self.font,
                        fill=PALETTE["text"],
                    )
                )

            # Legend for the biodiversity groups
            # Use slightly tighter spacing and keep this on its own row.
            for idx, group in enumerate(SPECIES_GROUPS):
                x = self.x3 + idx * 100
                dwg.add(
                    dwg.circle(
                        center=(x + 7, legend_y - 5),
                        r=5.5,
                        fill=group["color"],
                        fill_opacity=0.78,
                    )
                )
                dwg.add(
                    dwg.text(
                        group["name"],
                        insert=(x + 18, legend_y - 1.5),
                        font_size=10.5,
                        font_family=self.font,
                        fill=PALETTE["text"],
                    )
                )

            # Bubble size key on a separate row to prevent overlap with the group labels.
            key_x = self.x3
            dwg.add(dwg.circle(center=(key_x + 7, bubble_key_y - 5), r=4.5, fill="none", stroke=PALETTE["muted"], stroke_width=1))
            dwg.add(dwg.circle(center=(key_x + 36, bubble_key_y - 5), r=9.5, fill="none", stroke=PALETTE["muted"], stroke_width=1))
            dwg.add(
                dwg.text(
                    "Bubble size = abundance",
                    insert=(key_x + 54, bubble_key_y - 1.5),
                    font_size=10.5,
                    font_family=self.font,
                    fill=PALETTE["muted"],
                )
            )

        # Draw small footer text at the bottom
        def _draw_footer(self, dwg):
            dwg.add(
                dwg.text(
                    "Hover over bars and bubbles for exact values.",
                    insert=(self.margin["left"], self.height - 18),
                    font_size=10,
                    font_family=self.font,
                    fill=PALETTE["muted"],
                )
            )

    return (CoffeeSiteFigure,)


@app.cell
def _(
    CoffeeSiteFigure,
    PALETTE,
    Path,
    export_png,
    mo,
    output_stem,
    plot_df,
    xlsx_path,
):
    # output paths
    output_svg = Path(f"{output_stem.value}.svg")
    output_png = Path(f"{output_stem.value}.png")

    # drawing the figure
    figure = CoffeeSiteFigure(plot_df)
    figure.draw(output_svg)

    png_message = "PNG export skipped."
    if export_png.value:
        try:
            import cairosvg  # type: ignore

            cairosvg.svg2png(
                url=str(output_svg),
                write_to=str(output_png),
                dpi=220,
                background_color=PALETTE["background"],
            )
            png_message = f"PNG written to `{output_png}`"
        except Exception as exc:  # pragma: no cover
            png_message = f"PNG export skipped: {exc}"

    # Build the final HTML preview shown inside the notebook
    preview_html = f"""
    <div class="coffee-sites-notebook">
        <div class="card" style="padding: 1rem 1.1rem;">
            <div class="section-title">Final figure</div>
            <p class="helper download-note">
                Excel input: <code>{xlsx_path}</code><br>
                SVG written to <code>{output_svg}</code><br>
                {png_message}
            </p>
            <div class="figure-frame">
                {output_svg.read_text(encoding='utf-8')}
            </div>
            <div id="coffee-tooltip" class="coffee-tooltip"></div>
            <script>
                (function () {{
                    const root = document.currentScript.closest('.coffee-sites-notebook');
                    if (!root) return;
                    const tooltip = root.querySelector('#coffee-tooltip');
                    if (!tooltip) return;

                    const selectors = '.yield-bar, .csi-bar, .bio-bubble';
                    const marks = root.querySelectorAll(selectors);

                    const showTooltip = (event) => {{
                        const titleNode = event.currentTarget.querySelector('title');
                        const text = titleNode ? titleNode.textContent : '';
                        if (!text) return;
                        tooltip.textContent = text;
                        tooltip.style.opacity = '1';
                        tooltip.style.left = `${{event.clientX}}px`;
                        tooltip.style.top = `${{event.clientY}}px`;
                    }};

                    const moveTooltip = (event) => {{
                        tooltip.style.left = `${{event.clientX}}px`;
                        tooltip.style.top = `${{event.clientY}}px`;
                    }};

                    const hideTooltip = () => {{
                        tooltip.style.opacity = '0';
                    }};

                    marks.forEach((mark) => {{
                        mark.addEventListener('mouseenter', showTooltip);
                        mark.addEventListener('mousemove', moveTooltip);
                        mark.addEventListener('mouseleave', hideTooltip);
                    }});
                }})();
            </script>
        </div>
    </div>
    """
    mo.Html(preview_html)
    return


if __name__ == "__main__":
    app.run()