# Chapter 7 - A gallery of {bslib} layouts (one tab per layout)
library(shiny)
library(bslib)
library(bsicons)
library(dplyr)
library(ggplot2)
library(gapminder)

# A coloured placeholder showing its own width (in twelfths of the page)
box <- function(label, colour = "#e6f0ff") {
  card(
    card_body(
      class = "d-flex align-items-center justify-content-center",
      style = paste0("background:", colour, "; min-height: 120px;"),
      tags$span(style = "font-size: 1.4rem; font-family: monospace;", label)
    )
  )
}

ui <- page_navbar(
  title = "bslib layouts",
  sidebar = sidebar(
    width = 220,
    selectInput("continent", "Continent", choices = levels(gapminder$continent), selected = "Europe")
  ),

  # 1. layout_columns(): a grid of 12 columns
  nav_panel(
    "Columns", fillable = FALSE,   # rows keep their natural height
    layout_columns(col_widths = c(4, 8), box("4"), box("8")),
    layout_columns(col_widths = c(3, 3, 6), box("3", "#ffe5cc"), box("3", "#ffe5cc"), box("6", "#ffe5cc")),
    layout_columns(col_widths = 12, box("12", "#e5f5e5"))
  ),

  # 2. layout_column_wrap(): equal-width elements (here 3 per row)
  nav_panel(
    "KPI row",
    layout_column_wrap(
      width = 1 / 3, fill = FALSE,
      value_box("Countries", textOutput("n"), showcase = bs_icon("globe2"), theme = "primary"),
      value_box("Median life expectancy", textOutput("life"), showcase = bs_icon("heart-pulse"), theme = "success"),
      value_box("Median GDP per capita", textOutput("gdp"), showcase = bs_icon("cash-coin"), theme = "info")
    ),
    card(card_header("A graph below the KPIs"), plotOutput("trend"))
  ),

  # 3. navset_card_underline(): several outputs in tabs, in the same space
  nav_panel(
    "Tabs in a card",
    navset_card_underline(
      title = "Life expectancy",
      full_screen = TRUE,
      nav_panel("Over time", plotOutput("trend2")),
      nav_panel("Distribution", plotOutput("hist")),
      nav_panel("Table", tableOutput("table"))
    )
  ),

  # 4. layout_sidebar() inside a card: a local sidebar, for this card only
  nav_panel(
    "Card with sidebar",
    card(
      card_header("GDP per capita vs. life expectancy"),
      layout_sidebar(
        sidebar = sidebar(
          position = "right", width = 220,
          radioButtons("scale", "x axis", c("Log" = "log", "Linear" = "lin")),
          checkboxInput("labels", "Show country names", FALSE)
        ),
        plotOutput("scatter")
      )
    )
  )
)

server <- function(input, output, session) {
  cont <- reactive(filter(gapminder, continent == input$continent))
  last <- reactive(filter(cont(), year == 2007))

  output$n    <- renderText(n_distinct(cont()$country))
  output$life <- renderText(paste(round(median(last()$lifeExp), 1), "years"))
  output$gdp  <- renderText(scales::dollar(median(last()$gdpPercap), accuracy = 1))

  trend_plot <- function() {
    cont() |>
      group_by(year) |>
      summarise(life = median(lifeExp)) |>
      ggplot(aes(year, life)) +
      geom_line(linewidth = 1, colour = "#1e3a5f") +
      geom_point(colour = "#1e3a5f") +
      labs(x = NULL, y = "Median life expectancy (years)") +
      theme_minimal(base_size = 15)
  }
  output$trend  <- renderPlot(trend_plot())
  output$trend2 <- renderPlot(trend_plot())

  output$hist <- renderPlot(
    ggplot(last(), aes(lifeExp)) +
      geom_histogram(bins = 15, fill = "#1e3a5f", colour = "white") +
      labs(x = "Life expectancy in 2007 (years)", y = "Countries") +
      theme_minimal(base_size = 15)
  )
  output$table <- renderTable(
    last() |> arrange(desc(lifeExp)) |> select(country, lifeExp) |> head(8),
    digits = 1
  )

  output$scatter <- renderPlot({
    p <- ggplot(last(), aes(gdpPercap, lifeExp)) +
      geom_point(colour = "#d95f02", size = 3) +
      labs(x = "GDP per capita (US$)", y = "Life expectancy (years)") +
      theme_minimal(base_size = 15)
    if (input$scale == "log") p <- p + scale_x_log10()
    if (input$labels) p <- p + geom_text(aes(label = country), vjust = -0.8, size = 3.5)
    p
  })
}

shinyApp(ui, server)
