# Build maps step by step

# Step 1: base R plot of a data frame with coordinates
waterfalls <- data.frame(
  name = c("Iguazu Falls", "Niagara Falls", "Victoria Falls"),
  lat = c(-25.686785, 43.092461, -17.931805),
  lon = c(-54.444981, -79.047150, 25.825558)
)

plot(
  waterfalls$lon,
  waterfalls$lat,
  xlab = "Longitude",
  ylab = "Latitude",
  asp = 1
)

# Step 2: spatial visualization with sf
library(sf)
waterfalls_sf <- st_as_sf(
  waterfalls,
  coords = c("lon", "lat"),
  crs = "EPSG:4326"
)
plot(st_geometry(waterfalls_sf))

# Step 3: basic tmap visualization
library(tmap)
tm_shape(waterfalls_sf) +
  tm_symbols()

# Step 4: add context (world map)
library(spData)
data("world", package = "spData")

# Optional: compare base plots to tmap
plot(world)
plot(st_geometry(world))

tm_world <- tm_shape(world) +
  tm_polygons()
tm_world

tm_world +
  tm_shape(waterfalls_sf) +
  tm_symbols()

tm_world +
  tm_shape(waterfalls_sf) +
  tm_symbols(fill = "name")

# Step 5: improve projection

tm_world +
  tm_crs("auto")

tm_world +
  tm_shape(waterfalls_sf) +
  tm_symbols(fill = "name") +
  tm_crs("auto")

# Step 6: style points and legend

tm1 <- tm_world +
  tm_shape(waterfalls_sf) +
  tm_symbols(
    fill = "name",
    fill.scale = tm_scale(values = c("steelblue", "darkorchid", "forestgreen")),
    fill.legend = tm_legend(
      title = "",
      position = c("left", "bottom"),
      bg.color = "grey95"
    )
  ) +
  tm_crs("auto")

tm1

# Step 7: improve layout
tm2 <- tm1 +
  tm_graticules() +
  tm_layout(
    earth_boundary = TRUE,
    frame = FALSE,
    bg.color = "lightblue",
    space.color = "white"
  )

tm2

# Optional: save output (writes a file)
tmap_save(tm2, "waterfalls.png", width = 2400, height = 1200)
