library(rjson)
library(shiny)
library(bslib)
library(leaflet)
library(sf)


crime_json <- fromJSON(file="C:\\Users\\milli\\Documents\\Datenbereinigung\\data.json")
geojson_data <- st_read("C:\\Users\\milli\\Documents\\Datenbereinigung\\geojson.json")
geojson_data <- st_transform(geojson_data, crs = 4326)
bezirke <- names(crime_json)

ui <- page_fillable(
  layout_columns(
    card(
      selectInput(
        inputId = "drp_bezirk",
        label = "Bezirk",
        choices = bezirke),
      selectInput(
        inputId = "drp_stadtteil",
        label = "Stadtteil",
        choices = NULL,
      )
    ),
    leafletOutput("hhmap"),
    card("Card rechts"),
    col_widths = c(3, 6, 3)
  )
)
server <- function(input, output, session){
  
  observeEvent(input$drp_bezirk, {
    sel_bezirk <- input$drp_bezirk
    
    if (sel_bezirk != "") {
      
      # Neue Auswahlmöglichkeiten bestimmen
      sel_stadtteile <- names(crime_json[[sel_bezirk]])
      
      # Zweites SelectInput-Feld aktualisieren
      updateSelectInput(
        session, 
        inputId = "drp_stadtteil", 
        choices = sel_stadtteile,
        selected = sel_stadtteile[1] # Wählt den ersten Eintrag vor
      )
      
    }
  })
  
  output$hhmap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(providers$CartoDB.Positron) %>%
      addPolygons(
        data = geojson_data,
        color = "#7bb5ab",
        fillColor = "#bdf0e7",
        weight = 1,
        fillOpacity = 0.05,      # Polygon fill transparency
        highlightOptions = highlightOptions(
          color = "#103b57",
          weight = 4,
          bringToFront = TRUE
        ),
      ) %>%
      setView(
        lng = 9.98716634776887,
        lat = 53.5488439196432,
        zoom = 11
      )
  })
}
shinyApp(ui = ui, server = server)

