library(shiny)
library(ggplot2)

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

ui <- fluidPage(
  titlePanel("Normal Density and t Statistic"),
  sidebarLayout(
    sidebarPanel(
      numericInput("beta_j_hat", 
                  "Enter observed sample mean (Y_bar):", 
                  value = 2),
      numericInput("SE_hat", 
                   "Enter estimated standard error (SE_hat):", 
                   value = 1),
      numericInput("b", 
                   "Enter null hypothesis population mean value (mu_0):", 
                   value = 0)
    ),
    mainPanel(
      plotOutput("distPlot"),
      textOutput("statistic")
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    # Compute the statistic W
    W <- (input$beta_j_hat - input$b) / input$SE_hat
    
    # Calculate the shaded area (p-value)
    shaded_area <- 2 * pnorm(-abs(W))
    
    # Plot
    ggplot(data.frame(x=x, y=y), aes(x=x, y=y)) +
      geom_line() +
      geom_ribbon(data=data.frame(x=x, y=ifelse(x > abs(W) | x < -abs(W), dnorm(x), 0)), aes(x=x, ymax=y, ymin=0), fill="red", alpha=0.5) +
      labs(title = paste("P-value is:", round(shaded_area, 4)),
           x = "standard deviations",
           y = "Density") +
      theme_minimal()
  })
  
  output$statistic <- renderText({
    W <- (input$beta_j_hat - input$b) / input$SE_hat
    paste("Value of t statistic (Y_bar - mu_0)/SE_hat:", round(W, 4))
  })
}

shinyApp(ui = ui, server = server)
