# Chapter 9 - Step 2: several inputs, a reactive expression shared by two outputs
library(shiny)
library(bslib)
library(dplyr)
library(ggplot2)
library(gapminder)

continents <- levels(gapminder$continent)

ui <- page_sidebar(
  title = "Gapminder explorer",
  sidebar = sidebar(
    sliderInput(
      inputId = "year", label = "Year",
      min = 1952, max = 2007, value = 2007, step = 5, sep = ""
    ),
    checkboxGroupInput(
      inputId = "continents", label = "Continents",
      choices = continents, selected = continents
    )
  ),
  textOutput(outputId = "summary"),
  plotOutput(outputId = "scatter")
)

server <- function(input, output, session) {

  # Reactive expression: computed once, reused by every output that calls it
  filtered <- reactive({
    validate(need(length(input$continents) > 0, "Select at least one continent."))
    gapminder |>
      filter(year == input$year, continent %in% input$continents)
  })

  output$summary <- renderText({
    paste0(
      nrow(filtered()), " countries in ", input$year,
      ", median life expectancy: ",
      round(median(filtered()$lifeExp), 1), " years."
    )
  })

  output$scatter <- renderPlot({
    filtered() |>
      ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop)) +
      geom_point(alpha = 0.6) +
      scale_x_log10(labels = scales::label_dollar(accuracy = 1)) +
      scale_colour_discrete(drop = FALSE) +
      scale_size_area(max_size = 15, guide = "none") +
      labs(
        x = "GDP per capita (log scale)", y = "Life expectancy (years)",
        colour = "Continent"
      ) +
      theme_minimal(base_size = 16)
  })
}

shinyApp(ui, server)
