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5f4e5
c8d7b4c
d028225
 
 
 
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
###############################################################################
# Shiny App: San Francisco Biodiversity Access Decision Support Tool
# Author: Diego Ellis Soto, et al.
# University of California Berkeley, ESPM
# California Academy of Sciences
###############################################################################
require(shinyjs)
library(shiny)
library(shinydashboard)
library(leaflet)
library(mapboxapi)
library(tidyverse)
library(tidycensus)
library(sf)
library(DT)
library(RColorBrewer)
library(terra)       
library(data.table)
library(mapview)   
library(sjPlot)    
library(sjlabelled)
library(bslib)
library(shinycssloaders)

source('R/setup.R') # Load necessary data (annotated gbif, annotated cbg, ndvi)

# Define your Mapbox token securely
mapbox_token <- "pk.eyJ1Ijoia3dhbGtlcnRjdSIsImEiOiJjbHc3NmI0cDMxYzhyMmt0OXBiYnltMjVtIn0.Thtu6WqIhOfin6AykskM2g" 

# Global theme definition using a green-themed bootswatch
theme <- bs_theme(
  bootswatch = "minty", # 'minty' is a light green-themed bootswatch
  base_font = font_google("Roboto"),
  heading_font = font_google("Roboto Slab"),
  bg = "#f0fff0",       # Honeydew background
  fg = "#2e8b57"        # SeaGreen foreground
)

# UI
ui <- dashboardPage(
  skin = "green", # shinydashboard skin color
  dashboardHeader(title = "SF Biodiversity Access Tool"
  ),

  dashboardSidebar(
    sidebarMenu(
      menuItem("Isochrone Explorer", tabName = "isochrone", icon = icon("map-marker-alt")),
      menuItem("GBIF Summaries", tabName = "gbif", icon = icon("table")),
      menuItem("Community Science", tabName = "community_science", icon = icon("users")),
      menuItem("About", tabName = "about", icon = icon("info-circle"))
    )
  ),
  dashboardBody(
    theme = theme, # Apply the custom theme
    useShinyjs(),  
    # Loading message
    div(id = "loading", style = "display:none; font-size: 20px; color: red;", "Calculating..."),
    
    # fluidRow(
    #   column(
    #     width = 2,
    #     imageOutput("Combined_logos")
    #   )
    # ),
    
    # fluidPage(
    #   box(
    #     tags$img(height = 100, width = 100,src = "Combined_logos.png"),
    #     imageOutput('Combined_logos')
    #   )
    # ),
    
    
    # fluidRow(
    #   column(
    #     width = 2,
    #     imageOutput("uc_berkeley_logo")
    #   ),
    #   column(
    #     width = 4,
    #     imageOutput("california_academy_logo")
    #   ),
    #   column(
    #     width = 6,
    #     imageOutput("reimagining_sf_logo")
    #   )
    # ),
    # fluidPage(
    #   # Application title
    #   # titlePanel("Test app"),
    #   # to render images in the www folder 
    #   box(uiOutput("houz"), width = 3)
    # ),
    
    # 
    # fluidRow(
    #   column(
    #     width = 12, align = "center",
    #     tags$img(src = "UC_Berkeley_logo.png",
    #              height = "200px", style = "margin:10px;", alt = "UC Berkeley Logo"),
    #     tags$img(src = "California_academy_logo.png",
    #              height = "200px", style = "margin:10px;", alt = "California Academy Logo"),
    #     tags$img(src = "Reimagining_San_Francisco.png",
    #              height = "200px", style = "margin:10px;", alt = "Reimagining San Francisco Logo")
    #   )
    # ),
    # fluidPage(
    #   box(
    #     tags$img(height = 100, width = 100,src = "Rlogo.png"),
    #     imageOutput('image_logos')
    #   )
    # ),

    # Tab Items
    tabItems(
      # Isochrone Explorer Tab
      tabItem(tabName = "isochrone",
              fluidRow(
                box(
                  title = "Controls", status = "success", solidHeader = TRUE, width = 4,
                  radioButtons(
                    "location_choice", 
                    "Select Location Method:",
                    choices = c("Address (Geocode)" = "address", 
                                "Click on Map"      = "map_click"),
                    selected = "map_click"  
                  ),
                  
                  conditionalPanel(
                    condition = "input.location_choice == 'address'",
                    mapboxGeocoderInput(
                      inputId = "geocoder",
                      placeholder = "Search for an address",
                      access_token = mapbox_token
                    )
                  ),
                  
                  checkboxGroupInput(
                    "transport_modes", 
                    "Select Transportation Modes:",
                    choices = list("Driving"             = "driving",
                                   "Walking"             = "walking",
                                   "Cycling"             = "cycling",
                                   "Driving with Traffic"= "driving-traffic"),
                    selected = c("driving", "walking")
                  ),
                  
                  checkboxGroupInput(
                    "iso_times", 
                    "Select Isochrone Times (minutes):",
                    choices = list("5" = 5, "10" = 10, "15" = 15),
                    selected = c(5, 10)
                  ),
                  
                  actionButton("generate_iso", "Generate Isochrones", icon = icon("play")),
                  actionButton("clear_map", "Clear", icon = icon("times"))
                ),
                box(
                  title = "Map", status = "success", solidHeader = TRUE, width = 8,
                  leafletOutput("isoMap", height = 600)
                )
              ),
              fluidRow(
                box(
                  title = "Biodiversity Access Score", status = "success", solidHeader = TRUE, width = 6,
                  uiOutput("bioScoreBox")
                ),
                box(
                  title = "Closest Greenspace", status = "success", solidHeader = TRUE, width = 6,
                  uiOutput("closestGreenspaceUI")
                )
              ),
              fluidRow(
                box(
                  title = "Summary Data", status = "success", solidHeader = TRUE, width = 12,
                  DTOutput("dataTable") %>% withSpinner(type = 8, color = "#28a745")
                )
              ),
              fluidRow(
                box(
                  title = "Biodiversity & Socioeconomic Summary", status = "success", solidHeader = TRUE, width = 12,
                  plotOutput("bioSocPlot", height = "400px") %>% withSpinner(type = 8, color = "#28a745")
                )
              ),
              fluidRow(
                box(
                  title = "GBIF Records by Institution", status = "success", solidHeader = TRUE, width = 12,
                  plotOutput("collectionPlot", height = "400px") %>% withSpinner(type = 8, color = "#28a745")
                )
              )
      ),
      
      # GBIF Summaries Tab
      tabItem(tabName = "gbif",
              fluidRow(
                box(
                  title = "Filters", status = "success", solidHeader = TRUE, width = 4,
                  selectInput(
                    "class_filter",
                    "Select a GBIF Class to Summarize:",
                    choices = c("All", sort(unique(sf_gbif$class))), 
                    selected = "All"
                  ),
                  selectInput(
                    "family_filter",
                    "Filter by Family (optional):",
                    choices = c("All", sort(unique(sf_gbif$family))),
                    selected = "All"
                  )
                ),
                box(
                  title = "Data Summary", status = "success", solidHeader = TRUE, width = 8,
                  DTOutput("classTable")
                )
              ),
              fluidRow(
                box(
                  title = "Observations vs. Species Richness", status = "success", solidHeader = TRUE, width = 12,
                  plotOutput("obsVsSpeciesPlot", height = "300px") %>% withSpinner(type = 8, color = "#28a745"),
                  p("This plot displays the relationship between the number of observations and the species richness. Use this visualization to understand data coverage and biodiversity trends.")
                )
              )
      ),
      # Community Science Tab
      tabItem(tabName = "community_science",
              fluidRow(
                box(
                  title = "Partner Community Organizations", status = "success", solidHeader = TRUE, width = 12,
                  leafletOutput("communityMap", height = 600)
                )
              ),
              fluidRow(
                box(
                  title = "Community Organizations Data", status = "success", solidHeader = TRUE, width = 12,
                  DTOutput("communityTable") %>% withSpinner(type = 8, color = "#28a745")
                )
              )
      ),
      
      # About Tab
      tabItem(tabName = "about",
              fluidRow(
                box(
                  title = "App Summary", status = "success", solidHeader = TRUE, width = 12,
                  tags$b("App Summary (Fill out with RSF data working group):"),
                  p("
                    This application allows users to either click on a map or geocode an address 
                    to generate travel-time isochrones across multiple transportation modes 
                    (e.g., pedestrian, cycling, driving, driving during traffic).
                    It retrieves socio-economic data from precomputed Census variables, calculates NDVI, 
                    and summarizes biodiversity records from GBIF. Users can explore information 
                    related to biodiversity in urban environments, including greenspace coverage, 
                    population estimates, and species diversity within each isochrone.
                  "),
                  
                  tags$b("Created by:"),
                  p(strong("Diego Ellis Soto", "Carl Boettiger, Rebecca Johnson, Christopher J. Schell")),
                  
                  p("Contact Information: ", strong("[email protected]"))
                )
              ),
              fluidRow(
                box(
                  title = "Reimagining San Francisco", status = "success", solidHeader = TRUE, width = 12,
                  tags$b("Reimagining San Francisco (Fill out with CAS):"),
                  p("Reimagining San Francisco is an initiative aimed at integrating ecological, social, 
                     and technological dimensions to shape a sustainable future for the Bay Area. 
                     This collaboration unites diverse stakeholders to explore innovations in urban planning, 
                     conservation, and community engagement. The Reimagining San Francisco Data Working Group has been tasked with identifying and integrating multiple sources of socio-ecological biodiversity information in a co-development framework.")
                )
              ),
              fluidRow(
                box(
                  title = "Why Biodiversity Access Matters", status = "success", solidHeader = TRUE, width = 12,
                  p("Ensuring equitable access to biodiversity is essential for human well-being, 
                     ecological resilience, and global policy decisions related to conservation. 
                     Areas with higher biodiversity can support ecosystem services including pollinators, moderate climate extremes, 
                     and provide cultural, recreational, and health benefits to local communities. 
                     Recognizing that cities are particularly complex socio-ecological systems facing both legacies of sociocultural practices as well as current ongoing dynamic human activities and pressures.
                     Incorporating multiple facets of biodiversity metrics alongside variables employed by city planners, human geographers, and decision-makers into urban planning will allow a more integrative lens in creating a sustainable future for cities and their residents.")
                )
              ),
              fluidRow(
                box(
                  title = "How We Calculate Biodiversity Access Percentile", status = "success", solidHeader = TRUE, width = 12,
                  p("Total unique species found within the user-generated isochrone. 
                     We then compare that value to the distribution of unique species counts across all census block groups, 
                     converting that comparison into a percentile ranking (Polish this, look at the 15 Minute city). 
                     A higher percentile indicates greater biodiversity within the chosen area, 
                     relative to other parts of the city or region.")
                )
              ),
              fluidRow(
                box(
                  title = "Next Steps", status = "success", solidHeader = TRUE, width = 12,
                  tags$ul(
                    tags$li("Add impervious surface"),
                    tags$li("National walkability score"),
                    tags$li("Social vulnerability score"),
                    tags$li("NatureServe biodiversity maps"),
                    tags$li("Calculate cold-hotspots within aggregation of H6 bins instead of by census block group: Ask Carl"),
                    tags$li("Species range maps"),
                    tags$li("Add common name GBIF"),
                    tags$li("Partner orgs"),
                    tags$li("Optimize speed -> store variables -> H-ify the world?"),
                    tags$li("Brainstorm and co-develop the biodiversity access score"),
                    tags$li("For the GBIF summaries, add an annotated GBIF_sf with environmental variables so we can see landcover type association across the biodiversity within the isochrone.")
                  )
                )
              )
      )
    )
  )
)

# ------------------------------------------------
# Server
# ------------------------------------------------
server <- function(input, output, session) {
  
  chosen_point <- reactiveVal(NULL)
  
  # ------------------------------------------------
  # Render logos 
  # ------------------------------------------------
  

  output$combine_logo <- renderImage({
    list(
      src = file.path("www", "Combined_logos.png"),
      width = "50%",
      height = "45%",
      alt = "Combined_logos"
    )
  }, deleteFile = FALSE)
  
    # output$uc_berkeley_logo <- renderImage({
  #   list(
  #     src = file.path("www", "UC_Berkeley_logo.png"),
  #     width = "50%",
  #     height = "45%",
  #     alt = "UC Berkeley Logo"
  #   )
  # }, deleteFile = FALSE)
  # 
  # output$california_academy_logo <- renderImage({
  #   list(
  #     src = file.path("www", "California_academy_logo.png"),
  #     width = "50%",
  #     height = "45%",
  #     alt = "California Academy Logo"
  #   )
  # }, deleteFile = FALSE)
  # 
  # output$reimagining_sf_logo <- renderImage({
  #   list(
  #     src = file.path("www", "Reimagining_San_Francisco.png"),
  #     width = "50%",
  #     height = "45%",
  #     alt = "Reimagining San Francisco Logo"
  #   )
  # }, deleteFile = FALSE)


  # ------------------------------------------------
  # Leaflet Base + Hide Overlays
  # ------------------------------------------------
  output$isoMap <- renderLeaflet({
    pal_cbg <- colorNumeric("YlOrRd", cbg_vect_sf$medincE)
    
    pal_rich <- colorNumeric("YlOrRd", domain = cbg_vect_sf$unique_species)
    # Color palette for data availability
    pal_data <- colorNumeric("Blues", domain = cbg_vect_sf$n_observations)
    
    leaflet() %>%
      addTiles(group = "Street Map (Default)") %>%
      addProviderTiles(providers$Esri.WorldImagery, group = "Satellite (ESRI)") %>%
      addProviderTiles(providers$CartoDB.Positron, group = "CartoDB.Positron") %>%
      
      addPolygons(
        data = cbg_vect_sf,
        group = "Income",
        fillColor = ~pal_cbg(medincE),
        fillOpacity = 0.6,
        color = "white",
        weight = 1,
        label=~GEOID,
        highlightOptions = highlightOptions(
          weight = 5,
          color = "blue",
          fillOpacity = 0.5,
          bringToFront = TRUE
        ),
        labelOptions = labelOptions(
          style = list("font-weight" = "bold", "color" = "blue"),
          textsize = "12px",
          direction = "auto"
        )
      ) %>%
      
      addPolygons(
        data = osm_greenspace,
        group = "Greenspace",
        fillColor = "darkgreen",
        fillOpacity = 0.3,
        color = "green",
        weight = 1,
        label = ~name,
        highlightOptions = highlightOptions(
          weight = 5,
          color = "blue",
          fillOpacity = 0.5,
          bringToFront = TRUE
        ),
        labelOptions = labelOptions(
          style = list("font-weight" = "bold", "color" = "blue"),
          textsize = "12px",
          direction = "auto",
          noHide = FALSE # Labels appear on hover
        )
      ) %>%
      
      addPolygons(
        data = biodiv_hotspots,
        group = "Hotspots (KnowBR)",
        fillColor = "firebrick",
        fillOpacity = 0.2,
        color = "firebrick",
        weight = 2,
        label = ~GEOID,
        highlightOptions = highlightOptions(
          weight = 5,
          color = "blue",
          fillOpacity = 0.5,
          bringToFront = TRUE
        ),
        labelOptions = labelOptions(
          style = list("font-weight" = "bold", "color" = "blue"),
          textsize = "12px",
          direction = "auto"
        )
      ) %>%
      
      addPolygons(
        data = biodiv_coldspots,
        group = "Coldspots (KnowBR)",
        fillColor = "navyblue",
        fillOpacity = 0.2,
        color = "navyblue",
        weight = 2,
        label = ~GEOID,
        highlightOptions = highlightOptions(
          weight = 5,
          color = "blue",
          fillOpacity = 0.5,
          bringToFront = TRUE
        ),
        labelOptions = labelOptions(
          style = list("font-weight" = "bold", "color" = "blue"),
          textsize = "12px",
          direction = "auto"
        )
      ) %>%
      
      # Add Species Richness Layer
      addPolygons(
        data = cbg_vect_sf,
        group = "Species Richness",
        fillColor = ~pal_rich(unique_species),
        fillOpacity = 0.6,
        color = "white",
        weight = 1,
        label = ~unique_species,
        popup = ~paste0(
          "<strong>GEOID: </strong>", GEOID,
          "<br><strong>Species Richness: </strong>", unique_species,
          "<br><strong>Observations: </strong>", n_observations,
          "<br><strong>Median Income: </strong>", median_inc,
          "<br><strong>Mean NDVI: </strong>", ndvi_mean
        )
      ) %>%
      
      # Add Data Availability Layer
      addPolygons(
        data = cbg_vect_sf,
        group = "Data Availability",
        fillColor = ~pal_data(n_observations),
        fillOpacity = 0.6,
        color = "white",
        weight = 1,
        label = ~n_observations,
        popup = ~paste0(
          "<strong>GEOID: </strong>", GEOID,
          "<br><strong>Observations: </strong>", n_observations,
          "<br><strong>Species Richness: </strong>", unique_species,
          "<br><strong>Median Income: </strong>", median_inc,
          "<br><strong>Mean NDVI: </strong>", ndvi_mean
        )
      ) %>%
      
      setView(lng = -122.4194, lat = 37.7749, zoom = 12) %>%
      addLayersControl(
        baseGroups    = c("Street Map (Default)", "Satellite (ESRI)", "CartoDB.Positron"),
        overlayGroups = c("Income", "Greenspace", 
                          "Hotspots (KnowBR)", "Coldspots (KnowBR)",
                          "Species Richness", "Data Availability",
                          "Isochrones", "NDVI Raster"),
        options       = layersControlOptions(collapsed = FALSE)
      ) %>%
      hideGroup("Income") %>%
      hideGroup("Greenspace") %>%
      hideGroup("Hotspots (KnowBR)") %>%
      hideGroup("Coldspots (KnowBR)") %>%
      hideGroup("Species Richness") %>%
      hideGroup("Data Availability")
  })
  
  
  # ------------------------------------------------
  # Observe map clicks (location_choice = 'map_click')
  # ------------------------------------------------
  observeEvent(input$isoMap_click, {
    req(input$location_choice == "map_click")
    click <- input$isoMap_click
    if (!is.null(click)) {
      chosen_point(c(lon = click$lng, lat = click$lat))
      
      # Provide feedback with coordinates
      showNotification(
        paste0("Map clicked at Longitude: ", round(click$lng, 5), 
               ", Latitude: ", round(click$lat, 5)),
        type = "message"
      )
      
      # Update the map with a marker
      leafletProxy("isoMap") %>%
        clearMarkers() %>%
        addCircleMarkers(
          lng = click$lng, lat = click$lat,
          radius = 6, color = "firebrick",
          label = "Map Click Location"
        )
    }
  })
  
  # ------------------------------------------------
  # Observe geocoder input
  # ------------------------------------------------
  observeEvent(input$geocoder, {
    req(input$location_choice == "address")
    geocode_result <- input$geocoder
    if (!is.null(geocode_result)) {
      # Extract coordinates
      xy <- geocoder_as_xy(geocode_result)
      
      # Update the chosen_point reactive value
      chosen_point(c(lon = xy[1], lat = xy[2]))
      
      # Provide feedback with the geocoded address and coordinates
      showNotification(
        paste0("Address geocoded to Longitude: ", round(xy[1], 5), 
               ", Latitude: ", round(xy[2], 5)),
        type = "message"
      )
      
      # Update the map with a marker
      leafletProxy("isoMap") %>%
        clearMarkers() %>%
        addCircleMarkers(
          lng = xy[1], lat = xy[2],
          radius = 6, color = "navyblue",
          label = "Geocoded Address"
        ) %>%
        flyTo(lng = xy[1], lat = xy[2], zoom = 13)
    }
  })
  
  # ------------------------------------------------
  # Observe clearing of map
  # ------------------------------------------------
  observeEvent(input$clear_map, {
    # Reset the chosen point
    chosen_point(NULL)
    
    # Clear all markers and isochrones from the map, but keep other layers
    leafletProxy("isoMap") %>%
      clearMarkers() %>%
      clearGroup("Isochrones") %>%
      clearGroup("NDVI Raster")
    
    # Provide feedback to the user
    showNotification("Map cleared. You can select a new location.", type = "message")
  })
  
  # ------------------------------------------------
  # Generate Isochrones
  # ------------------------------------------------
  isochrones_data <- eventReactive(input$generate_iso, {
    
    leafletProxy("isoMap") %>%
      clearGroup("Isochrones") %>%
      clearGroup("NDVI Raster")
    
    # Validate inputs
    pt <- chosen_point()
    if (is.null(pt)) {
      showNotification("No location selected! Provide an address or click the map.", type = "error")
      return(NULL)
    }
    if (length(input$transport_modes) == 0) {
      showNotification("Select at least one transportation mode.", type = "error")
      return(NULL)
    }
    if (length(input$iso_times) == 0) {
      showNotification("Select at least one isochrone time.", type = "error")
      return(NULL)
    }
    
    location_sf <- st_as_sf(
      data.frame(lon = pt["lon"], lat = pt["lat"]),
      coords = c("lon","lat"), crs = 4326
    )
    
    iso_list <- list()
    for (mode in input$transport_modes) {
      for (t in input$iso_times) {
        iso <- tryCatch({
          mb_isochrone(location_sf, time = as.numeric(t), profile = mode, 
                       access_token = mapbox_token)
        }, error = function(e) {
          showNotification(paste("Isochrone error:", mode, t, e$message), type = "error")
          NULL
        })
        if (!is.null(iso)) {
          iso$mode <- mode
          iso$time <- t
          iso_list <- append(iso_list, list(iso))
        }
      }
    }
    if (length(iso_list) == 0) {
      showNotification("No isochrones generated.", type = "warning")
      return(NULL)
    }
    
    all_iso <- do.call(rbind, iso_list) %>% st_transform(4326)
    all_iso
  })
  
  # ------------------------------------------------
  # Plot Isochrones + NDVI
  # ------------------------------------------------
  observeEvent(isochrones_data(), {
    iso_data <- isochrones_data()
    req(iso_data)
    
    iso_data$iso_group <- paste(iso_data$mode, iso_data$time, sep = "_")
    pal <- colorRampPalette(brewer.pal(8, "Set2"))
    cols <- pal(nrow(iso_data))
    
    for (i in seq_len(nrow(iso_data))) {
      poly_i <- iso_data[i, ]
      leafletProxy("isoMap") %>%
        addPolygons(
          data = poly_i,
          group = "Isochrones",
          color = cols[i],
          weight = 2,
          fillOpacity = 0.4,
          label = paste0(poly_i$mode, " - ", poly_i$time, " mins")
        )
    }
    
    iso_union <- st_union(iso_data)
    iso_union_vect <- vect(iso_union)
    ndvi_crop <- terra::crop(ndvi, iso_union_vect)
    ndvi_mask <- terra::mask(ndvi_crop, iso_union_vect)
    ndvi_vals <- values(ndvi_mask)
    ndvi_vals <- ndvi_vals[!is.na(ndvi_vals)]
    
    if (length(ndvi_vals) > 0) {
      ndvi_pal <- colorNumeric("YlGn", domain = range(ndvi_vals, na.rm = TRUE), na.color = "transparent")
      
      leafletProxy("isoMap") %>%
        addRasterImage(
          x = ndvi_mask,
          colors = ndvi_pal,
          opacity = 0.7,
          project = TRUE,
          group = "NDVI Raster"
        ) %>%
        addLegend(
          position = "bottomright",
          pal = ndvi_pal,
          values = ndvi_vals,
          title = "NDVI"
        )
    }
    
    # Ensure other layers remain
    leafletProxy("isoMap") %>%
      addLayersControl(
        baseGroups = c("Street Map (Default)", "Satellite (ESRI)", "CartoDB.Positron"),
        overlayGroups = c("Income", "Greenspace", 
                          "Hotspots (KnowBR)", "Coldspots (KnowBR)",
                          "Species Richness", "Data Availability",
                          "Isochrones", "NDVI Raster"),
        options = layersControlOptions(collapsed = FALSE)
      )
  })
  
  # ------------------------------------------------
  # socio_data Reactive + Summaries
  # ------------------------------------------------
  socio_data <- reactive({
    iso_data <- isochrones_data()
    if (is.null(iso_data) || nrow(iso_data) == 0) {
      return(data.frame())
    }
    
    acs_wide <- cbg_vect_sf %>%
      mutate(
        population = popE,
        med_income = medincE
      )
    
    hotspot_union  <- st_union(biodiv_hotspots)
    coldspot_union <- st_union(biodiv_coldspots)
    
    results <- data.frame()
    
    # Calculate distance to coldspot and hotspots
    for (i in seq_len(nrow(iso_data))) {
      poly_i <- iso_data[i, ]
      
      dist_hot  <- st_distance(poly_i, hotspot_union)
      dist_cold <- st_distance(poly_i, coldspot_union)
      dist_hot_km  <- round(as.numeric(min(dist_hot))  / 1000, 3)
      dist_cold_km <- round(as.numeric(min(dist_cold)) / 1000, 3)
      
      inter_acs <- st_intersection(acs_wide, poly_i)
      
      vect_acs_wide <- vect(acs_wide)
      vect_poly_i <- vect(poly_i)
      inter_acs <- intersect(vect_acs_wide, vect_poly_i)
      inter_acs = st_as_sf(inter_acs)
      
      pop_total <- 0
      inc_str   <- "N/A"
      if (nrow(inter_acs) > 0) {
        inter_acs$area <- st_area(inter_acs)
        inter_acs$area_num <- as.numeric(inter_acs$area)
        inter_acs$area_ratio <- inter_acs$area_num / as.numeric(st_area(inter_acs))
        inter_acs$weighted_pop <- inter_acs$population * inter_acs$area_ratio
        
        pop_total <- round(sum(inter_acs$weighted_pop, na.rm = TRUE))
        
        w_income <- sum(inter_acs$med_income * inter_acs$area_num, na.rm = TRUE) /
          sum(inter_acs$area_num, na.rm = TRUE)
        if (!is.na(w_income) && w_income > 0) {
          inc_str <- paste0("$", formatC(round(w_income, 2), format = "f", big.mark = ","))
        }
      }
      
      # Intersection with greenspace
      vec_osm_greenspace <- vect(osm_greenspace)
      inter_gs <- intersect(vec_osm_greenspace, vect_poly_i)
      inter_gs = st_as_sf(inter_gs)
      
      gs_area_m2 <- 0
      if (nrow(inter_gs) > 0) {
        gs_area_m2 <- sum(st_area(inter_gs))
      }
      iso_area_m2 <- as.numeric(st_area(poly_i))
      gs_area_m2 <- as.numeric(gs_area_m2)
      gs_percent <- ifelse(iso_area_m2 > 0, 100 * gs_area_m2 / iso_area_m2, 0)
      
      # NDVI Calculation
      poly_vect <- vect(poly_i)
      ndvi_crop <- terra::crop(ndvi, poly_vect)
      ndvi_mask <- terra::mask(ndvi_crop, poly_vect)
      ndvi_vals <- values(ndvi_mask)
      ndvi_vals <- ndvi_vals[!is.na(ndvi_vals)]
      mean_ndvi <- ifelse(length(ndvi_vals) > 0, round(mean(ndvi_vals, na.rm=TRUE), 3), NA)
      
      # Intersection with GBIF data
      inter_gbif <- intersect(vect_gbif, vect_poly_i)
      inter_gbif <- st_as_sf(inter_gbif)
      
      inter_gbif_acs <- sf_gbif %>% 
        mutate(
          income = medincE,
          ndvi = ndvi_sentinel
        )
      
      if (nrow(inter_gbif) > 0) {
        inter_gbif_acs <- inter_gbif_acs[inter_gbif_acs$GEOID %in% inter_gbif$GEOID, ]
      }
      
      n_records   <- nrow(inter_gbif)
      n_species   <- length(unique(inter_gbif$species))
      
      n_birds   <- length(unique(inter_gbif$species[inter_gbif$class == "Aves"]))
      n_mammals <- length(unique(inter_gbif$species[inter_gbif$class == "Mammalia"]))
      n_plants  <- length(unique(inter_gbif$species[inter_gbif$class %in% 
                                                      c("Magnoliopsida","Liliopsida","Pinopsida","Polypodiopsida",
                                                        "Equisetopsida","Bryopsida","Marchantiopsida") ]))
      
      iso_area_km2 <- round(iso_area_m2 / 1e6, 3)
      
      row_i <- data.frame(
        Mode                = tools::toTitleCase(poly_i$mode),
        Time                = poly_i$time,
        IsochroneArea_km2   = iso_area_km2,
        DistToHotspot_km    = dist_hot_km,
        DistToColdspot_km   = dist_cold_km,
        EstimatedPopulation = pop_total,
        MedianIncome        = inc_str,
        MeanNDVI            = ifelse(!is.na(mean_ndvi), mean_ndvi, "N/A"),
        GBIF_Records        = n_records,
        GBIF_Species        = n_species,
        Bird_Species        = n_birds,
        Mammal_Species      = n_mammals,
        Plant_Species       = n_plants,
        Greenspace_m2       = round(gs_area_m2, 2),
        Greenspace_percent  = round(gs_percent, 2),
        stringsAsFactors    = FALSE
      )
      results <- rbind(results, row_i)
    }
    
    iso_union <- st_union(iso_data)
    vect_iso <- vect(iso_union)
    inter_all_gbif <- intersect(vect_gbif, vect_iso)
    inter_all_gbif <- st_as_sf(inter_all_gbif)
    
    union_n_species <- length(unique(inter_all_gbif$species))
    rank_percentile <- round(100 * ecdf(cbg_vect_sf$unique_species)(union_n_species), 1)
    attr(results, "bio_percentile") <- rank_percentile
    
    # Closest Greenspace from ANY part of the isochrone
    dist_mat <- st_distance(iso_union, osm_greenspace)  # 1 x N matrix
    if (length(dist_mat) > 0) {
      min_dist <- min(dist_mat)
      min_idx  <- which.min(dist_mat)
      gs_name  <- osm_greenspace$name[min_idx]
      attr(results, "closest_greenspace") <- gs_name
    } else {
      attr(results, "closest_greenspace") <- "None"
    }
    
    results
  })
  
  # ------------------------------------------------
  # Render main summary table
  # ------------------------------------------------
  output$dataTable <- renderDT({
    df <- socio_data()
    if (nrow(df) == 0) {
      return(DT::datatable(data.frame("Message" = "No isochrones generated yet.")))
    }
    DT::datatable(
      df,
      colnames = c(
        "Mode"                 = "Mode",
        "Time (min)"           = "Time",
        "Area (km²)"           = "IsochroneArea_km2",
        "Dist. Hotspot (km)"   = "DistToHotspot_km",
        "Dist. Coldspot (km)"  = "DistToColdspot_km",
        "Population"           = "EstimatedPopulation",
        "Median Income"        = "MedianIncome",
        "Mean NDVI"            = "MeanNDVI",
        "GBIF Records"         = "GBIF_Records",
        "Unique Species"       = "GBIF_Species",
        "Bird Species"         = "Bird_Species",
        "Mammal Species"       = "Mammal_Species",
        "Plant Species"        = "Plant_Species",
        # "Greenspace (m²)"      = "Greenspace_m2",
        "Greenspace (%)"       = "Greenspace_percent"
      ),
      options = list(pageLength = 10, autoWidth = TRUE),
      rownames = FALSE
    )
  })
  
  # ------------------------------------------------
  # Biodiversity Access Score + Closest Greenspace
  # ------------------------------------------------
  output$bioScoreBox <- renderUI({
    df <- socio_data()
    if (nrow(df) == 0) return(NULL)
    
    percentile <- attr(df, "bio_percentile")
    if (is.null(percentile)) percentile <- "N/A"
    else percentile <- paste0(percentile, "th Percentile")
    
    wellPanel(
      HTML(paste0("<h2>Biodiversity Access Score: ", percentile, "</h2>"))
    )
  })
  
  output$closestGreenspaceUI <- renderUI({
    df <- socio_data()
    if (nrow(df) == 0) return(NULL)
    gs_name <- attr(df, "closest_greenspace")
    if (is.null(gs_name)) gs_name <- "None"
    
    tagList(
      strong("Closest Greenspace (from any part of the Isochrone):"),
      p(gs_name)
    )
  })
  
  # ------------------------------------------------
  # Secondary table: user-selected CLASS & FAMILY
  # ------------------------------------------------
  output$classTable <- renderDT({
    iso_data <- isochrones_data()
    if (is.null(iso_data) || nrow(iso_data) == 0) {
      return(DT::datatable(data.frame("Message" = "No isochrones generated yet.")))
    }
    
    iso_union <- st_union(iso_data)
    vect_iso <- vect(iso_union)
    inter_gbif <- intersect(vect_gbif, vect_iso)
    inter_gbif = st_as_sf(inter_gbif)
    
    inter_gbif_acs = sf_gbif %>% 
      mutate(
        income = medincE,
        ndvi = ndvi_sentinel
      )
    
    if (input$class_filter != "All") {
      inter_gbif_acs <- inter_gbif_acs[ inter_gbif_acs$class == input$class_filter, ]
    }
    if (input$family_filter != "All") {
      inter_gbif_acs <- inter_gbif_acs[ inter_gbif_acs$family == input$family_filter, ]
    }
    
    if (nrow(inter_gbif_acs) == 0) {
      return(DT::datatable(data.frame("Message" = "No records for that combination in the isochrone.")))
    }
    
    species_counts <- inter_gbif_acs %>%
      st_drop_geometry() %>%
      group_by(species) %>%
      summarize(
        n_records   = n(),
        mean_income = round(mean(income, na.rm=TRUE), 2),
        mean_ndvi   = round(mean(ndvi, na.rm=TRUE), 3),
        .groups = "drop"
      ) %>%
      arrange(desc(n_records))
    
    DT::datatable(
      species_counts,
      colnames = c("Species", "Number of Records", "Mean Income", "Mean NDVI"),
      options = list(pageLength = 10),
      rownames = FALSE
    )
  })
  
  # ------------------------------------------------
  # Ggplot: Biodiversity & Socioeconomic Summary
  # ------------------------------------------------
  output$bioSocPlot <- renderPlot({
    df <- socio_data()
    if (nrow(df) == 0) return(NULL)
    
    df_plot <- df %>%
      mutate(IsoLabel = paste0(Mode, "-", Time, "min"))
    
    ggplot(df_plot, aes(x = IsoLabel)) +
      geom_col(aes(y = GBIF_Species), fill = "steelblue", alpha = 0.7) +
      geom_line(aes(y = EstimatedPopulation / 1000, group = 1), color = "red", size = 1) +
      geom_point(aes(y = EstimatedPopulation / 1000), color = "red", size = 3) +
      labs(
        x = "Isochrone (Mode-Time)",
        y = "Unique Species (Blue) | Population (Red) (Thousands)",
        title = "Biodiversity & Socioeconomic Summary"
      ) +
      theme_minimal(base_size = 14) +
      theme(
        axis.text.x  = element_text(angle = 45, hjust = 1, size = 12),
        axis.text.y  = element_text(size = 12),
        axis.title.x = element_text(size = 14),
        axis.title.y = element_text(size = 14),
        plot.title   = element_text(hjust = 0.5, size = 16, face = "bold")
      )
  })
  
  # ------------------------------------------------
  # Bar plot: GBIF records by institutionCode
  # ------------------------------------------------
  output$collectionPlot <- renderPlot({
    iso_data <- isochrones_data()
    if (is.null(iso_data) || nrow(iso_data) == 0) {
      plot.new()
      title("No GBIF records found in this isochrone.")
      return(NULL)
    }
    
    iso_union <- st_union(iso_data)
    vect_iso <- vect(iso_union)
    inter_gbif <- intersect(vect_gbif, vect_iso)
    inter_gbif = st_as_sf(inter_gbif)
    
    if (nrow(inter_gbif) == 0) {
      plot.new()
      title("No GBIF records found in this isochrone.")
      return(NULL)
    }
    
    df_code <- inter_gbif %>%
      st_drop_geometry() %>%
      group_by(institutionCode) %>%
      summarize(count = n(), .groups = "drop") %>%
      arrange(desc(count)) %>%
      mutate(truncatedCode = substr(institutionCode, 1, 5)) # Shorter version of the names 
    
    ggplot(df_code, aes(x = reorder(truncatedCode, -count), y = count)) +
      geom_bar(stat = "identity", fill = "darkorange", alpha = 0.7) +
      labs(
        x = "Institution Code (Truncated)",
        y = "Number of Records",
        title = "GBIF Records by Institution Code (Isochrone Union)"
      ) +
      theme_minimal(base_size = 14) +
      theme(
        axis.text.x  = element_text(angle = 45, hjust = 1, size = 12),
        axis.text.y  = element_text(size = 12),
        axis.title.x = element_text(size = 14),
        axis.title.y = element_text(size = 14),
        plot.title   = element_text(hjust = 0.5, size = 16, face = "bold")
      )
  })
  
  # ------------------------------------------------
  # Additional Plot: n_observations vs n_species
  # ------------------------------------------------
  
  # Make it reactive: obsVsSpeciesPlot updates dynamically based on user-selected class_filter or family_filter. 
  
  filtered_data <- reactive({
    data <- cbg_vect_sf
    if (input$class_filter != "All") {
      data <- data[data$class == input$class_filter, ]
    }
    if (input$family_filter != "All") {
      data <- data[data$family == input$family_filter, ]
    }
    data
  })
  
  output$obsVsSpeciesPlot <- renderPlot({
    data <- filtered_data()
    if (nrow(data) == 0) {
      plot.new()
      title("No data available for selected filters.")
      return(NULL)
    }
    
    ggplot(data, aes(x = log(n_observations + 1), y = log(unique_species + 1))) +
      geom_point(color = "blue", alpha = 0.6) +
      labs(
        x = "Log(Number of Observations + 1)",
        y = "Log(Species Richness + 1)",
        title = "Data Availability vs. Species Richness"
      ) +
      theme_minimal(base_size = 14) +
      theme(
        axis.text.x  = element_text(size = 12),
        axis.text.y  = element_text(size = 12),
        axis.title.x = element_text(size = 14),
        axis.title.y = element_text(size = 14),
        plot.title   = element_text(hjust = 0.5, size = 16, face = "bold")
      )
  })
  
  
  
  # ------------------------------------------------
  # [Optional: Linear Model Plot (Commented Out)]
  # ------------------------------------------------
  # Uncomment and adjust if needed
  # output$lmCoefficientsPlot <- renderPlot({
  #   df_lm <- cbg_vect_sf %>% 
  #     filter(!is.na(n_observations), 
  #            !is.na(unique_species),
  #            !is.na(median_inc),
  #            !is.na(ndvi_mean))
  #   
  #   if (nrow(df_lm) < 5) {
  #     plot.new()
  #     title("Not enough data for linear model.")
  #     return(NULL)
  #   }
  #   
  #   fit <- lm(unique_species ~ n_observations + median_inc + ndvi_mean, data = df_lm)
  #   
  #   p <- plot_model(fit, show.values = TRUE, value.offset = .3, title = "LM Coefficients: n_species ~ n_observations + median_inc + ndvi_mean")
  #   print(p)
  # })


# 
# # Add Images:
# df_img = data.frame(id = c(1:3), img_path=c('California_academy_logo.png', 'Reimagining_San_Francisco.png', 'UC Berkeley_logo.png'))
# n <- nrow(df_img)
# 
# n <- nrow(df_img)
# 
# observe({
#   for (i in 1:n)
#   {
#     print(i)
#     local({
#       my_i <- i
#       imagename = paste0("img", my_i)
#       print(imagename)
#       output[[imagename]] <-
#         renderImage({
#           list(src = file.path('www', df_img$img_path[my_i]), 
#                width = "100%", height = "55%",
#                alt = "Image failed to render")
#         }, deleteFile = FALSE)
#     })
#   }
# })
# 
# 
# output$houz <- renderUI({
#   
#   image_output_list <- 
#     lapply(1:n,
#            function(i)
#            {
#              imagename = paste0("img", i)
#              imageOutput(imagename)
#            })
#   
#   do.call(tagList, image_output_list)
# })


}



# Run the Shiny app
shinyApp(ui, server)

#