library(shiny)
library(tidyverse)

################################################################################
# Precompute simulation data
################################################################################

n_universes <- 10000
n_values <- c(10, 100, 1000)
mu_values <- seq(0.1, 0.9, by = 0.1)

cat("Precomputing confidence interval data...\n")

# Create a data structure to hold all precomputed results
precomputed_data <- list()

for (n in n_values) {
  for (mu in mu_values) {
    cat(sprintf("  n = %d, μ = %.1f\n", n, mu))

    # Simulate binary observations: each Y_i is 0 or 1
    # Sum of n Bernoulli(mu) random variables is Binomial(n, mu)
    results <- replicate(n_universes, rbinom(1, n, mu))

    # Calculate sample means (sample proportions)
    y_bar <- results / n

    # Calculate standard error for each universe
    # For binary data: sample SD = sqrt(y_bar * (1 - y_bar) * n/(n-1))
    # So SE = sample_SD / sqrt(n) = sqrt(y_bar * (1 - y_bar) / (n-1))
    se <- sqrt(y_bar * (1 - y_bar) / (n - 1))

    # Calculate 95% confidence intervals
    z <- qnorm(0.975)
    lower_bounds <- y_bar - z * se
    upper_bounds <- y_bar + z * se

    # Store the results
    data <- data.frame(
      universe = 1:n_universes,
      lower = lower_bounds,
      upper = upper_bounds,
      y_bar = y_bar
    )

    # Order universes by lower bound of the interval
    data <- data[order(data$lower), ]
    data$universe <- 1:n_universes

    # Calculate fraction outside interval
    fraction_outside <- mean(mu < lower_bounds | mu > upper_bounds)

    # Store in nested list structure
    key <- paste0("n", n, "_mu", sprintf("%.1f", mu))
    precomputed_data[[key]] <- list(
      data = data,
      fraction_outside = fraction_outside
    )
  }
}

cat("Precomputation complete!\n\n")

################################################################################
# Shiny App UI
################################################################################

ui <- fluidPage(
  titlePanel("Confidence Intervals for Binary Outcomes"),

  # Add explanatory text at the top
  wellPanel(
    h4("Connection to Lecture 9:"),
    p(HTML("This dashboard illustrates the <b>same confidence interval concept</b> from the lecture,
           but applied to <b>binary outcomes</b> (0 or 1) instead of continuous outcomes like flight delays.")),

    p(HTML("<b>Setup:</b> Suppose we have a population of binary observations Y ∈ {0, 1},
           where <b>μ = E[Y] = P(Y = 1)</b> is the population mean.")),

    p(HTML("<b>Estimation:</b> We draw a sample of size <i>n</i> and compute the <b>sample mean</b>:
           <br>&nbsp;&nbsp;&nbsp;&nbsp;<b>Ȳ = (1/n) Σ Y<sub>i</sub></b>
           <br>For binary data, this equals the sample proportion of 1's.")),

    p(HTML("<b>Confidence Interval:</b> A 95% CI for μ is:
           <b>[Ȳ - 1.96·SE, Ȳ + 1.96·SE]</b>, where SE = σ̂/√n and σ̂ is the sample standard deviation.")),

    p(HTML("<b>This visualization:</b> Shows 10,000 'parallel universes', each with a different sample of size <i>n</i>.
           Each universe constructs its own 95% confidence interval.
           The dashed line shows the true population mean μ.
           Approximately 95% of the intervals should contain μ."))
  ),

  sidebarLayout(
    sidebarPanel(
      selectInput("n_obs",
                  "Sample size (n)",
                  choices = c(10, 100, 1000),
                  selected = 100),
      sliderInput("mu",
                  "True population mean μ = P(Y = 1)",
                  min = 0.1,
                  max = 0.9,
                  value = 0.6,
                  step = 0.1),

      hr(),

      p(strong("Interpretation:")),
      p("• Each dot represents one endpoint of a confidence interval from one universe"),
      p("• Blue = lower bound, Red = upper bound"),
      p("• Dashed black line = true population mean μ"),
      p("• Intervals are sorted by their lower bound for visualization")
    ),

    mainPanel(
      plotOutput("ciPlot", height = "500px"),
      verbatimTextOutput("coverageOutput")
    )
  )
)

################################################################################
# Shiny App Server
################################################################################

server <- function(input, output) {

  # Reactive to get precomputed data based on current inputs
  current_data <- reactive({
    n <- as.numeric(input$n_obs)
    mu <- input$mu
    key <- paste0("n", n, "_mu", sprintf("%.1f", mu))
    precomputed_data[[key]]
  })

  output$ciPlot <- renderPlot({
    mu <- input$mu
    n <- as.numeric(input$n_obs)
    data <- current_data()$data

    ggplot(data, aes(x = universe)) +
      geom_point(aes(y = lower), color = "blue", alpha = 0.5, size = 0.5) +
      geom_point(aes(y = upper), color = "red", alpha = 0.5, size = 0.5) +
      geom_hline(yintercept = mu, linetype = "dashed", color = "black", linewidth = 1) +
      labs(title = sprintf("95%% Confidence Intervals Across %d Universes (n = %d, μ = %.1f)",
                           n_universes, n, mu),
           subtitle = "Intervals ordered by lower bound for visualization",
           x = "Universe (ordered)",
           y = "Sample Mean Ȳ (Sample Proportion)") +
      theme_minimal() +
      theme(plot.title = element_text(size = 14, face = "bold"),
            plot.subtitle = element_text(size = 11))
  })

  output$coverageOutput <- renderText({
    mu <- input$mu
    fraction_outside <- current_data()$fraction_outside
    fraction_inside <- 1 - fraction_outside

    paste0(
      "Coverage: ", sprintf("%.1f%%", fraction_inside * 100),
      " of intervals contain the true μ = ", sprintf("%.1f", mu), "\n",
      "(Expected: ~95% for a 95% confidence interval)\n\n",
      "Fraction of universes where μ is OUTSIDE the interval: ",
      sprintf("%.3f", fraction_outside)
    )
  })
}

################################################################################
# Run App
################################################################################

shinyApp(ui = ui, server = server)
