# Load required functions from the package
source(system.file("R", "corrCI_sa.R", package = "saCI"), local = TRUE)
source(system.file("R", "boot_corrCI.R", package = "saCI"), local = TRUE)

library(shiny)

# Define UI
ui <- fluidPage(
  titlePanel("Confidence Interval for Correlation - SA vs Bootstrap BCa"),

  sidebarLayout(
    sidebarPanel(
      h4("Data Input"),
      textInput("x_data", "X Data (comma-separated)",
                value = "1.2, 2.5, 3.1, 4.0, 5.2, 6.1, 7.0, 8.3, 9.1, 10.2"),
      textInput("y_data", "Y Data (comma-separated)",
                value = "1.4, 2.7, 2.9, 4.5, 5.0, 6.3, 7.2, 8.0, 9.5, 10.1"),

      h4("Confidence Level"),
      sliderInput("conf_level", "Confidence Level",
                  min = 0.80, max = 0.99, value = 0.95, step = 0.01),

      actionButton("calc_btn", "Calculate CI", class = "btn-primary")
    ),

    mainPanel(
      tabsetPanel(
        tabPanel("Results",
                 h4("Stochastic Approximation (SA) Method"),
                 verbatimTextOutput("sa_result"),

                 h4("Bootstrap BCa Method"),
                 verbatimTextOutput("boot_result")
        ),

        tabPanel("Visualization",
                 plotOutput("scatter_plot"),
                 br(),
                 plotOutput("ci_plot")
        ),

        tabPanel("Simulation",
                 selectInput("scenario", "Select Scenario",
                             choices = c(
                               "n=15, rho=0" = "n15_rho0",
                               "n=30, rho=0.3" = "n30_rho03",
                               "n=50, rho=0.6" = "n50_rho06"
                             )),
                 actionButton("run_sim", "Run Simulation", class = "btn-success"),
                 br(), br(),
                 verbatimTextOutput("sim_result")
        )
      )
    )
  )
)

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

  calc_corrCI <- eventReactive(input$calc_btn, {
    x <- as.numeric(strsplit(input$x_data, ",")[[1]])
    y <- as.numeric(strsplit(input$y_data, ",")[[1]])
    list(x = x, y = y)
  })

  output$sa_result <- renderPrint({
    data <- calc_corrCI()
    result <- corrCI_sa(data$x, data$y, conf.level = input$conf_level)
    print(result)
  })

  output$boot_result <- renderPrint({
    data <- calc_corrCI()
    result <- boot_corrCI(data$x, data$y, conf.level = input$conf_level)
    print(result)
  })

  output$scatter_plot <- renderPlot({
    data <- calc_corrCI()
    plot(data$x, data$y, xlab = "X", ylab = "Y",
         main = "Scatter Plot", pch = 19, col = "steelblue")
  })

  output$ci_plot <- renderPlot({
    data <- calc_corrCI()
    sa_res <- corrCI_sa(data$x, data$y, conf.level = input$conf_level)
    boot_res <- boot_corrCI(data$x, data$y, conf.level = input$conf_level)

    methods <- c("SA (Xiong & Xu)", "Bootstrap BCa")
    lower <- c(sa_res$lower, boot_res$lower)
    upper <- c(sa_res$upper, boot_res$upper)

    plot(NULL, xlim = c(0, 3), ylim = range(c(lower, upper)) + c(-0.1, 0.1),
         yaxt = "n", xlab = "", ylab = "Correlation")
    axis(2, las = 2)
    for (i in 1:2) {
      segments(i, lower[i], i, upper[i], lwd = 3, col = i)
      points(i, (lower[i] + upper[i]) / 2, pch = 20, col = "red", cex = 2)
    }
    legend("topright", methods, col = 1:2, lwd = 2)
    title(main = "95% Confidence Intervals Comparison")
  })

  output$sim_result <- renderPrint({
    input$run_sim
    isolate({
      scenario <- input$scenario
      set.seed(42)
      if (scenario == "n15_rho0") {
        n <- 15; rho <- 0
      } else if (scenario == "n30_rho03") {
        n <- 30; rho <- 0.3
      } else {
        n <- 50; rho <- 0.6
      }
      # Monte Carlo simulation
      sigma <- matrix(c(1, rho, rho, 1), 2, 2)
      Z <- mvtnorm::rmvnorm(n * 100, c(0, 0), sigma)
      Z <- cbind(t(matrix(Z[, 1], n)), t(matrix(Z[, 2], n)))

      covered <- 0
      for (i in 1:100) {
        x <- Z[i, 1:n]
        y <- Z[i, (n+1):(2*n)]
        ci <- corrCI_sa(x, y)
        if (ci$lower <= rho && rho <= ci$upper) {
          covered <- covered + 1
        }
      }
      cat("Scenario: n =", n, ", rho =", rho, "\n")
      cat("Coverage probability:", covered / 100, "\n")
    })
  })
}

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