library(shiny)
library(ggplot2)

set.seed(123)

# Define parameters
n_values <- c(10, 50, 100)
q_values <- seq(0.1, 0.9, by = 0.1)
n_simulations <- 100000

# Set the maximum number of trials to be simulated
max_n <- max(n_values)

# Precompute uniform random variables only once
uniform_samples <- matrix(runif(max_n * n_simulations), nrow = n_simulations, ncol = max_n)

# Initialize an empty list to store counts and fractions
counts_list <- list()

for (n in n_values) {
  for (q in q_values) {
    # Select the first `n` values in each row and apply the cutoff for q
    coin_flips <- uniform_samples[, 1:n] < q
    
    # Calculate the mean success rate for each simulation
    sample_means <- rowMeans(coin_flips)
    
    # Count the occurrences of each unique sample average
    tabulated <- table(sample_means)
    
    # Convert counts to fractions
    fractions <- tabulated / n_simulations
    
    # Convert to a data frame for each unique (n, q) pair
    df <- data.frame(sample_average = as.numeric(names(fractions)), fraction = as.numeric(fractions))
    counts_list[[paste(n, q, sep = "_")]] <- df
  }
}

# Define the UI for the application
ui <- fluidPage(
  titlePanel("Sampling Distribution of Sample Average\n from Bernoulli Distribution"),
  sidebarLayout(
    sidebarPanel(
      h4("Parameters"),
      selectInput(inputId = "n",
                  label = "Number of trials (n)",
                  choices = n_values,
                  selected = 100),
      sliderInput(inputId = "q",
                  label = "True Parameter (q)",
                  min = 0.1,
                  max = 0.9,
                  value = 0.5,
                  step = 0.1),
      sliderInput(inputId = "q_hat",
                  label = "Observed Sample Average (q_hat)",
                  min = 0.1,
                  max = 0.9,
                  value = 0.5,
                  step = 0.05),
      hr(),
      h4("About This Visualization"),
      p(strong("What this shows:"), "The sampling distribution of the sample average
        from repeated Bernoulli trials. Each bar represents the probability of
        observing a particular sample average when the true success probability is q."),
      p(strong("Parameters:")),
      tags$ul(
        tags$li(strong("n:"), "Number of independent trials (coin flips)"),
        tags$li(strong("q:"), "The true probability of success on each trial"),
        tags$li(strong("q_hat:"), "The observed sample average from your data")
      ),
      p(strong("The red area:"), "Shows the p-value, which is the probability of
        observing a sample average at least as large as q_hat if the true parameter
        is q. Smaller p-values provide stronger evidence against the assumption that
        the true parameter equals q.")
    ),
    mainPanel(
      plotOutput("samplingDistPlot"),
      hr()
    )
  )
)

# Define Server
server <- function(input, output) {
  output$samplingDistPlot <- renderPlot({
    df <- counts_list[[paste(input$n, input$q, sep = "_")]]
    q_hat <- input$q_hat
    
    # Calculate p-value
    p_value <- sum(df$fraction[df$sample_average >= q_hat])
    
    # Update the color of the bars based on q_hat
    df$bar_color <- ifelse(df$sample_average >= q_hat, "red", "skyblue")
    
    # Plot the histogram
    ggplot(df, aes(x = sample_average, y = fraction, fill = bar_color)) +
      geom_bar(stat = "identity", color = NA) +
      scale_fill_identity() +
      labs(x = "Sample Average", y = "Density",
           title = paste0("Density Histogram for n=", input$n, " and q=", input$q),
           subtitle = paste0("Red Area = ", round(p_value, 4))) +
      scale_x_continuous(breaks = seq(0, 1, by = 0.1), limits = c(-0.05,1.05))
  })
}

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