library(shiny)
library(ggplot2)

# Create data for the normal distribution
x <- seq(-4, 4, by = 0.01)
y <- dnorm(x)

ui <- fluidPage(
  titlePanel("Normal Distribution Coverage Explorer"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("aValue",
                  "Select value for 'a':",
                  min = 1,
                  max = 3,
                  value = 1.96,
                  step = 0.01)
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    a <- input$aValue
    
    # Calculate the shaded area
    shaded_area <- pnorm(a) - pnorm(-a)
    
    ggplot(data.frame(x=x, y=y), aes(x=x, y=y)) +
      geom_line() +
      geom_ribbon(data=data.frame(x=x, y=ifelse(x > -a & x < a, dnorm(x), 0)), aes(x=x, ymax=y, ymin=0), fill="blue", alpha=0.5) +
      labs(title = paste("Coverage for [-a,a] is:", round(shaded_area*100, 2), "%"),
           x = "standard deviations",
           y = "Density") +
      theme_minimal()
  })
}

shinyApp(ui = ui, server = server)
