#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 800

# Load necessary libraries
library(shiny)
library(ggplot2)

# Define the meta.power function
meta.power <- function(k, d, tau2, n, alpha = 0.05){
    vt <- 1/n + 1/n
    V <- (tau2 + vt)/k
    z <- d / sqrt(V)
    zc <- abs(qnorm(alpha/2))
    1 - pnorm(zc - z) + pnorm(-zc - z)
}

# Define UI for the application
ui <- fluidPage(
    # Application title
    titlePanel("Meta Power Calculator with Power Curve"),

    # Sidebar layout with input fields
    sidebarLayout(
        sidebarPanel(
            numericInput("k", "Number of studies (k):", value = 5, min = 1),
            checkboxInput("flag_k", "Vary k?", value = FALSE),
            numericInput("d", "Effect size (d):", value = 0.5),
            checkboxInput("flag_d", "Vary d?", value = FALSE),
            numericInput("tau2", "Between-study variance (tau^2):", value = 0.1),
            checkboxInput("flag_tau2", "Vary tau^2?", value = FALSE),
            numericInput("n", "Sample size per group (n):", value = 50),
            checkboxInput("flag_n", "Vary n?", value = FALSE),
            numericInput("alpha", "Significance level (alpha):", value = 0.05, step = 0.01),
            checkboxInput("flag_alpha", "Vary alpha?", value = FALSE),

            hr(),
            numericInput("minRange", "Min value for flagged variable:", value = 1),
            numericInput("maxRange", "Max value for flagged variable:", value = 50),
            actionButton("calc", "Calculate Power Curve")
        ),

        # Main panel to display results
        mainPanel(
            plotOutput("powerPlot"),
            textOutput("curveDescription")
        )
    )
)

# Define server logic
server <- function(input, output) {

    observeEvent(input$calc, {

        # Extract input values
        k <- input$k
        d <- input$d
        tau2 <- input$tau2
        n <- input$n
        alpha <- input$alpha

        # Range for the flagged variable
        min_range <- input$minRange
        max_range <- input$maxRange
        range <- seq(min_range, max_range, length.out = 100)

        # Identify which variable is flagged and vary it across the range
        if(input$flag_k){
            varied_var <- "k"
            power_values <- sapply(range, function(v) meta.power(v, d, tau2, n, alpha))
        } else if(input$flag_d){
            varied_var <- "d"
            power_values <- sapply(range, function(v) meta.power(k, v, tau2, n, alpha))
        } else if(input$flag_tau2){
            varied_var <- "tau2"
            power_values <- sapply(range, function(v) meta.power(k, d, v, n, alpha))
        } else if(input$flag_n){
            varied_var <- "n"
            power_values <- sapply(range, function(v) meta.power(k, d, tau2, v, alpha))
        } else if(input$flag_alpha){
            varied_var <- "alpha"
            power_values <- sapply(range, function(v) meta.power(k, d, tau2, n, v))
        } else {
            varied_var <- "None"
            power_values <- NULL
        }

        # Plot the power curve
        output$powerPlot <- renderPlot({
            if(!is.null(power_values)){
                plot_data <- data.frame(
                    VarValue = range,
                    Power = power_values
                )
                ggplot(plot_data, aes(x = VarValue, y = Power)) +
                    geom_line(color = "blue") +
                    labs(x = varied_var, y = "Power", title = paste("Power Curve by varying", varied_var)) +
                    theme_minimal()
            }
        })

        # Output description of curve
        output$curveDescription <- renderText({
            if(varied_var != "None"){
                paste("Power curve by varying", varied_var, "from", min_range, "to", max_range)
            } else {
                "No variable flagged for variation."
            }
        })
    })
}

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