renderLeaflet({
  req(input$dataset)

  df <- read_csv(input$dataset, locale = locale(encoding = "latin1")) %>%
    mutate(seccion = as.character(seccion))

  mapa_df <- secciones_tlh %>%
    left_join(df, by = c("SECCION" = "seccion")) %>%
    st_transform(crs = 4326)

  resultados <- mapa_df %>%
    group_by(SECCION) %>%
    summarise(
      PT = sum(PT, na.rm = TRUE),
      PVEM = sum(PVEM, na.rm = TRUE),
      MC = sum(MC, na.rm = TRUE),
      MORENA_PNAH = sum(MORENA_PNAH, na.rm = TRUE),
      `PAN-PRI-PRD` = sum(`PAN_PRI_PRD`, na.rm = TRUE),
      TOTAL = sum(TOTAL, na.rm = TRUE),
      .groups = "drop"
    ) %>%
    mutate(popup = paste0(
      "<strong>Sección: </strong>", SECCION, "<br/>",
      "<strong>PT: </strong>", PT, "<br/>",
      "<strong>PVEM: </strong>", PVEM, "<br/>",
      "<strong>MC: </strong>", MC, "<br/>",
      "<strong>MORENA_PNAH: </strong>", MORENA_PNAH, "<br/>",
      "<strong>PAN_PRI_PRD: </strong>", `PAN-PRI-PRD`, "<br/>",
      "<strong>TOTAL: </strong>", TOTAL
    ))

  leaflet(resultados) %>%
    addProviderTiles("Esri.WorldImagery") %>%
    addPolygons(
      fillColor = ~colorNumeric("Greens", TOTAL)(TOTAL),
      color = "white",
      weight = 1,
      fillOpacity = 0.6,
      popup = ~popup
    ) %>%
    addLegend(
      pal = colorNumeric("Greens", resultados$TOTAL),
      values = resultados$TOTAL,
      title = "Votos",
      position = "bottomright"
    )
})