# Shiny Dashboard: Sampling Distribution of Flight Arrival Delay Sample Mean
# This app visualizes how the sampling distribution changes with sample size

library(shiny)
library(ggplot2)

# Load precomputed sampling distributions
sampling_distributions <- readRDS("sampling_distributions.rds")

# Extract available sample sizes
sample_sizes <- unname(sapply(sampling_distributions, function(x) x$n))

# UI
ui <- fluidPage(
  titlePanel("Sampling Distribution of Flight Arrival Delay Sample Mean"),

  sidebarLayout(
    sidebarPanel(
      radioButtons("sample_size",
        "Select Sample Size (n):",
        choices = sample_sizes,
        selected = sample_sizes[1]),

      hr(),

      h4("About this visualization"),
      p("This dashboard shows approximate sampling distributions for the sample mean
        of flight arrival delays (in minutes). Each distribution is based on 1,000,000
        simulations (parallel universes)."),

      p("In each simulation, we randomly sample", em("n"), "flights from the 2024 population
        and compute their mean arrival delay. The distribution shows how much this sample mean
        varies across different random samples."),

      p(strong("Key insight:"), "As the sample size increases, the sampling distribution
        becomes narrower (lower variance) and more concentrated around the true population mean.")
    ),

    mainPanel(
      plotOutput("sampling_dist_plot", height = "500px"),

      hr(),

      h4("Statistics"),
      verbatimTextOutput("statistics")
    )
  )
)

# Server
server <- function(input, output) {

  # Get selected distribution
  selected_dist <- reactive({
    key <- paste0("n_", input$sample_size)
    sampling_distributions[[key]]
  })

  # Plot sampling distribution
  output$sampling_dist_plot <- renderPlot({
    dist <- selected_dist()

    ggplot(data.frame(sample_mean = dist$sample_means), aes(x = sample_mean)) +
      geom_density(fill = "steelblue", alpha = 0.6, linewidth = 1) +
      labs(
        title = sprintf("Sampling Distribution of Sample Mean (n = %d)", dist$n),
        subtitle = "Based on 1,000,000 simulations",
        x = "Sample Mean Arrival Delay (minutes)",
        y = "Density"
      ) +
      xlim(-30, 90) +
      ylim(0, 0.2) +
      theme_minimal(base_size = 16) +
      theme(
        plot.title = element_text(size = 20, face = "bold"),
        plot.subtitle = element_text(size = 14, color = "gray30"),
        axis.title = element_text(size = 14),
        axis.text = element_text(size = 12)
      )
  })

  # Display statistics
  output$statistics <- renderText({
    dist <- selected_dist()

    sprintf(
      "Sample size (n): %d
Population mean (true μ): %.2f minutes
Expected value of sample mean (E[Ȳ]): %.3f minutes
Bias: %.4f minutes
Number of simulations: 1,000,000",
      dist$n,
      dist$mu,
      dist$sampling_mean,
      dist$sampling_bias
    )
  })
}

# Run the app
shinyApp(ui = ui, server = server)
