#' @title Create a leaflet map with popup information at commune level
#' 
#' @description
#' This function generates an interactive Leaflet map displaying commune-level
#' data, with customizable styling and popups. It uses spatial data from an `sf`
#' object to render polygons representing communes on the map.
#'
#' The function adds a base map layer using the provided `map_bg` information
#' and then overlays polygons representing the communes.  Communes are styled
#' with a light fill color and a transparent background. When a commune is
#' clicked, its corresponding `popup` content is displayed. A background polygon
#' representing the overall limit is also added for context.
#' 
#' @param dataset sf object, data to be plotted.
#' Default to `so_ii_collectivity`. See details
#' @param map_bg named list, containing the background map provider URL and the
#' attribution text, as issued from the function `set_provider()`
#' 
#' @return A Leaflet map object (invisibly). The map is displayed in the viewer
#' or within an R Markdown or quarto document.
#' 
#' @details
#' `dataset` should contain valid html content in `popup` variable added to the 
#' tributary table of the sf object. If this column does not exist, the
#' function issues a warning and generate and empty `popup` column 
#' 
#' @family interactive mapping
#' 
#' @export 
#' 
#' @examples
#' 
#' \dontrun{
#' # example 1
#' dataset = so.ii::so_ii_collectivity
#' dataset[["popup"]] = paste(
#'  dataset[["commune_name"]],
#'  sprintf("(%s hab)", formatC(so_ii_population[,"2019"], big.mark = " ", format = "d"))
#' )
#' map_leaflet_commune(dataset)
#' 
#' # example 2:  issues warning and creates empty popup
#' map_leaflet_commune()
#' }

map_leaflet_commune = function(
    dataset = so.ii::so_ii_collectivity, 
    map_bg = set_provider("ign_ortho")
) {
    if (isFALSE("popup" %in% colnames(dataset))) {
        warning(
            "'popup' column is missing. Using commune names as pooup content"
        )
        dataset[["popup"]] = " "
    }
    leaflet::leaflet() |>
    leaflet::addTiles(
        urlTemplate = map_bg[["provider"]],
        attribution = map_bg[["attribution"]],
        options = leaflet::tileOptions(opacity = 0.2)
    ) |>
    leaflet::addPolygons(
        data = sf::st_geometry(so.ii::so_ii_limit),
        color = "#EEAA86", 
        weight = 2,
        smoothFactor = 0.5,
        opacity = 1.0,
        fillColor = "transparent"
    ) |>
    leaflet::addPolygons(
        data = sf::st_geometry(dataset),
        color = "#EEAA86", 
        weight = 0.5,
        smoothFactor = 0.5,
        opacity = 1.0,
        fillColor = "#fef9e9", 
        fillOpacity = 0.75,
        highlightOptions = leaflet::highlightOptions(
            color = "#1038aa", 
            weight = 2,
            bringToFront = TRUE
        ),
        popup = dataset[["popup"]]
    )
}
