library(shiny)
library(ggplot2)

# Define the server logic
server <- function(input, output) {
  
  output$powerPlot <- renderPlot({
    SE_hat <- input$SE_hat
    b <- input$null_hypothesis
    alpha <- input$alpha
    a <- input$alternative
    critical_value <- qnorm(1 - alpha / 2)
    
    # t test statistic distribution under H0
    x <- seq(-5, 5, length.out = 1000)
    y0 <- dnorm(x)
    df0 <- data.frame(x, y0)
    
    # t test statistic distribution under H1
    y1 <- dnorm(x, mean = (a - b)/SE_hat, sd = 1)
    df1 <- data.frame(x, y1)
    
    # Calculate the power
    power <- 1 - (pnorm(critical_value, mean = (a - b) / SE_hat, sd = 1) -
                    pnorm(-critical_value, mean = (a - b) / SE_hat, sd = 1))
    
    # Update the text output for power
    output$powerText <- renderText({
      paste("Power at given false positive probability (alpha):", round(power, 4))
    })
    
    # Create the plot
    ggplot() +
      geom_line(data = df0, aes(x = x, y = y0), col = "red") +
      geom_line(data = df1, aes(x = x, y = y1), col = "blue") +
      geom_ribbon(data = df0[df0$x < -critical_value, ], aes(x, ymin = 0, ymax = y0), fill = "red", alpha = 0.5) +
      geom_ribbon(data = df0[df0$x > critical_value, ], aes(x, ymin = 0, ymax = y0), fill = "red", alpha = 0.5) +
      geom_ribbon(data = df1[df1$x < -critical_value, ], aes(x, ymin = 0, ymax = y1), fill = "blue", alpha = 0.25) +
      geom_ribbon(data = df1[df1$x > critical_value, ], aes(x, ymin = 0, ymax = y1), fill = "blue", alpha = 0.25) +
      labs(title = "Statistical Power", x = "Test Statistic", y = "Density") +
      theme_minimal()
  })
}

# Define the UI
ui <- fluidPage(
  titlePanel("t Statistic: False Positive Probability and Power"),
  
  sidebarLayout(
    sidebarPanel(
      sliderInput("SE_hat", "Estimated Standard Error", min = 0.5, max = 10, value = 1, step = 0.5),
      numericInput("null_hypothesis", "Null Hypothesis", value = 0),
      sliderInput("alpha", "False positive probability alpha", min = 0.01, max = 0.1, value = 0.05, step = 0.01),
      sliderInput("alternative", "Specific Alternative Hypothesis", min = -4, max = 4,
                  value = 2, step = 0.5)
    ),
    mainPanel(
      plotOutput("powerPlot"),
      textOutput("powerText")
    )
  )
)

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