library(shiny)
library(mathjaxr)

# Function to generate multiple dynamic lines
generate_dynamic_lines <- function(dynamics, texts) {
  lines <- lapply(seq_along(dynamics), function(i) {
    fluidRow(
      column(8, tags$p(HTML(texts[i]), class = "compact-text")),
      column(1, textOutput(dynamics[i]), class = "compact-text")
    )
  })
  return(do.call(tagList, lines))
}
# Function to generate lines with equations and text
generate_text_with_equation <- function(equations, paragraphs) {
  report_html <- tags$div()
  for (i in seq_along(equations)) {
    text_html <- HTML(paragraphs[i])
    equation_html <- withMathJax(equations[i])
    report_html <- tagAppendChild(report_html, tags$p(text_html))
    report_html <- tagAppendChild(report_html, tags$p(equation_html))
  }
  return(report_html)
}
# Function to generate equations and text in the same line inside a table
generate_text_with_equation_1 <- function(equations2, paragraphs2) {
  report_html <- tags$div()
  table_html <- tags$table(
    lapply(seq_along(equations2), function(i) {
      equation_html <- withMathJax(equations2[i])
      text_html <- HTML(paragraphs2[i])
      tags$tr(
        tags$td(equation_html, style = "padding-right: 20px;"),
        tags$td(text_html)
      )
    })
  )
  report_html <- tagAppendChild(report_html, table_html)
  return(report_html)
}

# Start UI
ui <- fluidPage(
  tags$head(
    # Define the output style
    tags$style(HTML("
      body {
        background-color: #f0f0f0;
        font-family: Arial ;
         font-size: 12px;
      }
      .well {
        border: 3px solid #dddddd;
      }
      .navbar-brand {
        font-size: 2.0em;
      }
      .tab-pane {
        margin-top: 5px;
      }
       .dropdown-menu li a {
        font-size: 12px;
       }

       .custom-title-bold {
                      font-size: 15px;
                     text-align: left;
                    }
    .bordered-panel {
      border: 3px solid #dddddd;  /* Bordes de 2 pÃ­xeles con color negro */
      padding: 20px;           /* Espaciado interno */
      border-radius: 10px;     /* Esquinas redondeadas */
    }
    ")),
    tags$script(src = "https://polyfill.io/v3/polyfill.min.js?features=es6"),
    tags$script(id = "MathJax-script", async = TRUE, src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js")
  ),
  navbarPage(
    "SAMPLE X",
    # Menu for simple random sampling
    shiny::navbarMenu(HTML("<b>Simple Random Sampling</b>"),
                      shiny::tabPanel(HTML("<b>The Mean</b>"), id = "M",
                                      sidebarLayout(
                                        sidebarPanel(
                                          id = "sidebar_SRS",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          
                                          selectInput("Type", label = "Sampling type", choices = c("Infinite Population", "Finite Population")),
                                          conditionalPanel(
                                            'input.Type == "Finite Population"',
                                            numericInput(inputId = "N", label = "Population size:", value = 300, min = 1)
                                          ),
                                          numericInput(inputId = "Confidence", label = "Confidence level", value = 95, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Precision", label = "Absolute precision", value = 3, min = 0, step = 1),
                                          numericInput(inputId = "Variance", label = "Estimated variance", value = 100, min = 0)
                                          
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",  # AÃ±adir la clase aquÃ­
                                          
                                          tabsetPanel(
                                            tabPanel("Sampling Plan", uiOutput("summary")),
                                            tabPanel("Equation", uiOutput("equa")),
                                            tabPanel("Additional Information", uiOutput("inform")),
                                            tabPanel("Example", uiOutput("example"))
                                          )
                                        )
                                      )
                      ),
                      shiny::tabPanel(HTML("<b>Proportion</b>"), id = "P",
                                      sidebarLayout(
                                        sidebarPanel(
                                          
                                          id = "sidebar_SRS_p",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          
                                          selectInput("Type2", label = "Sampling type", choices = c("Infinite Population", "Finite Population")),
                                          conditionalPanel(
                                            'input.Type2 == "Finite Population"',
                                            numericInput(inputId = "N2", label = "Population size:", value = 2000, min = 1)
                                          ),
                                          numericInput(inputId = "Confidence2", label = "Confidence level", value = 95, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Precision2", label = "Absolute precision", value = 0.05, min = 0, max = 1, step = 0.01),
                                          numericInput(inputId = "Proportion2", label = "Proportion of the characteristic", value = 0.5, min = 0, max = 1)
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",  # AÃ±adir la clase aquÃ­
                                          
                                          tabsetPanel(
                                            tabPanel("Sampling Plan", uiOutput("summaryp")),
                                            tabPanel("Equation", uiOutput("equap")),
                                            tabPanel("Additional Information", uiOutput("informp")),
                                            tabPanel("Example", uiOutput("examplep"))
                                          )
                                        )
                                      )
                      ),
                      shiny::tabPanel(HTML("<b>The Total</b>"), id = "T",
                                      sidebarLayout(
                                        sidebarPanel(
                                          id = "sidebar_SRS_t",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          
                                          selectInput("Type3", label = "Sampling type", choices = c("Finite Population")),
                                          conditionalPanel(
                                            'input.Type3 == "Finite Population"',
                                            numericInput(inputId = "N3", label = "Population size:", value = 500, min = 1)
                                          ),
                                          numericInput(inputId = "Confidence3", label = "Confidence level", value = 95, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Precision3", label = "Absolute precision", value = 5000, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Variance3", label = "Estimated variance", value = 1000, min = 0)                                        
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",  # AÃ±adir la clase aquÃ­
                                          
                                          tabsetPanel(
                                            tabPanel("Sampling Plan", uiOutput("summaryt")),
                                            tabPanel("Equation", uiOutput("equat")),
                                            tabPanel("Additional Information", uiOutput("informt")),
                                            tabPanel("Example", uiOutput("examplet"))
                                          )
                                        )
                                      )
                      )
    ),
    
    shiny::navbarMenu(HTML("<b>Stratified Sampling</b>"),
                      shiny::tabPanel(HTML("<b>The Mean</b>"), id = "ME",
                                      sidebarLayout(
                                        sidebarPanel(
                                          
                                          id = "sidebar_ES",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          selectInput("Type_A", label = "Assignment type", choices = c("Uniform Assignment", "Proportional Assignment",
                                                                                                       "Neyman Assignment", "Optimal Fixed Variance and Minimum Cost",
                                                                                                       "Optimal Minimum Variance and Fixed Cost")),
                                          
                                          numericInput("population_sizeME", "Population size:", value = 483, min = 2),
                                          conditionalPanel(
                                            'input.Type_A == "Optimal Minimum Variance and Fixed Cost"',
                                            numericInput(inputId = "Cost", label = "Total Cost:", value = 5000, min = 0)
                                          ),
                                          conditionalPanel(
                                            'input.Type_A != "Optimal Minimum Variance and Fixed Cost"',
                                            numericInput("precisionME", "Absolute precision:", value = 3, min = 0),
                                            numericInput("confidenceME", "Confidence level:", value = 95, min = 0, max = 100)
                                          ),
                                          numericInput("num_strata", "Number of strata:", value = 4, min = 2),
                                          p(strong("Now capture the information about the strata"), style = "color: red;")
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",  # AÃ±adir la clase aquÃ­
                                          
                                          tabsetPanel(
                                            tabPanel("Sampling Plan",
                                                     tags$h4(class = "custom-title-bold", textOutput("plan_title")),#h4(textOutput("plan_title")),
                                                     p("To continue, you must enter the information for the strata. In the spaces provided, enter the values for the variance and size of each stratum, then press the enter key and continue the same way with the remaining strata. The information about the strata must be added one stratum at a time."),
                                                     tags$h4(class = "custom-title-bold","Information about the strata"),
                                                     fluidRow(
                                                       column(4, numericInput("stratum_size", "Stratum Size:", value = 0)),
                                                       column(4, numericInput("estimated_variance", "Estimated Variance:", value = 0)),
                                                       conditionalPanel(
                                                         condition = "input.Type_A == 'Optimal Fixed Variance and Minimum Cost' || input.Type_A == 'Optimal Minimum Variance and Fixed Cost'",
                                                         column(4, numericInput("costs", "Costs:", value = 0))
                                                       )
                                                     ),
                                                     fluidRow(
                                                       column(4, actionButton("submit", "Submit Data", style = "color: #fff; background-color: #007bff; border-color: #007bff")),
                                                       column(4, actionButton("clear", "Clear Data", style = "color: #fff; background-color: #dc3545; border-color: #dc3545"))
                                                     ),
                                                     verbatimTextOutput("error_message"),
                                                     verbatimTextOutput("sample_size"),
                                                     verbatimTextOutput("table_data")
                                            ),
                                            tabPanel("Equation", uiOutput("equame")),
                                            tabPanel("Additional Information", uiOutput("informme")),
                                            tabPanel("Example", uiOutput("exampleme"))
                                          )
                                        )
                                      )
                      ),
                      shiny::tabPanel(HTML("<b>A Proportion</b>"), id = "P_ES",
                                      sidebarLayout(
                                        sidebarPanel(
                                          
                                          id = "sidebar_ESp",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          selectInput("Type_B", label = "Assignment type", choices = c("Uniform Assignment", "Proportional Assignment",
                                                                                                       "Neyman Assignment", "Optimal Fixed Variance and Minimum Cost",
                                                                                                       "Optimal Minimum Variance and Fixed Cost")),
                                          
                                          numericInput("population_sizeMEp", "Population size:", value = 2400, min = 2),
                                          conditionalPanel(
                                            'input.Type_B == "Optimal Minimum Variance and Fixed Cost"',
                                            numericInput(inputId = "Costp", label = "Total Cost:", value = 80000, min = 0)
                                          ),
                                          conditionalPanel(
                                            'input.Type_B != "Optimal Minimum Variance and Fixed Cost"',
                                            numericInput("precisionMEp", "Absolute precision:", value = 0.04, min = 0,max=1),
                                            numericInput("confidenceMEp", "Confidence level:", value = 95, min = 0, max = 100)
                                          ),
                                          numericInput("num_stratap", "Number of strata:", value = 3, min = 2),
                                          p(strong("Now capture the information about the strata"), style = "color: red;")
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",  # Añadir la clase aqui
                                          
                                          tabsetPanel(
                                            tabPanel("Sampling Plan",
                                                     tags$h4(class = "custom-title-bold", textOutput("plan_title_p")),
                                                     p("To continue, you must enter the information for the strata. In the spaces provided, enter the values for the variance and size of each stratum, then press the enter key and continue the same way with the remaining strata. The information about the strata must be added one stratum at a time."),
                                                     tags$h4(class = "custom-title-bold","Information about the strata"),
                                                     fluidRow(
                                                       column(4, numericInput("stratum_sizep", "Stratum Size:", value = 0)),
                                                       column(4, numericInput("estimated_proportion", "Estimated Proportion:",min=0, max=1, value = 0)),
                                                       conditionalPanel(
                                                         condition = "input.Type_B == 'Optimal Fixed Variance and Minimum Cost' || input.Type_B == 'Optimal Minimum Variance and Fixed Cost'",
                                                         column(4, numericInput("costsp", "Costs:", value = 0))
                                                       )
                                                     ),
                                                     fluidRow(
                                                       column(4, actionButton("submitp", "Submit Data", style = "color: #fff; background-color: #007bff; border-color: #007bff")),
                                                       column(4, actionButton("clearp", "Clear Data", style = "color: #fff; background-color: #dc3545; border-color: #dc3545"))
                                                     ),
                                                     verbatimTextOutput("error_message"),
                                                     verbatimTextOutput("sample_sizep"),
                                                     verbatimTextOutput("table_datap")
                                            ),
                                            tabPanel("Equation", uiOutput("equamep")),
                                            tabPanel("Additional Information", uiOutput("informmep")),
                                            tabPanel("Example", uiOutput("examplemep"))
                                          )
                                        )
                                      )
                      ),
                      
                      shiny::tabPanel(HTML("<b>The Total</b>"), id = "T_ES",
                                      sidebarLayout(
                                        sidebarPanel(
                                          
                                          id = "sidebar_ESt",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          
                                          selectInput("Type_C", label = "Assignment type", choices = c("Uniform Assignment", "Proportional Assignment",
                                                                                                       "Neyman Assignment", "Optimal Fixed Variance and Minimum Cost",
                                                                                                       "Optimal Minimum Variance and Fixed Cost")),
                                          
                                          numericInput("population_sizeMEt", "Population size:", value = 1000, min = 2),
                                          conditionalPanel(
                                            'input.Type_C == "Optimal Minimum Variance and Fixed Cost"',
                                            numericInput(inputId = "Costt", label = "Total Cost:", value = 5000, min = 0)
                                          ),
                                          conditionalPanel(
                                            'input.Type_C != "Optimal Minimum Variance and Fixed Cost"',
                                            numericInput("precisionMEt", "Absolute precision:", value = 50000, min = 0),
                                            numericInput("confidenceMEt", "Confidence level:", value = 95, min = 0, max = 100)
                                          ),
                                          numericInput("num_stratat", "Number of strata:", value = 3, min = 2),
                                          p(strong("Now capture the information about the strata"), style = "color: red;")
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",  # AÃ±adir la clase aquÃ­
                                          
                                          tabsetPanel(
                                            tabPanel("Sampling Plan",
                                                     tags$h4(class = "custom-title-bold", textOutput("plan_title_t")),
                                                     p("To continue, you must enter the information for the strata. In the spaces provided, enter the values for the variance and size of each stratum, then press the enter key and continue the same way with the remaining strata. The information about the strata must be added one stratum at a time."),
                                                     tags$h4(class = "custom-title-bold","Information about the strata"),
                                                     fluidRow(
                                                       column(4, numericInput("stratum_sizet", "Stratum Size:", value = 0)),
                                                       column(4, numericInput("estimated_variancet", "Estimated variance:",min=0,  value = 0)),
                                                       conditionalPanel(
                                                         condition = "input.Type_C == 'Optimal Fixed Variance and Minimum Cost' || input.Type_C == 'Optimal Minimum Variance and Fixed Cost'",
                                                         column(4, numericInput("costst", "Costs:", value = 0))
                                                       )
                                                     ),
                                                     fluidRow(
                                                       column(4, actionButton("submitt", "Submit Data", style = "color: #fff; background-color: #007bff; border-color: #007bff")),
                                                       column(4, actionButton("cleart", "Clear Data", style = "color: #fff; background-color: #dc3545; border-color: #dc3545"))
                                                     ),
                                                     verbatimTextOutput("error_messaget"),
                                                     verbatimTextOutput("sample_sizet"),
                                                     verbatimTextOutput("table_datat")
                                            ),
                                            tabPanel("Equation", uiOutput("equamet")),
                                            tabPanel("Additional Information", uiOutput("informmet")),
                                            tabPanel("Example", uiOutput("examplemet"))
                                          )
                                        )
                                      )
                      )
    ),
    
    shiny::navbarMenu(HTML("<b>Single-Stage Cluster</b>"),
                      
                      shiny::tabPanel(HTML("<b>The Mean</b>"), id = "mc",
                                      sidebarLayout(
                                        sidebarPanel(
                                          id = "sidebar_mc",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          
                                          
                                          selectInput(
                                            inputId = "method_mc",
                                            label = "Method to determine sample size:",
                                            choices = c("Using intracluster correlation", "Using deff")
                                          ),
                                          
                                          selectInput(
                                            "Type_mc", 
                                            label = "Sampling type", 
                                            choices = c("Infinite Population", "Finite Population")
                                          ),
                                          
                                          conditionalPanel(
                                            condition = 'input.Type_mc == "Finite Population"',
                                            numericInput(inputId = "N_mc", label = "Total number of clusters:", value = 300, min = 1)
                                          ),
                                          
                                          numericInput(inputId = "Confidence_mc", label = "Confidence level", value = 95, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Variance_mc", label = "Estimated variance", value = 1000, min = 0),
                                          numericInput(inputId = "Precision_mc", label = "Absolute precision", value = 5, min = 0, step = 1),
                                          conditionalPanel(
                                            condition = 'input.method_mc == "Using intracluster correlation"',
                                            numericInput(inputId = "ICC_mc", label = "Intracluster correlation", value = 0.01, min = 0, max = 1, step = 0.01),
                                            numericInput(inputId = "CSUS_mc", label = "Average cluster size", value = 50, min = 0, step = 1)
                                          ),
                                          conditionalPanel(
                                            condition = 'input.method_mc == "Using deff"', 
                                            numericInput(inputId = "CSUS_mc", label = "Average cluster size", value = 50, min = 0, step = 1),
                                            numericInput(inputId = "deff_mc", label = "Design effect (deff)", value = 1.49, min = 1, step = 0.1)
                                          )
                                        ),
                                        
                                        mainPanel(
                                          class = "bordered-panel",
                                          tabsetPanel(
                                            tabPanel("Sampling Plan", uiOutput("summarymc")),
                                            tabPanel("Equation", uiOutput("equamc")),
                                            tabPanel("Additional Information", uiOutput("informmc")),
                                            tabPanel("Example", uiOutput("examplemc"))
                                          )
                                        )
                                      )
                      ),
                      
                      shiny::tabPanel(HTML("<b>A Proportion</b>"), id = "Pc",
                                      sidebarLayout(
                                        sidebarPanel(
                                          id = "sidebar_Pc",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          selectInput(
                                            inputId = "method_pc",
                                            label = "Method to determine sample size:",
                                            choices = c("Using intracluster correlation", "Using deff")
                                          ),
                                          
                                          selectInput("Type_pc", label = "Sampling type", choices = c("Infinite Population", "Finite Population")),
                                          conditionalPanel(
                                            'input.Type_pc == "Finite Population"',
                                            numericInput(inputId = "N_pc", label = "Total number of clusters:", value = 600, min = 1)
                                          ),
                                          numericInput(inputId = "Confidence_pc", label = "Confidence level", value = 95, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Proportion_pc", label = "Proportion of the characteristic", value = 0.8, min = 0, max = 1, step = 0.01),
                                          numericInput(inputId = "Precision_pc", label = "Absolute precision", value = 0.04, min = 0, max = 1, step = 0.01),
                                          
                                          conditionalPanel(
                                            condition = 'input.method_pc == "Using intracluster correlation"',
                                            numericInput(inputId = "ICC_pc", label = "Intracluster correlation", value = 0.01, min = 0, max = 1, step = 0.01),
                                            numericInput(inputId = "CSUS_pc", label = "Average cluster size", value = 100, min = 0, step = 1)
                                          ),
                                          conditionalPanel(
                                            condition = 'input.method_pc == "Using deff"',
                                            numericInput(inputId = "CSUS_pc", label = "Average cluster size", value = 100, min = 0, step = 1),
                                            numericInput(inputId = "deff_pc", label = "Design effect (deff)", value = 1.99, min = 1, step = 0.1)
                                            
                                          )
                                        ),
                                        mainPanel(
                                          class = "bordered-panel",
                                          tabsetPanel(
                                            tabPanel("Sampling Plan", uiOutput("summarypc")),
                                            tabPanel("Equation", uiOutput("equapc")),
                                            tabPanel("Additional Information", uiOutput("informpc")),
                                            tabPanel("Example", uiOutput("examplepc"))
                                          )
                                        )
                                      )
                      ),
                      
                      shiny::tabPanel(HTML("<b>The Total</b>"), id = "ct",
                                      sidebarLayout(
                                        sidebarPanel(
                                          id = "sidebar_t_c",
                                          p(span(strong("CAPTURE STARTS HERE"), style = "color: red;")),
                                          
                                          
                                          # NUEVO BOTÓN para elegir método
                                          selectInput(
                                            inputId = "method_tc",
                                            label = "Method to determine sample size:",
                                            choices = c("Using intracluster correlation", "Using deff")
                                          ),
                                          
                                          selectInput("Type_ct", label = "Sampling type", choices = c("Finite Population")),
                                          numericInput(inputId = "N_tc", label = "Total number of clusters", value = 500, min = 1),
                                          numericInput(inputId = "Confidence_tc", label = "Confidence level", value = 95, min = 0, max = 100, step = 1),
                                          numericInput(inputId = "Variance_tc", label = "Estimated variance", value = 100, min = 0),
                                          numericInput(inputId = "Precision_tc", label = "Absolute precision", value = 1000, min = 0, max = 100, step = 1),
                                          
                                          # Mostrar solo si se selecciona "Using intracluster correlation"
                                          conditionalPanel(
                                            condition = 'input.method_tc == "Using intracluster correlation"',
                                            numericInput(inputId = "ICC_tc", label = "Intracluster correlation", value = 0.05, min = 0, max = 1, step = 0.01), 
                                            numericInput(inputId = "CSUS_tc", label = "Average cluster size", value = 30, min = 0, step = 1),
                                          ),
                                          
                                          # Mostrar solo si se selecciona "Using deff"
                                          conditionalPanel(
                                            condition = 'input.method_tc == "Using deff"',
                                            numericInput(inputId = "deff_tc", label = "Design effect (deff)", value = 2.45, min = 1, step = 0.1)
                                          )
                                        ),
                                        
                                        mainPanel(
                                          class = "bordered-panel",
                                          tabsetPanel(
                                            tabPanel(HTML("<b>Sampling Plan</b>"), uiOutput("summarytc")),
                                            
                                            tabPanel("Equation", uiOutput("equatc")),
                                            tabPanel("Additional Information", uiOutput("informtc")),
                                            tabPanel("Example", uiOutput("exampletc"))
                                          )
                                        )
                                      )
                      )
    )
  )
)

# Start server section
server <- function(input, output, session) {
  #############################################################################
  ################################################ Start simple random sampling
  #############################################################################
  ############ Start summary mean simple random sampling
  #######################################################
  descriptionT3 <- paste("Note: The sample size corresponds to the nearest upper integer.")
  descriptionT_div1 <- tags$div(descriptionT3)
  output$summary <- renderUI({
    output$pop_size_value <- renderText({ input$N })
    output$conf_value <- renderText({ input$Confidence })
    output$prec_value <- renderText({ input$Precision })
    output$var_value <- renderText({ input$Variance })
    confidence <- input$Confidence
    precision <- input$Precision
    variance <- input$Variance
    alpha2 <- (1 - confidence / 100) / 2
    z <- qnorm(alpha2, lower.tail = FALSE)
    n0 <- variance * (z^2) / (precision^2)
    if (input$Type == "Infinite Population") {
      ni <- ceiling(n0)
      output$ni_value <- renderText(ni)
      
      texts <- c(
        "",
        "The estimated sample size : ",
        "Confidence level : ",
        "The absolute precision :",
        "The estimated variance of the studied characteristic : "
        
      )
      
      title <- "Sample Size for Estimating the Mean with Simple Random Sampling and Infinite Populations"
      dynamics <- c("", "ni_value", "conf_value", "prec_value", "var_value")
      
      P1 <- generate_dynamic_lines(dynamics, texts)
      report_f_html <- tags$div()
      title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
      report_f_html <- tagAppendChild(report_f_html, title_html)
      report_f_html <- tagAppendChild(report_f_html, P1)
      report_f_html <- tagAppendChild(report_f_html, descriptionT_div1)
      
      return(report_f_html)
    } else {
      N <- input$N
      ni <- ceiling(n0 / (1 + (n0 / N)))
      output$ni_value <- renderText(ni)
      
      texts <- c(
        "", 
        "The estimated sample size : ",
        "The population size : ",
        "Confidence level : ",
        "The absolute precision : ",
        "The estimated variance of the studied characteristic : "
        
      )
      
      title <- "Sample Size for Estimating the Mean with Simple Random Sampling and Finite Populations"
      dynamics <- c(" ", "ni_value","pop_size_value", "conf_value", "prec_value", "var_value")
      
      P1 <- generate_dynamic_lines(dynamics, texts)
      
      report_f_html <- tags$div()
      title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
      report_f_html <- tagAppendChild(report_f_html, title_html)
      report_f_html <- tagAppendChild(report_f_html, P1)
      report_f_html <- tagAppendChild(report_f_html, descriptionT_div1)
      return(report_f_html)
    }
  })
  
  ############ Start equations mean simple random sampling
  output$equa <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type == "Infinite Population") {
      equations <- c("","$$n_0 = \\frac{s^2 z_{(\\alpha/2)}^2}{e^2}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate the mean of an infinite population:")
    } else {
      equations <- c("","$$n = \\frac{N s^2 z_{(\\alpha/2)}^2}{N e^2 + s^2 z_{(\\alpha/2)}^2} = \\frac{n_0}{1 + \\frac{n_0}{N}}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate the mean of a finite population:")
    }
    
    # Definition of additional explanatory paragraphs
    paragraphs2 <- c("Where:")
    if (input$Type == "Infinite Population") {
      paragraphs2 <- c(paragraphs2, "is the sample size to estimate the mean of an infinite population.")
    } else {
      paragraphs2 <- c(paragraphs2, "is the sample size to estimate the mean of an infinite population.",
                       "is the sample size to estimate the mean of a finite population.")
    }
    paragraphs2 <- c(paragraphs2,
                     "is the variance of the characteristic of interest.",
                     "is the z-score corresponding to the desired confidence level.",
                     "is the maximum permissible absolute error (or desired absolute precision)."
    )
    
    # Definition of additional explanatory equations
    equations2 <- c("$$ $$")
    if (input$Type == "Infinite Population") {
      equations2 <- c(equations2, "$$n_0$$")
    } else {
      equations2 <- c(equations2, "$$n_0$$", "$$n$$")
    }
    equations2 <- c(equations2, "$$s^2$$", "$$z_{(\\alpha/2)}$$", "$$e$$")
    
    if (input$Type == "Finite Population") {
      equations2 <- c(equations2, "$$N$$")
      paragraphs2 <- c(paragraphs2, "is the population size.")
    }
    if (input$Type == "Finite Population") {
      title <- "Equation of Sample Size Calculation for Estimating the Mean with Simple Random Sampling and Finite Populations"
    }else{
      title <- "Equation of Sample Size Calculation for Estimating the Mean with Simple Random Sampling and Infinite Populations"
    }
    report_html <- tags$div()
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ############ Start additional information  mean simple random sampling
  output$inform <- renderUI({
    if (input$Type == "Infinite Population") {
      equations <- c(
        "",
        "$$\\bar{y} = \\frac{1}{n} \\sum_{i=1}^{n} y_i$$",
        "$$\\hat{V}(\\bar{y}) = \\frac{s^2}{n}$$"
      )
    } else {
      equations <- c(
        "",
        "$$\\bar{y} = \\frac{1}{n} \\sum_{i=1}^{n} y_i$$",
        "$$\\hat{V}(\\bar{y}) = \\left(1 - \\frac{n}{N}\\right) \\frac{s^2}{n}$$"
      )
    }
    paragraphs <- c(
      "",
      "Estimator of the population total:",
      "Estimator of the variance of the sample mean:"
    )
    
    paragraphs2 <- c(
      "Where:",
      "is the sample mean",
      "is the sample variance of the characteristic of interest",
      "is the sample size"
    )
    
    equations2 <- c("$$ $$", "$$\\bar{y}$$", "$$s^2$$", "$$n$$")
    if (input$Type == "Finite Population") {
      equations2 <- c(equations2, "$$N$$")
      paragraphs2 <- c(paragraphs2, "is the population size")
    }
    
    title <- if (input$Type == "Finite Population") {
      "Estimating The Mean with Simple Random Sampling and Finite Populations"
    } else {
      "Estimating The mean with Simple Random Sampling and Infinite Populations"
    }
    
    report_html <- tags$div()
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ################# Start example mean simple random sampling
  output$example <- renderUI({
    # Define the content of the example
    if (input$Type == "Finite Population") {
      example_title <- "Example: Estimating the Mean with Simple Random Sampling and Finite Populations"
    }else{
      example_title <- "Example: Estimating the Mean with Simple Random Sampling and Infinite Populations"
    }
    if (input$Type == "Finite Population") {
      example_description <- paste(
        "On a ranch where steers are fattened for meat, the goal is to estimate the average",
        "weight per steer. It is known that the estimated variance is 100. The aim is to",
        "estimate the average weight per steer with a precision of 3 kg and a confidence",
        "level of 95%. What sample size will be needed to meet the given requirements if",
        "N = 300 steers?"
      )
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating the Mean with Simple Random Sampling and Finite Populations"
      
      example_result <- c(
        "",
        "The estimated sample size :",
        "The population size :",
        "Confidence level :",
        "The absolute precision :",
        "The estimated variance of the studied characteristic :"
        
      )
      result_numbers <- c("", 38 ,300, 95, 3, 100)
      
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        table_html,
        tags$p(HTML(blanco)),
        tags$p(HTML(descriptionT3))
      )
      
      return(example_html)
    } else {
      example_description <- paste(
        "A researcher wants to estimate the mean systolic blood pressure of adult Americans",
        "with 95% confidence and an error no larger than 3 mm Hg. If the estimated variance",
        "is 100, how many adult Americans should the researcher randomly sample to achieve",
        "her estimation goal?"
      )
      example_title2 <- "Result:"
      example_title3 <-  "Sample Size for Estimating the Mean with Simple Random Sampling and Infinite Populations"
      
      example_result <- c(
        "",
        "The estimated sample size :",
        "Confidence level :",
        "The absolute precision :",
        "The estimated variance of the studied characteristic :"
        
      )
      result_numbers <- c("", 43,95, 3, 100)
      
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        table_html,
        tags$p(HTML(blanco)),
        tags$p(HTML(descriptionT3))
      )
      
      return(example_html)
    }
  })
  
  ##############################################################################################
  ################################################ Start simple random sampling with proportions
  ##############################################################################################
  
  ############ Start summary proportion simple random sampling
  output$summaryp <- renderUI({
    output$pop_size_valuep <- renderText({ input$N2 })
    output$conf_valuep <- renderText({ input$Confidence2 })
    output$prec_valuep <- renderText({ input$Precision2 })
    output$prop_valuep <- renderText({ input$Proportion2 })
    
    confidence <- input$Confidence2
    precision <- input$Precision2
    proportion <- input$Proportion2
    alpha2 <- (1 - confidence / 100) / 2
    z <- qnorm(alpha2, lower.tail = FALSE)
    n0 <- proportion * (1 - proportion) * (z^2) / (precision^2)
    
    if (input$Type2 == "Infinite Population") {
      ni <- ceiling(n0)
      output$ni_valuep <- renderText(ni)
      
      texts <- c(
        "",
        "The estimated sample size: ",
        "Confidence level: ",
        "The absolute precision:",
        "The estimated proportion of the studied characteristic: "
        
      )
      
      title <- "Sample Size for Estimating the Proportion with Simple Random Sampling and Infinite Populations"
      dynamics <- c("", "ni_valuep","conf_valuep", "prec_valuep", "prop_valuep")
      
      P1 <- generate_dynamic_lines(dynamics, texts)
      report_f_html <- tags$div()
      title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
      report_f_html <- tagAppendChild(report_f_html, title_html)
      report_f_html <- tagAppendChild(report_f_html, P1)
      report_f_html <- tagAppendChild(report_f_html, descriptionT_div1)
      
      return(report_f_html)
    } else {
      N <- input$N2
      ni <- ceiling(n0 / (1 + (n0 / N)))
      output$ni_valuep <- renderText(ni)
      
      texts <- c(
        "",
        "The estimated sample size : ",
        "The population size : ",
        "Confidence level :",
        "The absolute precision : ",
        "The estimated proportion of the studied characteristic : "
        
      )
      
      title <- "Sample Size for Estimating the Proportion with Simple Random Sampling and Finite Populations"
      dynamics <- c("", "ni_valuep","pop_size_valuep", "conf_valuep", "prec_valuep", "prop_valuep")
      
      P1 <- generate_dynamic_lines(dynamics, texts)
      report_f_html <- tags$div()
      title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
      report_f_html <- tagAppendChild(report_f_html, title_html)
      report_f_html <- tagAppendChild(report_f_html, P1)
      report_f_html <- tagAppendChild(report_f_html, descriptionT_div1)
      
      return(report_f_html)
    }
  })
  
  ############ Start equations proportion simple random sampling
  output$equap <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type2 == "Infinite Population") {
      equations <- c("","$$n_0 = \\frac{p (1-p) z_{(\\alpha/2)}^2}{e^2}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate the proportion of an infinite population:")
    } else {
      equations <- c("","$$n = \\frac{N p (1-p) z_{(\\alpha/2)}^2}{N e^2 + p (1-p) z_{(\\alpha/2)}^2} = \\frac{n_0}{1 + \\frac{n_0}{N}}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate the proportion of a finite population:")
    }
    
    # Definition of additional explanatory paragraphs
    paragraphs2 <- c("Where:")
    if (input$Type2 == "Infinite Population") {
      paragraphs2 <- c(paragraphs2, "is the sample size to estimate a proportion of an infinite population.")
    } else {
      paragraphs2 <- c(paragraphs2, "is the sample size to estimate a proportion of an infinite population.",
                       "is the sample size to estimate the proportion of a finite population.")
    }
    paragraphs2 <- c(paragraphs2,
                     "is the estimated proportion of the characteristic of interest.",
                     "is the z-score corresponding to the desired confidence level.",
                     "is the maximum permissible absolute error (or desired absolute precision)."
    )
    
    # Definition of additional explanatory equations
    equations2 <- c("$$ $$")
    if (input$Type2 == "Infinite Population") {
      equations2 <- c(equations2, "$$n_0$$")
    } else {
      equations2 <- c(equations2, "$$n_0$$", "$$n$$")
    }
    equations2 <- c(equations2, "$$p$$", "$$z_{(\\alpha/2)}$$", "$$e$$")
    
    if (input$Type2 == "Finite Population") {
      equations2 <- c(equations2, "$$N$$")
      paragraphs2 <- c(paragraphs2, "is the population size.")
    }
    
    if (input$Type2 == "Infinite Population") {
      title <- "Equation for Sample Size Calculation for Estimating a Proportion with Simple Random Sampling and Infinite Populations"
    } else {
      title <- "Equation for Sample Size Calculation for Estimating a Proportion with Simple Random Sampling and Finite Populations"
    }
    report_html <- tags$div()
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  
  ############ Start additional information proportion simple random sampling
  output$informp <- renderUI({
    if (input$Type2 == "Infinite Population") {
      equations <- c(
        "",
        "$$\\hat{p} = \\frac{1}{n} \\sum_{i=1}^{n} x_i$$",
        "$$ x_{i} =
            \\begin{cases}
            1 & \\text{If the characteristic of interest is present} \\\\
            0 & \\text{If the characteristic of interest is not present}
           \\end{cases}
           $$",
        
        "$$\\hat{V}(\\hat{p}) = \\frac{\\hat{p}(1-\\hat{p})}{n}$$"
      )
    } else {
      equations <- c(
        "",
        "$$\\hat{p} = \\frac{1}{n} \\sum_{i=1}^{n} x_i$$",
        
        "$$ x_{i} =
            \\begin{cases}
            1 & \\text{If the characteristic of interest is present} \\\\
            0 & \\text{If the characteristic of interest is not present}
           \\end{cases}
           $$",
        "$$\\hat{V}(\\hat{p}) = \\left(1 - \\frac{n}{N}\\right) \\frac{\\hat{p}(1-\\hat{p})}{n}$$"
      )
    }
    paragraphs <- c(
      "",
      
      "Estimator of the population proportion:",
      "Where:",
      "Estimator of the variance of the sample proportion:"
    )
    
    paragraphs2 <- c(
      "Where:",
      "is the sample proportion",
      "is the estimated variance of the sample proportion",
      "is the sample size"
    )
    
    equations2 <- c("$$ $$", "$$\\hat{p}$$", "$$\\hat{V}(\\hat{p})$$", "$$n$$")
    if (input$Type2 == "Finite Population") {
      equations2 <- c(equations2, "$$N$$")
      paragraphs2 <- c(paragraphs2, "is the population size")
    }
    
    title <- if (input$Type2 == "Finite Population") {
      "Estimating a Proportion with Simple Random Sampling and Finite Populations"
    } else {
      "Estimating a Proportion with Simple Random Sampling and Infinite Populations"
    }
    
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)#title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  
  ################# Start example proportion simple random sampling
  output$examplep <- renderUI({
    # Define the content of the example
    if (input$Type2 == "Finite Population") {
      example_title <- "Example: Estimating the the Proportion with Simple Random Sampling and Finite Populations"
    }else{
      example_title <- "Example: Estimating the the Proportion with Simple Random Sampling and Infinite Populations"
    }
    if (input$Type2 == "Finite Population") {
      example_description <- paste(
        "In a certain region of the country, an effort is made to determine the proportion",
        "of farmers who are tenants. A preliminary sample of 60 farmers from a population",
        "of 2000 is taken, and it is found that 30 of them are tenants. What should be the",
        "sample size to estimate P with a precision of 0.05 and a confidence level of 95%?"
      )
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating the Proportion with Simple Random Sampling and Finite Populations"
      
      example_result <- c(
        "",
        "The estimated sample size :",
        "The population size :",
        "Confidence level :",
        "The absolute precision :",
        "The estimated proportion of the studied characteristic :"
        
        
        
      )
      result_numbers <- c("",323,2000, 95, 0.05, 0.5)
      
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        table_html,
        tags$p(HTML(blanco)),
        tags$p(HTML(descriptionT3))
      )
      
      return(example_html)
    } else {
      example_description <- paste(
        "We want to estimate the proportion of people who prefer a new ice cream flavor",
        "in a large city. We want our estimate to have a precision of 5% (0.05) and a confidence",
        "level of 95%. Since there is no preliminary estimate of the proportion, we use p = 0.5",
        "to achieve a conservative estimate with the maximum variance."
      )
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating the Proportion with Simple Random Sampling and Infinite Populations"
      
      example_result <- c(
        "",
        "The estimated sample size :",
        "Confidence level :",
        "The absolute precision :",
        "The estimated variance of the studied characteristic :"
      )
      result_numbers <- c("", 385,95, 0.05, 0.5)
      
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        table_html,
        tags$p(HTML(blanco)),
        tags$p(HTML(descriptionT3))
      )
      
      return(example_html)
    }
  })
  
  ##############################################################################################
  ################################################ Start simple random sampling with the total
  #############################################################################################
  
  ############ Start summary total simple random sampling
  output$summaryt <- renderUI({
    output$pop_size_value3 <- renderText({ input$N3 })
    output$conf_value3 <- renderText({ input$Confidence3 })
    output$prec_value3 <- renderText({ input$Precision3 })
    output$var_value3 <- renderText({ input$Variance3 })
    N <- input$N3
    confidence <- input$Confidence3
    precision <- input$Precision3
    variance <- input$Variance3
    alpha3 <- (1 - confidence / 100) / 2
    z <- qnorm(alpha3, lower.tail = FALSE)
    ni <- ((N^2) * variance * (z^2)) / (precision^2 + variance * (z^2))
    ni <- ceiling(ni)
    output$ni_value3 <- renderText(ni)
    
    texts <- c(
      "",
      "The estimated sample size : ",
      "The population size : ",
      "The confidence level : ",
      "The absolute precision : ",
      "The estimated variance of the studied characteristic : "
      
    )
    
    title <- "Sample Size for Estimating the Total with Simple Random Sampling and Finite Populations"
    dynamics <- c("", "ni_value3","pop_size_value3", "conf_value3", "prec_value3", "var_value3")
    
    lines <- lapply(seq_along(dynamics), function(i) {
      fluidRow(
        column(10, tags$p(HTML(texts[i]))),
        column(2, textOutput(dynamics[i]))
      )
    })
    P1 <- do.call(tagList, lines)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, descriptionT_div1)
    
    return(report_f_html)
  })
  ############ Start equations total simple random sampling
  output$equat <- renderUI({
    equations <- c("","$$n = \\frac{N^2 S^2 z_{(\\alpha/2)}^2}{e^2 + S^2 z_{(\\alpha/2)}^2}$$")
    paragraphs <- c("","Equation for calculating the sample size to estimate the total of a finite population:")
    
    paragraphs2 <- c(
      "Where:",
      "is the sample size to estimate the total of a finite population.",
      "is the population size.",
      "is the estimated variance of the total of a finite population.",
      "is the z-score corresponding to the desired confidence level.",
      "is the maximum permissible absolute error (or desired absolute precision)."
    )
    
    equations2 <- c("$$ $$", "$$n$$", "$$N$$", "$$S^2$$", "$$z_{(\\alpha/2)}$$", "$$e$$")
    
    # Combine the equations and paragraphs into the UI components
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title<-"Equation of Sample Size Calculation for Estimating the Total with Simple Random Sampling and Finite Populations"
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ############ Start additional information total simple random sampling
  output$informt <- renderUI({
    equations <- c(
      "",
      "$$\\hat{t} = N\\bar{y}=N\\frac{1}{n} \\sum_{i=1}^{n} y_i$$",
      "$$\\hat{V}(\\hat{t}) = N^2\\left(1 - \\frac{n}{N}\\right) \\frac{s^2}{n}$$"
    )
    paragraphs <- c(
      "",
      "Estimator of the population total:",
      "Estimator of the variance of the sample total:"
    )
    
    paragraphs2 <- c(
      "Where:",
      "is the sample mean",
      "is the estimator of the population total.",
      "is the sample variance of the characteristic of interest",
      "is the sample size",
      "is the population size"
    )
    
    equations2 <- c("$$ $$", "$$\\bar{y}$$","$$\\hat{t}$$", "$$s^2$$", "$$n$$", "$$N$$")
    if (input$Type == "Finite Population") {
      title <- "Estimating the Total with Simple Random Sampling and Finite Populations"
    }else{
      title <- "Estimating the Total with Simple Random Sampling and Infinite Populations"
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ################# Start example total simple random sampling
  output$examplet <- renderUI({
    
    example_title <- "Example: Estimating the Total with Simple Random Sampling and Finite Populations"
    
    example_description <- paste(
      "Suppose we want to estimate the total apple production in kilograms in a region",
      "with 500 orchards. It is known that the variance of apple production per orchard",
      "is 1000 kg². We want to estimate the total production with a precision of ±5000 kg",
      "and a confidence level of 95%."
    )
    example_title2 <- "Result:"
    example_title3 <- "Estimating the Total with Simple Random Sampling and Finite Populations"
    
    example_result <- c(
      "",
      "The estimated sample size :",
      "The population size :",
      "Confidence level :",
      "The absolute precision :",
      "The estimated variance of the studied characteristic :"
      
    )
    result_numbers <- c("",39,500, 95, 5000, 1000)
    
    table_html <- tags$table(
      lapply(seq_along(example_result), function(i) {
        result_html <- HTML(example_result[i])
        text_html <- HTML(result_numbers[i])
        tags$tr(
          tags$td(result_html, style = "padding-right: 20px;"),
          tags$td(text_html)
        )
      })
    )
    
    blanco<- " "
    example_html <- tags$div(
      title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
      tags$p(HTML(blanco)),
      tags$p(HTML(example_description)),
      tags$p(HTML(blanco)),
      tags$p(HTML(blanco)),
      tags$div(class = "custom-title-bold",example_title2),
      tags$p(HTML(blanco)),
      tags$div(class = "custom-title-bold",example_title3),
      tags$p(HTML(blanco)),
      table_html,
      tags$p(HTML(blanco)),
      tags$p(HTML(descriptionT3))
    )
    
    return(example_html)
  })
  
  #########################################################################
  ############################################### Start stratified sampling
  #########################################################################
  ############################################### Start estimating the mean
  ########################################################################
  # Start capturing estrata data
  values <- reactiveValues(data = data.frame(
    Stratum = integer(0),
    StratumSize = numeric(0),
    EstimatedVariance = numeric(0),
    Costs = numeric(0),
    Cost = numeric(0),
    stringsAsFactors = FALSE,
    sample_size = NULL
  ))
  values_mean <- reactiveValues(data = data.frame())
  values_total <- reactiveValues(data = data.frame())
  
  observeEvent(input$submit, {
    if (nrow(values$data) < input$num_strata) {
      new_row <- data.frame(
        Stratum = nrow(values$data) + 1,
        StratumSize = input$stratum_size,
        EstimatedVariance = input$estimated_variance,
        Costs = ifelse(input$Type_A %in% c("Optimal Fixed Variance and Minimum Cost", "Optimal Minimum Variance and Fixed Cost"), input$costs, NA),
        stringsAsFactors = FALSE
      )
      values$data <- rbind(values$data, new_row)
      output$error_message <- renderText("")
      if (nrow(values$data) == input$num_strata) {
        if (sum(values$data$StratumSize) != input$population_sizeME) {
          output$error_message <- renderText("Error: The sum of the stratum sizes does not equal the total population size. The table has been cleared.")
          values$data <- data.frame(
            Stratum = integer(0),
            StratumSize = numeric(0),
            EstimatedVariance = numeric(0),
            Costs = numeric(0),
            stringsAsFactors = FALSE
          )
        } else {
          
          update_sample_size()
        }
      }
    } else {
      output$error_message <- renderText("Error: You cannot add more rows than the specified number of strata.")
    }
  })
  observeEvent(input$clear, {
    clear_data()
    output$error_message <- renderText("The information about the strata has been cleared.")
  })
  observeEvent(input$population_sizeME, {
    if (nrow(values_mean$data) > 0) {  # Verificar si ya se capturaron datos de estratos
      clear_data()  # Limpiar datos capturados para media
      output$error_message <- renderText("You must re-enter the information about the strata.")  # Mostrar el mensaje solo cuando ya hay datos
    } else {
      output$error_message <- renderText("")  # No mostrar mensaje si no hay datos capturados
    }
  })
  observeEvent(input$num_strata, {
    if (nrow(values_mean$data) > 0) {  # Igual para el nÃºmero de estratos
      clear_data()
      output$error_message <- renderText("You must re-enter the information about the strata.")
    } else {
      output$error_message <- renderText("")
    }
  })
  observeEvent(input$confidenceME, {
    if (nrow(values$data) == input$num_strata && sum(values$data$StratumSize) == input$population_sizeME) {
      update_sample_size()
    }
  })
  observeEvent(input$precisionME, {
    if (nrow(values$data) == input$num_strata && sum(values$data$StratumSize) == input$population_sizeME) {
      update_sample_size()
    }
  })
  observeEvent(input$Type_A, {
    if (nrow(values_mean$data) > 0) {  # Control para el tipo de asignaciÃ³n en media
      clear_data()
      output$error_message <- renderText("You must re-enter the information about the strata.")
    } else {
      output$error_message <- renderText("")
    }
  })
  observeEvent(input$Cost, {
    if (input$Type_A == "Optimal Minimum Variance and Fixed Cost" &&
        nrow(values$data) == input$num_strata && sum(values$data$StratumSize) == input$population_sizeME) {
      update_sample_size()
    }
  })
  observeEvent(input$Type_A, {
    if (input$Type_A == "Neyman Assignment" &&
        nrow(values$data) == input$num_strata &&
        sum(values$data$StratumSize) == input$population_sizeME) {
      update_sample_size()  # Recalcula el tamaÃ±o de muestra
      output$error_message <- renderText("")  # Limpia cualquier mensaje de error previo
    }
  })
  observeEvent(input$Type_A, {
    if (input$Type_A == "Proportional Assignment" &&
        nrow(values$data) == input$num_strata &&
        sum(values$data$StratumSize) == input$population_sizeME) {
      update_sample_size()  # Recalcula el tamaÃ±o de muestra
      output$error_message <- renderText("")  # Limpia cualquier mensaje de error previo
    }
  })
  observeEvent(input$Type_A, {
    if (input$Type_A == "Uniform Assignment" &&
        nrow(values$data) == input$num_strata &&
        sum(values$data$StratumSize) == input$population_sizeME) {
      update_sample_size()  # Recalcula el tamaÃ±o de muestra
      output$error_message <- renderText("")  # Limpia cualquier mensaje de error previo
    }
  })
  observeEvent(input$Type_A, {
    if (input$Type_A %in% c("Optimal Minimum Variance and Fixed Cost", "Optimal Fixed Variance and Minimum Cost")) {
      clear_data()  # Limpia los datos existentes de los estratos
      updateNumericInput(session, "stratum_size", value = 0)  # Restablece Stratum Size a 0
      updateNumericInput(session, "estimated_variance", value = 0)  # Restablece Estimated Variance a 0
      updateNumericInput(session, "costs", value = 0)  # Restablece Costs a 0
      # output$error_message <- renderText("You must re-enter the information about the strata, including the costs.")
    } else if (nrow(values_mean$data) > 0) {  # Control para otros tipos de asignaciÃ³n
      clear_data()
      output$error_message <- renderText("You must re-enter the information about the strata.")
    } else {
      output$error_message <- renderText("")
    }
  })
  update_sample_size <- function() {
    N <- input$population_sizeME
    k <- input$num_strata
    Ni <- values$data$StratumSize
    Si <- sqrt(values$data$EstimatedVariance)
    z_alpha_2 <- qnorm((1 + input$confidenceME / 100) / 2)
    e <- input$precisionME
    Ci<-values$data$Costs
    RCi <- sqrt(values$data$Costs)
    C <- input$Cost
    if (input$Type_A == "Uniform Assignment") {
      numerator <- sum(Ni^2 * Si^2)
      denominator <- ( N^2*e^2 / z_alpha_2^2) + sum(Ni * Si^2)
      n <- ceiling(k * numerator / denominator)
      values$sample_size <- n
    } else if (input$Type_A == "Proportional Assignment") {
      numerator <- N * sum(Ni * Si^2)
      denominator <- (N^2* e^2 / z_alpha_2^2) + sum(Ni * Si^2)
      n <- ceiling(numerator / denominator)
      values$sample_size <- n
    } else if (input$Type_A == "Neyman Assignment") {
      numerator <- (sum(Ni * Si))^2
      denominator <- (N^2* e^2 / z_alpha_2^2) + sum(Ni * Si^2)
      n <- ceiling(numerator / denominator)
      values$sample_size <- n
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      numerator <- sum(Ni * Si * RCi) * sum(Ni * Si / RCi)
      denominator <- (N^2*e^2 / z_alpha_2^2) + sum(Ni * Si^2)
      n <- ceiling(numerator / denominator)
      values$sample_size <- n
      
    } else {
      numerator <- C * sum(Ni * Si / RCi)
      denominator <- sum(Ni * Si * RCi)
      n <- ceiling(numerator / denominator)
      values$sample_size <- n
    }
  }
  clear_data <- function() {
    values$data <- data.frame(
      Stratum = integer(0),
      StratumSize = numeric(0),
      EstimatedVariance = numeric(0),
      Costs = numeric(0),
      stringsAsFactors = FALSE
    )
    values$sample_size <- NULL
  }
  output$sample_size <- renderText({
    if (!is.null(values$sample_size)) {
      paste("Sample size:", values$sample_size, "\nThe sample size obtained corresponds to the nearest upper integer.")
    }
  })
  output$table_data <- renderPrint({
    if (nrow(values$data) > 0) {
      
      cat("Information about the strata\n")
      if (input$Type_A %in% c("Optimal Fixed Variance and Minimum Cost", "Optimal Minimum Variance and Fixed Cost")) {
        print(values$data)
      } else {
        print(values$data[, -which(names(values$data) == "Costs")])
      }
      if (!is.null(values$sample_size)) {
        cat("\nSample Size:", values$sample_size, "\n")
        cat("\nSample Size of Strata:\n")
        if (input$Type_A == "Uniform Assignment") {
          print(data.frame(
            Stratum = values$data$Stratum,
            `Sample Size of Stratum` = ceiling(values$sample_size / input$num_strata)
          ))
        } else if (input$Type_A == "Proportional Assignment") {
          print(data.frame(
            Stratum = values$data$Stratum,
            `Sample Size of Stratum` = ceiling(values$sample_size * (values$data$StratumSize / input$population_sizeME))
          ))
        } else if (input$Type_A == "Neyman Assignment") {
          print(data.frame(
            Stratum = values$data$Stratum,
            `Sample Size of Stratum` = ceiling((values$sample_size * values$data$StratumSize * sqrt(values$data$EstimatedVariance)) / (sum(values$data$StratumSize * sqrt(values$data$EstimatedVariance))))
          ))
        } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
          print(data.frame(
            Stratum = values$data$Stratum,
            `Sample Size of Stratum` = ceiling((values$sample_size * (values$data$StratumSize * sqrt(values$data$EstimatedVariance) / sqrt(values$data$Costs)) / sum((values$data$StratumSize * sqrt(values$data$EstimatedVariance) / sqrt(values$data$Costs)))))
          ))
        }
        else {
          print(data.frame(
            Stratum = values$data$Stratum,
            `Sample Size of Stratum` = ceiling(values$sample_size * (values$data$StratumSize * sqrt(values$data$EstimatedVariance) / sqrt(values$data$Costs)) / sum((values$data$StratumSize * sqrt(values$data$EstimatedVariance) / sqrt(values$data$Costs))))
          ))
        }
        
        cat("\nThe sample size obtained for each stratum is the nearest upper integer\nof the calculated value. Therefore, the sum of the sample sizes for\n each stratum may differ from the total calculated sample size.")
      }
      if (input$Type_A != "Optimal Minimum Variance and Fixed Cost") {
        cat("\nPopulation Size:", input$population_sizeME, "\n")
        cat("Precision:", input$precisionME, "\n")
        cat("Confidence:", input$confidenceME, "\n")
      }else{
        cat("\nPopulation Size:", input$population_sizeME, "\n")
        cat("Total cost:", input$Cost, "\n")
      }
    }
  })
  output$plan_title <- renderText({
    if (input$Type_A == "Uniform Assignment") {
      "Stratified Sampling: Estimating the Mean with Uniform Assignment"
    } else if (input$Type_A == "Proportional Assignment") {
      "Stratified Sampling: Estimating the Mean with Proportional Assignment"
    } else if (input$Type_A == "Neyman Assignment") {
      "Stratified Sampling: Estimating the Mean with Neyman Assignment"
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      "Stratified Sampling: Estimating the Mean with Optimal Fixed Variance and Minimum Cost"
    } else {
      "Stratified Sampling: Estimating the Mean with Optimal Minimum Variance and Fixed Cost"
    }
  })
  output$equame <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type_A == "Uniform Assignment") {
      equations <- c("","$$n = \\frac{k  \\sum_{i=1}^{k} N_i^2 s_i^2}{\\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{n}{k}$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Uniform Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_A == "Proportional Assignment") {
      equations <- c("","$$n = \\frac{N \\sum_{i=1}^{k} N_i s_i^2}{\\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{N_i }{N} n$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Proportional Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_A == "Neyman Assignment") {
      equations <- c("","$$n = \\frac{(\\sum_{i=1}^{k} N_i s_i)^2}{\\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{N_i s_i}{ \\sum_{i=1}^{k} N_i s_i}n$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Neyman Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      equations <- c("","$$n =\\frac{\\sum_{i=1}^{k} N_i s_i \\sqrt{C_i}\\sum_{i=1}^{k}\\frac{N_i s_i}{\\sqrt{C_i}}} { \\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{\\frac { N_i s_i}{\\sqrt{C_i} }}{\\sum_{i=1}^{k}\\frac { N_i s_i}{\\sqrt{C_i} }} n $$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Optimal Fixed Variance and Minimum Cost",
                      "Sample Size for stratum i")
    } else {
      equations <- c("","$$n =\\frac{ C \\sum_{i=1}^{k} \\frac{N_i s_i}{\\sqrt{C_i}}}{\\sum_{i=1}^{k}N_i s_i \\sqrt{C_i} } $$",
                     "$$n_i = \\frac{\\frac { N_i s_i}{\\sqrt{C_i} }}  {\\sum_{i=1}^{k} \\frac{N_i s_i}{\\sqrt{C_i} }} n $$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Optimal Minimum Variance and Fixed Cost",
                      "Sample Size for stratum i")
    }
    paragraphs2 <- c("Where:",
                     "is the total sample size.",
                     "is the sample size for stratum i.",
                     "is the population size.",
                     "is the total size of stratum i.",
                     "is the stratum number.",
                     "is the estimated variance of the characteristic of interest in the stratum i.",
                     "is the z-score corresponding to the desired confidence level.",
                     "is the maximum permissible absolute error (or desired absolute precision).")
    equations2 <- c("$$ $$",
                    "$$n$$",
                    "$$n_i$$",
                    "$$N$$",
                    "$$N_i$$",
                    "$$k$$",
                    "$$s_i^2$$",
                    "$$z_{(\\alpha/2)}$$",
                    "$$e$$")
    if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      paragraphs2 <-c(paragraphs2, "is the cost to obtain a unit from stratum i")
      equations2 <- c(equations2, "$$C_i$$")
    }
    if (input$Type_A == "Optimal Minimum Variance and Fixed Cost") {
      paragraphs2 <- c("Where:",
                       "is the total sample size.",
                       "is the sample size for stratum i.",
                       "is the total cost",
                       "is the cost to obtain a unit from stratum i",
                       "is the total size of stratum i.",
                       "is the estimated variance of the characteristic of interest in the stratum i.")
      equations2 <- c("$$ $$",
                      "$$n$$",
                      "$$n_i$$",
                      "$$C$$",
                      "$$C_i$$",
                      "$$N_i$$",
                      "$$s_i^2$$")
    }
    # Depending on the type of population, define the corresponding title
    if (input$Type_A == "Uniform Assignment") {
      title<- "Equation of Sample Size Calculation for Estimating the Mean using Uniform Assignment "
    } else if (input$Type_A == "Proportional Assignment") {
      title<-"Equation of Sample Size Calculation for Estimating the Mean using Proportional Assignment "
    } else if (input$Type_A == "Neyman Assignment") {
      title<- "Equation of Sample Size Calculation for Estimating the Mean using Neyman Assignment "
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      title<-"Equation of Sample Size Calculation for Estimating the Mean using Optimal Fixed Variance and Minimum Cost "
    } else {
      title<-"Equation of Sample Size Calculation for Estimating the Mean using Optimal Minimum Variance and Fixed Cost "
    }
    
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  output$informme <- renderUI({
    equations <- c(
      "",
      "$$\\bar{y_i} = \\frac{1}{n_i} \\sum_{h=1}^{n_i} y_{ih}$$",
      "$$\\bar{y} = \\sum_{i=1}^{k}\\frac{N_i}{N} \\bar{y_i}$$",
      "$$\\hat{V}(\\bar{y}) = \\sum_{i=1}^{k} \\left(1-\\frac{n_i}{N_i}\\right) \\left(\\frac{N_i}{N}\\right)^2 \\frac{s_i^2}{n_i}$$")
    paragraphs <- c("",
                    "Estimator of the mean of stratum i",
                    "Estimator of the population mean",
                    "Estimator of the variance of the estimator of the population mean")
    paragraphs2 <- c("Where:",
                     "is the estimator of the mean of stratum i.",
                     "is the estimator of the population mean.",
                     "is the estimator of the variance of the estimator of the population mean.",
                     "is the sample size for stratum i.",
                     "is the population size.",
                     "is the total size of stratum i.",
                     "is the stratum number.",
                     "is the estimated variance of the characteristic of interest in the stratum i.")
    equations2 <- c("$$ $$",
                    "$$\\bar{y_i}$$",
                    "$$\\bar{y}$$",
                    "$$\\hat{V}(\\bar{y})$$",
                    "$$n_i$$",
                    "$$N$$",
                    "$$N_i$$",
                    "$$k$$",
                    "$$s_i^2$$")
    if (input$Type_A == "Uniform Assignment") {
      title <- "Stratified Random Sampling for Estmating the Mean with Uniform Allocation"
    } else if (input$Type_A == "Proportional Assignment") {
      title <- "Stratified Random Sampling for Estmating the Mean with Proportional Allocation"
    } else if (input$Type_A == "Neyman Assignment") {
      title <- "Stratified Random Sampling for Estmating the Mean with Neyman Allocation"
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      title <- "Stratified Random Sampling for Estmating the Mean with Optimal Fixed Variance and Minimum Cost"
    } else {
      title <- "Stratified Random Sampling for Estmating the Mean with Optimal Minimum Variance and Fixed Cost"
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  output$plan_title <- renderText({
    if (input$Type_A == "Uniform Assignment") {
      "Stratified Sampling: Estimating the Mean with Uniform Assignment"
    } else if (input$Type_A == "Proportional Assignment") {
      "Stratified Sampling: Estimating the Mean with Proportional Assignment"
    } else if (input$Type_A == "Neyman Assignment") {
      "Stratified Sampling: Estimating the Mean with Neyman Assignment"
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      "Stratified Sampling: Estimating the Mean with Optimal Fixed Variance and Minimum Cost"
    } else {
      "Stratified Sampling: Estimating the Mean with Optimal Minimum Variance and Fixed Cost"
    }
  })
  output$plan_title_t <- renderText({
    if (input$Type_C == "Uniform Assignment") {
      "Stratified Sampling: Estimating the Total with Uniform Assignment"
    } else if (input$Type_C == "Proportional Assignment") {
      "Stratified Sampling: Estimating the Total with Proportional Assignment"
    } else if (input$Type_C == "Neyman Assignment") {
      "Stratified Sampling: Estimating the Total with Neyman Assignment"
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      "Stratified Sampling: Estimating the Total with Optimal Fixed Variance and Minimum Cost"
    } else {
      "Stratified Sampling: Estimating the Total with Optimal Minimum Variance and Fixed Cost"
    }
  })
  output$exampleme <- renderUI({
    # Define el contenido del ejemplo
    { if (input$Type_A == "Uniform Assignment") {
      example_title <- "Example of estimating the mean using uniform allocation within strata."
    }else if (input$Type_A == "Proportional Assignment") {
      example_title <- "Example of estimating the mean using proportional allocation within strata."
    } else if (input$Type_A == "Neyman Assignment") {
      example_title <- "Example of estimating the mean using Neyman allocation within strata."  
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      example_title <- "Example of estimating the mean using the optimal fixed variance and minimum cost allocation within strata." 
    } else {
      example_title <- "Example of estimating the mean using optimal allocation for minimum variance and fixed cost within strata."
    }}
    example_html <- NULL
    
    example_description <- paste(
      "A livestock development program is to be initiated in a certain region of the country.",
      "Due to the limited information available about the region, it was deemed necessary to estimate",
      "the average size in hectares of the ranches in question."
    )
    example_description2 <- paste(
      "To this end, the population was divided into four strata, which presented the following quantities",
      "of ranches: 198, 96, 96, and 93, respectively."
    )
    
    if (input$Type_A == "Uniform Assignment") {
      example_description3 <- paste(
        "What should be the sample size to estimate the stratified mean with a precision of plus or minus 3",
        "hectares and a 95% confidence level? A uniform allocation within the strata is desired. From a preliminary",
        "survey, the following information about the variances was obtained:"
      )
    } else if (input$Type_A == "Proportional Assignment") {
      example_description3 <- paste(
        "What should be the sample size to estimate the stratified mean with a precision of plus or minus 3",
        "hectares and a 95% confidence level? A proportional allocation within the strata is desired. From a preliminary",
        "survey, the following information about the variances was obtained:"
      )
    } else if (input$Type_A == "Neyman Assignment") {
      example_description3 <- paste(
        "What should be the sample size to estimate the stratified mean with a precision of plus or minus 3",
        "hectares and a 95% confidence level? A Neyman allocation within the strata is desired. From a preliminary",
        "survey, the following information about the variances was obtained:"
      )
    } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
      example_description3 <- paste(
        "What should be the sample size to estimate the stratified mean with a precision of plus or minus 3",
        "hectares and a 95% confidence level? An optimal fixed variance and minimum cost is desired. From a preliminary",
        "survey, the following information about the variances and the cost was obtained:"
      )
    } else {
      example_description3 <- paste(
        "What should the sample size be to estimate the stratified mean if an optimal minimum variance ",
        "and fixed-cost allocation is desired? The total budget allocated for the sampling ",
        "study is $5,000.00, and from a preliminary survey, the following information about variances",
        "and costs was obtained:"
      )
    }
    if (input$Type_A %in% c("Uniform Assignment", "Proportional Assignment",
                            "Neyman Assignment")) {
      example_table <- tags$table(
        style = "width: 70%; border-collapse: collapse; text-align: center;",
        tags$thead(
          tags$tr(
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum"),
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum Size"),
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Estimated Variance")
            
          )
        ),
        tags$tbody(
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "1"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "198"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "1.7")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "2"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "96"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "17.6")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "3"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "96"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "47.6")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "4"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "93"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "166.3")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "Total"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "483"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "")
          )
        )
      )
    }else {example_table <- tags$table(
      style = "width: 70%; border-collapse: collapse; text-align: center;",
      tags$thead(
        tags$tr(
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum Size"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Estimated Variance"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Costs per Unit")
          
        )
      ),
      tags$tbody(
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "1"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "198"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "1.7"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "135")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "2"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "96"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "17.6"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "163")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "3"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "96"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "47.6"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "180")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "4"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "93"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "166.3"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "191")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "Total"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "483"),
          tags$td(style = "border: 1px solid black; padding: 1px;", ""),
          tags$td(style = "border: 1px solid black; padding: 1px;", "")
        )
      )
    )}
    
    example_html <- tags$div(
      tags$h4(example_title,class = "custom-title-bold" ), #title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
      tags$p(HTML(example_description)),
      tags$p(HTML(example_description2)),
      tags$p(HTML(example_description3)),
      example_table,
      tags$h6(" . " ),
      tags$h4("  " ),
      tags$h4("  " ),
      tags$h4("Result:",class = "custom-title-bold"),
      
      if (input$Type_A == "Uniform Assignment") {
        tags$h4("Stratified Sampling: Estimating the Mean with Uniform Assignment",class = "custom-title-bold")
        
      } else if (input$Type_A == "Proportional Assignment") {
        tags$h4("Stratified Sampling: Estimating the Mean with Proportional Assignment")
      } else if (input$Type_A == "Neyman Assignment") {
        tags$h4("Stratified Sampling: Estimating the Mean with Neyman Assignment")
      } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
        tags$h4("Stratified Sampling: Estimating the Mean with Optimal Fixed Variance and Minimum Cost")
      } else {
        tags$h4("Stratified Sampling: Estimating the Mean with Optimal Minimum Variance and Fixed Cost")
      },
      if (input$Type_A == "Uniform Assignment") {
        tags$p(paste("Sample size:", 15))
        
      } else if (input$Type_A == "Proportional Assignment") {
        tags$p(paste("Sample size:", 19))
      } else if (input$Type_A == "Neyman Assignment") {
        tags$p(paste("Sample size:", 12))
      } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
        tags$p(paste("Sample size:", 12))
      } else {
        tags$p(paste("Sample size:", 29))
      },
      
      tags$p("The sample size obtained corresponds to the nearest upper integer."),
      tags$p("Information about the strata"),
      
      if (input$Type_A %in% c("Uniform Assignment", "Proportional Assignment",
                              "Neyman Assignment")) {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "StratumSize"),
              tags$th(style = "padding: 1px; text-align: center;", "EstimatedVariance")
              
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "198"),
              tags$td(style = "padding: 1px;", "1.7")
              
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "96"),
              tags$td(style = "padding: 1px;", "17.6")
              
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "96"),
              tags$td(style = "padding: 1px;", "47.6")
              
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "93"),
              tags$td(style = "padding: 1px;", "166.3")
              
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "Total"),
              tags$td(style = "padding: 1px;", "483"),
              tags$td(style = "padding: 1px;", "")
            )
          )
        )
      }else {example_table <- tags$table(
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "StratumSize"),
              tags$th(style = "padding: 1px; text-align: center;", "EstimatedVariance"),
              tags$th(style = "padding: 1px; text-align: center;", "Costs")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "198"),
              tags$td(style = "padding: 1px;", "1.7"),
              tags$td(style = "padding: 1px;", "135")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "96"),
              tags$td(style = "padding: 1px;", "17.6"),
              tags$td(style = "padding: 1px;", "163")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "96"),
              tags$td(style = "padding: 1px;", "47.6"),
              tags$td(style = "padding: 1px;", "180")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "93"),
              tags$td(style = "padding: 1px;", "166.3"),
              tags$td(style = "padding: 1px;", "191")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "Total"),
              tags$td(style = "padding: 1px;", "483"),
              tags$td(style = "padding: 1px;", ""),
              tags$td(style = "padding: 1px;", "")
            )
          )
        ))},
      
      
      
      if (input$Type_A == "Uniform Assignment") {
        tags$p(paste("Sample size:", 15))
        
      } else if (input$Type_A == "Proportional Assignment") {
        tags$p(paste("Sample size:", 19))
      } else if (input$Type_A == "Neyman Assignment") {
        tags$p(paste("Sample size:", 12))
      } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
        tags$p(paste("Sample size:", 15))
      } else {
        tags$p(paste("Sample size:", 29))
      },
      
      if (input$Type_A == "Uniform Assignment") {
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "4")
            )
          )
        )
        
      } else if (input$Type_A == "Proportional Assignment") {
        
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "8")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "4")
            )
          )
        )
      } else if (input$Type_A == "Neyman Assignment") {
        
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "2")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "2")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "6")
            )
          )
        )
      } else if (input$Type_A == "Optimal Fixed Variance and Minimum Cost") {
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "2")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "2")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "6")
            )
          )
        )
      } else {
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "4")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "5")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "8")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "4"),
              tags$td(style = "padding: 1px;", "14")
            )
          )
        )
        
      },
      tags$p("The sample size obtained for each stratum is the nearest upper integer of the calculated value. Therefore, the sum of the sample sizes for each stratum may differ from the total calculated sample size."),
      if (input$Type_A != "Optimal Minimum Variance and Fixed Cost") {
        list(
          tags$p(paste("Population Size:", 483)),
          tags$p(paste("Precision:", 3)),
          tags$p(paste("Confidence:", 95)),
          tags$p(style = "height: 50px;")  # Espacio adicional al final
        )
      }else{
        list(
          tags$p(paste("Population Size:", 483)),
          tags$p(paste("Total Cost:", 5000)),
          tags$p(style = "height: 50px;")  # Espacio adicional al final
        ) 
      }
      
      
    )
    
    return(example_html)
  })
  
  ################################################ Start estimating a proportion
  values_proportion <- reactiveValues(data = data.frame(
    Stratump = integer(0),
    StratumSizep = numeric(0),
    Estimatedproportion = numeric(0),
    Costsp = numeric(0),
    Costp = numeric(0),
    stringsAsFactors = FALSE,
    sample_sizep = NULL
  ))
  values_proportion <- reactiveValues(data = data.frame())
  observeEvent(input$submitp, {
    # Validar que la precisiÃ³n estÃ© entre 0 y 1
    if (is.null(input$precisionMEp) || input$precisionMEp > 1 || input$precisionMEp < 0) {
      output$error_message <- renderText("Error: The precision value must be between 0 and 1. Please adjust the precision before capturing the information.")
      return()  # Detener la ejecuciÃ³n si la precisiÃ³n no es vÃ¡lida
    }
    
    # Validar que la proporciÃ³n estimada estÃ© entre 0 y 1
    if (is.null(input$estimated_proportion) || input$estimated_proportion > 1 || input$estimated_proportion < 0) {
      output$error_message <- renderText("Error: The estimated proportion must be between 0 and 1 (inclusive).")
      return()  # Detener la ejecuciÃ³n si la proporciÃ³n estimada no es vÃ¡lida
    }
    
    # CÃ³digo para agregar un nuevo estrato si la precisiÃ³n y la proporciÃ³n son vÃ¡lidas
    if (nrow(values_proportion$data) < input$num_stratap) {
      new_row <- data.frame(
        Stratump = nrow(values_proportion$data) + 1,
        StratumSizep = input$stratum_sizep,
        Estimatedproportion = input$estimated_proportion,
        Costsp = ifelse(input$Type_B %in% c("Optimal Fixed Variance and Minimum Cost", "Optimal Minimum Variance and Fixed Cost"), input$costsp, NA),
        stringsAsFactors = FALSE
      )
      values_proportion$data <- rbind(values_proportion$data, new_row)
      output$error_message <- renderText("")
      if (nrow(values_proportion$data) == input$num_stratap) {
        if (sum(values_proportion$data$StratumSizep) != input$population_sizeMEp) {
          output$error_message <- renderText("Error: The sum of the stratum sizes does not equal the total population size. The table has been cleared.")
          values_proportion$data <- data.frame(
            Stratump = integer(0),
            StratumSizep = numeric(0),
            Estimatedproportion = numeric(0),
            Costsp = numeric(0),
            stringsAsFactors = FALSE
          )
        } else {
          
          update_sample_sizep()
        }
      }
    } else {
      output$error_message <- renderText("Error: You cannot add more rows than the specified number of strata.")
    }
  })
  observeEvent(input$clearp, {
    clear_datap()
    output$error_message <- renderText("The information about the strata has been cleared.")
  })
  observeEvent(input$population_sizeMEp, {
    if (nrow(values_proportion$data) > 0) {  # Verificar si ya se capturaron datos de estratos
      clear_datap()  # Limpiar datos capturados para proporciÃ³n
      output$error_message <- renderText("You must re-enter the information about the strata.")  # Mostrar el mensaje solo cuando ya hay datos
    } else {
      output$error_message <- renderText("")  # No mostrar mensaje si no hay datos capturados
    }
  })
  observeEvent(input$num_stratap, {
    if (nrow(values_proportion$data) > 0) {  # Igual para el nÃºmero de estratos en proporciÃ³n
      clear_datap()
      output$error_message <- renderText("You must re-enter the information about the strata.")
    } else {
      output$error_message <- renderText("")
    }
  })
  observeEvent(input$confidenceMEp, {
    if (nrow(values_proportion$data) == input$num_stratap && sum(values_proportion$data$StratumSizep) == input$population_sizeMEp) {
      update_sample_sizep()
    }
  })
  observeEvent(input$precisionMEp, {
    if (nrow(values_proportion$data) == input$num_stratap && sum(values_proportion$data$StratumSizep) == input$population_sizeMEp) {
      update_sample_sizep()
    }
  })
  observeEvent(input$Type_B, {
    output$error_message <- renderText("")
    # Si el tipo es "Optimal Minimum Variance and Fixed Cost" o "Optimal Fixed Variance and Minimum Cost"
    if (input$Type_B %in% c("Optimal Minimum Variance and Fixed Cost", "Optimal Fixed Variance and Minimum Cost")) {
      clear_datap()  # Limpia los datos existentes de los estratos
      updateNumericInput(session, "stratum_sizep", value = 0)  # Restablece Stratum Size a 0
      updateNumericInput(session, "estimated_proportion", value = 0)  # Restablece Estimated Proportion a 0
      updateNumericInput(session, "costsp", value = 0)  # Restablece Costs a 0
      output$error_message <- renderText("The strata information has been cleared.")
      # output$error_message <- renderText("Please re-enter the information, including the costs.")
    }
    
    else if (input$Type_B %in% c("Uniform Assignment", "Proportional Assignment", "Neyman Assignment")) {
      if (nrow(values_proportion$data) == input$num_stratap && sum(values_proportion$data$StratumSizep) == input$population_sizeMEp) {
        update_sample_sizep()  # Recalcula el tamaÃ±o de muestra
        output$error_message <- renderText("")  
      } 
    }
  })
  observeEvent(input$Costp, {
    if (input$Type_B == "Optimal Minimum Variance and Fixed Cost" &&
        nrow(values_proportion$data) == input$num_stratap && sum(values_proportion$data$StratumSizep) == input$population_sizeMEp) {
      update_sample_sizep()
    }
  })
  update_sample_sizep <- function() {
    N <- input$population_sizeMEp
    k <- input$num_stratap
    Ni <- values_proportion$data$StratumSizep
    pi <- values_proportion$data$Estimatedproportion
    z_alpha_2 <- qnorm((1 + input$confidenceMEp / 100) / 2)
    e <- input$precisionMEp
    Ci <- values_proportion$data$Costsp
    RCi <- sqrt(values_proportion$data$Costsp)
    C <- input$Costp
    if (input$Type_B == "Uniform Assignment") {
      numerator <- sum(Ni^2 * pi * (1 - pi)*(Ni/(Ni-1)))
      denominator <- (N*N* e^2 / z_alpha_2^2) + sum(Ni * pi * (1 - pi)*(Ni/(Ni-1)))
      n <- ceiling(k * numerator / denominator)
      values_proportion$sample_sizep <- n
    } else if (input$Type_B == "Proportional Assignment") {
      numerator <- N * sum(Ni * pi * (1 - pi)*(Ni/(Ni-1)))
      denominator <- (N^2 * e^2 / z_alpha_2^2) + sum(Ni * pi * (1 - pi)*(Ni/(Ni-1)))
      n <- ceiling(numerator / denominator)
      values_proportion$sample_sizep <- n
    } else if (input$Type_B == "Neyman Assignment") {
      numerator <- (sum(Ni * sqrt(pi * (1 - pi)*(Ni/(Ni-1)))))^2
      denominator <- (N^2 * e^2 / z_alpha_2^2) + sum(Ni * pi * (1 - pi)*(Ni/(Ni-1)))
      n <- ceiling(numerator / denominator)
      values_proportion$sample_sizep <- n
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      numerator <- sum(Ni * sqrt(pi * (1 - pi)*(Ni/(Ni-1))) * RCi) * sum(Ni * sqrt(pi * (1 - pi)*(Ni/(Ni-1))) / RCi)
      denominator <- (N^2 * e^2 / z_alpha_2^2) + sum(Ni * pi * (1 - pi)*(Ni/(Ni-1)))
      n <- ceiling(numerator / denominator)
      values_proportion$sample_sizep <- n
    } else {
      numerator <- C * sum(Ni * sqrt(pi * (1 - pi)*(Ni/(Ni-1))) / RCi)
      denominator <- sum(Ni * sqrt(pi * (1 - pi)*(Ni/(Ni-1))) * RCi)
      n <- ceiling(numerator / denominator)
      values_proportion$sample_sizep <- n
    }
  }
  clear_datap <- function() {
    values_proportion$data <- data.frame(
      Stratump = integer(0),
      StratumSizep = numeric(0),
      Estimatedproportion = numeric(0),
      Costsp = numeric(0),
      stringsAsFactors = FALSE
    )
    values_proportion$sample_sizep <- NULL
  }
  output$sample_sizep <- renderText({
    if (!is.null(values_proportion$sample_sizep)) {
      paste("Sample size:", values_proportion$sample_sizep, "\nThe sample size obtained corresponds to the nearest upper integer.")
    }
  })
  output$table_datap <- renderPrint({
    if (nrow(values_proportion$data) > 0) {
      
      cat("Information about the strata\n")
      if (input$Type_B %in% c("Optimal Fixed Variance and Minimum Cost", "Optimal Minimum Variance and Fixed Cost")) {
        print(values_proportion$data)
      } else {
        print(values_proportion$data[, -which(names(values_proportion$data) == "Costsp")])
      }
      if (!is.null(values_proportion$sample_sizep)) {
        cat("\nSample Size:", values_proportion$sample_sizep, "\n")
        cat("\nSample Size of Strata:\n")
        if (input$Type_B == "Uniform Assignment") {
          print(data.frame(
            Stratum = values_proportion$data$Stratump,
            `Sample Size of Stratum` = ceiling(values_proportion$sample_sizep / input$num_stratap)
          ))
        } else if (input$Type_B == "Proportional Assignment") {
          print(data.frame(
            Stratum = values_proportion$data$Stratump,
            `Sample Size of Stratum` = ceiling(values_proportion$sample_sizep * (values_proportion$data$StratumSizep / input$population_sizeMEp))
          ))
        } else if (input$Type_B == "Neyman Assignment") {
          print(data.frame(
            Stratum = values_proportion$data$Stratump,
            `Sample Size of Stratum` = ceiling((values_proportion$sample_sizep * values_proportion$data$StratumSizep * sqrt(values_proportion$data$Estimatedproportion*(1-values_proportion$data$Estimatedproportion))) / (sum(values_proportion$data$StratumSizep * sqrt(values_proportion$data$Estimatedproportion*(1-values_proportion$data$Estimatedproportion)))))
          ))
        } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
          print(data.frame(
            Stratum = values_proportion$data$Stratump,
            `Sample Size of Stratum` = ceiling((values_proportion$sample_sizep * (values_proportion$data$StratumSizep * sqrt(values_proportion$data$Estimatedproportion*(1-values_proportion$data$Estimatedproportion)) / sqrt(values_proportion$data$Costsp)) / sum((values_proportion$data$StratumSizep * sqrt(values_proportion$data$Estimatedproportion*(1-values_proportion$data$Estimatedproportion)) / sqrt(values_proportion$data$Costsp)))))
          ))
        } else {
          print(data.frame(
            Stratum = values_proportion$data$Stratump,
            `Sample Size of Stratum` = ceiling(values_proportion$sample_sizep * (values_proportion$data$StratumSizep * sqrt(values_proportion$data$Estimatedproportion*(1-values_proportion$data$Estimatedproportion)) / sqrt(values_proportion$data$Costsp)) / sum((values_proportion$data$StratumSizep * sqrt(values_proportion$data$Estimatedproportion*(1-values_proportion$data$Estimatedproportion)) / sqrt(values_proportion$data$Costsp))))
          ))
        }
        
        cat("\nThe sample size obtained for each stratum is the nearest upper integer\nof the calculated value. Therefore, the sum of the sample sizes for\n each stratum may differ from the total calculated sample size.")
      }
      if (input$Type_B != "Optimal Minimum Variance and Fixed Cost") {
        cat("\nPopulation Size:", input$population_sizeMEp, "\n")
        cat("Precision:", input$precisionMEp, "\n")
        cat("Confidence:", input$confidenceMEp, "\n")
      }else{
        cat("\nPopulation Size:", input$population_sizeMEp, "\n")
        cat("Total cost:", input$Costp, "\n")
      }
    }
  })
  output$plan_title_p <- renderText({
    if (input$Type_B == "Uniform Assignment") {
      "Stratified Sampling: Estimating a Proportion with Uniform Assignment"
    } else if (input$Type_B == "Proportional Assignment") {
      "Stratified Sampling: Estimating a Proportion with Proportional Assignment"
    } else if (input$Type_B == "Neyman Assignment") {
      "Stratified Sampling: Estimating a Proportion with Neyman Assignment"
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      "Stratified Sampling: Estimating a Proportion with Optimal Fixed Variance and Minimum Cost"
    } else {
      "Stratified Sampling: Estimating a Proportion with Optimal Minimum Variance and Fixed Cost"
    }
  })
  output$equamep <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type_B == "Uniform Assignment") {
      equations <- c("","$$n = \\frac{k \\sum_{i=1}^{k} N_i^2   p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}{\\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}$$",
                     "$$n_i = \\frac{n}{k}$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Uniform Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_B == "Proportional Assignment") {
      equations <- c("","$$n = \\frac{N \\sum_{i=1}^{k} N_i p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}{\\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}$$",
                     "$$n_i = \\frac{N_i n}{N}$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Proportional Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_B == "Neyman Assignment") {
      equations <- c("","$$n = \\frac{\\sum_{i=1}^{k} N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}}{\\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}$$",
                     "$$n_i = \\frac{N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)} }{ \\sum_{i=1}^{k} N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}}n$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Neyman Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      equations <- c("","$$n =\\frac{\\sum_{i=1}^{k} N_i C_i\\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)} \\sum_{i=1}^{k}\\frac{N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)} }{\\sqrt{C_i}}} { \\frac{N^2 e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right) }$$",
                     "$$n_i = \\frac{\\frac { N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right) }}{\\sqrt{C_i} }}{\\sum_{i=1}^{k} \\left( \\frac { N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}}{\\sqrt{C_i} }\\right)} n $$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Optimal Fixed Variance and Minimum Cost",
                      "Sample Size for stratum i")
    } else {
      equations <- c("","$$n =\\frac{ C \\sum_{i=1}^{k} \\frac{N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}}{\\sqrt{C_i}}}{\\sum_{i=1}^{k} N_i  C_i\\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right) }} $$",
                     "$$n_i = \\frac{\\frac { N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}}{\\sqrt{C_i}} } {\\sum_{i=1}^{k} \\frac{N_i \\sqrt{p_i \\left ( 1-p_i \\right ) \\left( \\frac{N_i}{N_i-1} \\right)}}{\\sqrt{C_i} }}n $$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Optimal Minimum Variance and Fixed Cost",
                      "Sample Size for stratum i")
    }
    paragraphs2 <- c("Where:",
                     "is the total sample size.",
                     "is the sample size for stratum i.",
                     "is the population size.",
                     "is the total size of stratum i.",
                     "is the stratum number.",
                     "is the estimated proportion of the characteristic of interest in the stratum i.",
                     "is the z-score corresponding to the desired confidence level.",
                     "is the maximum permissible absolute error (or desired absolute precision).")
    equations2 <- c("$$ $$",
                    "$$n$$",
                    "$$n_i$$",
                    "$$N$$",
                    "$$N_i$$",
                    "$$k$$",
                    "$$p_i$$",
                    "$$z_{(\\alpha/2)}$$",
                    "$$e$$")
    if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      paragraphs2 <- c(paragraphs2, "is the cost to obtain a unit from stratum i")
      equations2 <- c(equations2, "$$C_i$$")
    }
    if (input$Type_B == "Optimal Minimum Variance and Fixed Cost") {
      paragraphs2 <- c("Where:",
                       "is the total sample size.",
                       "is the sample size for stratum i.",
                       "is the total cost",
                       "is the cost to obtain a unit from stratum i",
                       "is the total size of stratum i.",
                       "is the estimated proportion of the characteristic of interest in the stratum i.")
      equations2 <- c("$$ $$",
                      "$$n$$",
                      "$$n_i$$",
                      "$$C$$",
                      "$$C_i$$",
                      "$$N_i$$",
                      "$$p_i$$")
    }
    # Depending on the type of population, define the corresponding title
    if (input$Type_B == "Uniform Assignment") {
      title<- "Equation of Sample Size Calculation for Estimating a Proportion using Uniform Assignment "
    } else if (input$Type_B == "Proportional Assignment") {
      title<-"Equation of Sample Size Calculation for Estimating a Proportion using Proportional Assignment "
    } else if (input$Type_B == "Neyman Assignment") {
      title<- "Equation of Sample Size Calculation for Estimating a Proportion using Neyman Assignment "
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      title<-"Equation of Sample Size Calculation for Estimating a Proportion using Optimal Fixed Variance and Minimum Cost "
    } else {
      title<-"Equation of Sample Size Calculation for Estimating a Proportion using Optimal Minimum Variance and Fixed Cost "
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  output$informmep <- renderUI({
    equations <- c(
      "",
      "$$\\hat{p_i} = \\frac{1}{n_i} \\sum_{h=1}^{n_i} y_{ih}$$",
      "$$ y_{ih} =
            \\begin{cases}
            1 & \\text{If the characteristic of interest is present} \\\\
            0 & \\text{If the characteristic of interest is not present}
           \\end{cases}
           $$",
      "$$\\hat{p} = \\sum_{j=1}^{k}\\frac{N_i}{N} \\hat{p_i}$$",
      "$$\\hat{V}(\\hat{p}) = \\sum_{j=1}^{k} \\left (1-\\frac{n_i}{N_i}\\right) \\left(\\frac{N_i}{N}\\right)^2 \\frac{\\hat{p}(1-\\hat{p})}{(n_i -1)}$$")
    paragraphs <- c("",
                    "Estimator of the proportion of stratum i",
                    "Where: ",
                    "Estimator of the population proportion",
                    "Estimator of the variance of the estimator of the population proportion")
    paragraphs2 <- c("Where:",
                     "is the estimator of the proportion of stratum i.",
                     "is the estimator of the population proportion.",
                     "is the estimator of the variance of the estimator of the population proportion.",
                     "is the sample size for stratum i.",
                     "is the population size.",
                     "is the total size of stratum i.",
                     "is the stratum number.",
                     "is the estimated proportion of the characteristic of interest in the stratum i.")
    equations2 <- c("$$ $$",
                    "$$\\hat{p_i}$$",
                    "$$\\hat{p}$$",
                    "$$\\hat{V}(\\hat{p})$$",
                    "$$n_i$$",
                    "$$N$$",
                    "$$N_i$$",
                    "$$k$$",
                    "$$p$$")
    if (input$Type_B == "Uniform Assignment") {
      title <- "Stratified Random Sampling with Uniform Allocation"
    } else if (input$Type_B == "Proportional Assignment") {
      title <- "Stratified Random Sampling with Proportional Allocation"
    } else if (input$Type_B == "Neyman Assignment") {
      title <- "Stratified Random Sampling with Neyman Allocation"
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      title <- "Stratified Random Sampling with Optimal Fixed Variance and Minimum Cost"
    } else {
      title <- "Stratified Random Sampling with Optimal Minimum Variance and Fixed Cost"
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  output$examplemep <- renderUI({
    # Define el contenido del ejemplo
    if (input$Type_B == "Uniform Assignment") {
      example_title <- "Example of estimating a proportion using uniform allocation within the strata"
    }else if (input$Type_B == "Proportional Assignment") {
      example_title <- "Example of estimating a proportion using proportional allocation within the strata"
    } else if (input$Type_B == "Neyman Assignment") {
      example_title <- "Example of estimating a proportion using Neyman allocation within the strata"  
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      example_title <- "Example of estimating a proportion using optimal fixed variance and minimum cost allocation within the strata" 
    } else {
      example_title <- "Example of estimating a proportion using optimal minimum variance and fixed cost allocation within the strata"
    }
    example_html <- NULL
    
    example_description <- paste(
      "We want to estimate the proportion of students who are satisfied with the cafeteria services",
      "at a university. The university is divided into three faculties (strata): Sciences, Humanities,",
      "and Engineering. The faculties have a total population of 500, 1200, and 700, respectively."
    )
    example_description2 <- paste(
      "From a preliminary survey, the following information about the strata was obtained:"
      
    )
    
    # DeterminaciÃ³n del texto segÃºn el tipo de asignaciÃ³n
    if (input$Type_B == "Uniform Assignment") {
      example_description3 <- paste(
        "If a uniform allocation is desired, what is the required sample size to achieve a 95% ",
        "confidence level and a precision of 0.04?"
      )
    } else if (input$Type_B == "Proportional Assignment") {
      example_description3 <- paste(
        "If a proportional allocation is desired, what is the required sample size to achieve a 95% ",
        "confidence level and a precision of 0.04?"
      )
    } else if (input$Type_B == "Neyman Assignment") {
      example_description3 <- paste(
        "If a Neyman allocation is desired, what is the required sample size to achieve a 95% ",
        "confidence level and a precision of 0.04?"
      )
    } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
      example_description3 <- paste(
        "If an optimal fixed variance and minimum cost is desired,what is the required sample",
        "size to achieve a 95% confidence level and a precision of 0.04?"
      )
    } else {
      example_description3 <- paste(
              "What should the sample size be to estimate a proportion if an optimal minimum-variance",
        "and fixed-cost allocation is desired? The total budget allocated for the sampling study is $80,000.00"
      )
    }
    
    if (input$Type_B %in% c("Uniform Assignment", "Proportional Assignment",
                            "Neyman Assignment")) {
      example_table <- tags$table(
        style = "width: 70%; border-collapse: collapse; text-align: center;",
        tags$thead(
          tags$tr(
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum"),
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratump Size"),
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Estimated Proportion")
            )
        ),
        tags$tbody(
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "1"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "500"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "0.8")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "2"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "1200"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "0.5")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "3"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "700"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "0.7")
          ),
          
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "Total"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "2400"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "")
          )
        )
      )
    }else {example_table <- tags$table(
      style = "width: 70%; border-collapse: collapse; text-align: center;",
      tags$thead(
        tags$tr(
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum Size"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Estimated Proportion"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Costs per Unit")
          
        )
      ),
      tags$tbody(
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "1"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "500"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "0.8"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "135")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "2"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "1200"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "0.5"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "163")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "3"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "700"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "0.7"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "180")
        ),
        
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "Total"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "2400"),
          tags$td(style = "border: 1px solid black; padding: 1px;", ""),
          tags$td(style = "border: 1px solid black; padding: 1px;", "")
        )
      )
    )}
    
    
    example_html <- tags$div(
      tags$h4(example_title,class = "custom-title-bold" ),
      tags$p(HTML(example_description)),
      tags$p(HTML(example_description2)),
      example_table,
      tags$p(HTML(example_description3)),
      tags$p(" ."),
      tags$h4("Result:",class = "custom-title-bold"),
      tags$h4(
        switch(input$Type_B,
               "Uniform Assignment" = "Stratified Sampling: Estimating the Proportion with Uniform Assignment",
               "Proportional Assignment" = "Stratified Sampling: Estimating the Proportion with Proportional Assignment",
               "Neyman Assignment" = "Stratified Sampling: Estimating the Proportion with Neyman Assignment",
               "Optimal Fixed Variance and Minimum Cost" = "Stratified Sampling: Estimating the Proportion with Optimal Fixed Variance and Minimum Cost",
               "Stratified Sampling: Estimating the Proportion with Optimal Minimum Variance and Fixed Cost"
        ),class = "custom-title-bold"
      ),
      
      tags$p(
        switch(input$Type_B,
               "Uniform Assignment" = "Sample size: 517",
               "Proportional Assignment" = "Sample size: 433",
               "Neyman Assignment" = "Sample size: 430",
               "Optimal Fixed Variance and Minimum Cost" = "Sample size: 431",
               "Sample size: 494"
        )),
      
      tags$p("The sample size obtained corresponds to the nearest upper integer."),
      tags$p("Information about the strata"),
     
       if (input$Type_B %in% c("Uniform Assignment", "Proportional Assignment",
                              "Neyman Assignment")) {
      
      tags$table(
        style = "width: 80%; border-collapse: collapse; text-align: center; border: none;",
        tags$thead(
          tags$tr(
            tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
            tags$th(style = "padding: 1px; text-align: center;", "StratumSize"),
            tags$th(style = "padding: 1px; text-align: center;", "EstimatedProportion")
          )
        ),
        tags$tbody(
          tags$tr(
            tags$td(style = "padding: 1px;", "1"),
            tags$td(style = "padding: 1px;", "500"),
            tags$td(style = "padding: 1px;", "0.8")
          ),
          tags$tr(
            tags$td(style = "padding: 1px;", "2"),
            tags$td(style = "padding: 1px;", "1200"),
            tags$td(style = "padding: 1px;", "0.5")
          ),
          tags$tr(
            tags$td(style = "padding: 1px;", "3"),
            tags$td(style = "padding: 1px;", "700"),
            tags$td(style = "padding: 1px;", "0.7")
          ),
          tags$tr(
            tags$td(style = "padding: 1px;", "Total"),
            tags$td(style = "padding: 1px;", "2400"),
            tags$td(style = "padding: 1px;", "")
          )
        )
      )
         }else 
           {
             tags$table(
               style = "width: 80%; border-collapse: collapse; text-align: center; border: none;",
               tags$thead(
                 tags$tr(
                   tags$th(style = "padding: 1px; text-align: center;", "Stratump"),
                   tags$th(style = "padding: 1px; text-align: center;", "StratumSizep"),
                   tags$th(style = "padding: 1px; text-align: center;", "EstimatedProportionp"),
                   tags$th(style = "padding: 1px; text-align: center;", "Costp"),
                 )
               ),
               tags$tbody(
                 tags$tr(
                   tags$td(style = "padding: 1px;", "1"),
                   tags$td(style = "padding: 1px;", "500"),
                   tags$td(style = "padding: 1px;", "0.8"),
                   tags$td(style = "padding: 1px;", "135")
                 ),
                 tags$tr(
                   tags$td(style = "padding: 1px;", "2"),
                   tags$td(style = "padding: 1px;", "1200"),
                   tags$td(style = "padding: 1px;", "0.5"),
                   tags$td(style = "padding: 1px;", "163")
                 ),
                 tags$tr(
                   tags$td(style = "padding: 1px;", "3"),
                   tags$td(style = "padding: 1px;", "700"),
                   tags$td(style = "padding: 1px;", "0.7"),
                   tags$td(style = "padding: 1px;", "180")
                 ),
                 tags$tr(
                   tags$td(style = "padding: 1px;", "Total"),
                   tags$td(style = "padding: 1px;", "2400"),
                   tags$td(style = "padding: 1px;", "")
                 ),
                 
               )
             )
             
           },
      tags$p(
        switch(input$Type_B,
               "Uniform Assignment" = "Sample size: 517",
               "Proportional Assignment" = "Sample size: 433",
               "Neyman Assignment" = "Sample size: 430",
               "Optimal Fixed Variance and Minimum Cost" = "Sample size: 431",
               "Sample size: 494"
        )),
      tags$p("Sample Size of Strata:"),
      if (input$Type_B == "Uniform Assignment") {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "173")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "173")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "173")
            )
          )
        )
      } else if (input$Type_B == "Proportional Assignment") {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "91")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "217")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "127")
            )
          )
        )   
      } else if (input$Type_B == "Neyman Assignment") {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "77")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "231")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "124")
            )
          )
        ) 
      } else if (input$Type_B == "Optimal Fixed Variance and Minimum Cost") {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "85")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "230")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "117")
            )
          )
        )
      }else {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "97")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "264")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "135")
            )
          )
        )}
      ,
      tags$p("The sample size obtained for each stratum is the nearest upper integer of the calculated value. Therefore, the sum of the sample sizes for each stratum may differ from the total calculated sample size."),
      if (input$Type_B != "Optimal Minimum Variance and Fixed Cost") {
        list(
          
          tags$p(paste("Population Size:", 2400)),
          tags$p(paste("Precision:", 0.04)),
          tags$p(paste("Confidence:", 95)),
          tags$p(style = "height: 50px;")  # Espacio adicional al final
        )
      }else{
        list(
          tags$p(paste("Population Size:", 2400)),
          tags$p(paste("Total Cost:", 80000)),
          tags$p(style = "height: 50px;")  # Espacio adicional al final
        ) 
      }
      
      
    )
    
    return(example_html)
  })
  
  ###########################################################################
  ################################################ Start estimating the total
  ##########################################################################
  
  # Start capturing estrata data
  values_total <- reactiveValues(data = data.frame(
    Stratum = integer(0),
    StratumSize = numeric(0),
    EstimatedVariance = numeric(0),
    Costs = numeric(0),
    Cost = numeric(0),
    stringsAsFactors = FALSE,
    sample_size = NULL
  ))
  
  observeEvent(input$submitt, {
    if (nrow(values_total$data) < input$num_stratat) {
      new_row <- data.frame(
        Stratum = nrow(values_total$data) + 1,
        StratumSize = input$stratum_sizet,
        EstimatedVariance = input$estimated_variancet,
        Costs = ifelse(input$Type_C %in% c("Optimal Fixed Variance and Minimum Cost", "Optimal Minimum Variance and Fixed Cost"), input$costst, NA),
        stringsAsFactors = FALSE
      )
      values_total$data <- rbind(values_total$data, new_row)
      output$error_messaget <- renderText("")
      if (nrow(values_total$data) == input$num_stratat) {
        if (sum(values_total$data$StratumSize) != input$population_sizeMEt) {
          output$error_messaget <- renderText("Error: The sum of the stratum sizes does not equal the total population size. The table has been cleared.")
          values_total$data <- data.frame(
            Stratum = integer(0),
            StratumSize = numeric(0),
            EstimatedVariance = numeric(0),
            Costs = numeric(0),
            stringsAsFactors = FALSE
          )
        } else {
          
          update_sample_sizet()
        }
      }
    } else {
      output$error_messaget <- renderText("Error: You cannot add more rows than the specified number of strata.")
    }
  })
  observeEvent(input$cleart, {
    clear_datat()
    output$error_messaget <- renderText("The information about the strata has been cleared.")
  })
  observeEvent(input$population_sizeMEt, {
    if (nrow(values_total$data) > 0) {  # Verificar si ya se capturaron datos de estratos
      clear_datat()  # Limpiar datos capturados para total
      output$error_message <- renderText("You must re-enter the information about the strata.")  # Mostrar el mensaje solo cuando ya hay datos
    } else {
      output$error_message <- renderText("")  # No mostrar mensaje si no hay datos capturados
    }
  })
  observeEvent(input$num_stratat, {
    if (nrow(values_total$data) > 0) {
      clear_datat()
      output$error_message <- renderText("You must re-enter the information about the strata.")
    } else {
      output$error_message <- renderText("")
    }
  })
  observeEvent(input$confidenceMEt, {
    if (nrow(values_total$data) == input$num_stratat && sum(values_total$data$StratumSize) == input$population_sizeMEt) {
      update_sample_sizet()
    }
  })
  observeEvent(input$precisionMEt, {
    if (nrow(values_total$data) == input$num_stratat && sum(values_total$data$StratumSize) == input$population_sizeMEt) {
      update_sample_sizet()
    }
  })
  observeEvent(input$Type_C, {
    # Si el tipo es "Optimal Minimum Variance and Fixed Cost" o "Optimal Fixed Variance and Minimum Cost"
    if (input$Type_C %in% c("Optimal Minimum Variance and Fixed Cost", "Optimal Fixed Variance and Minimum Cost")) {
      clear_datat()
      values_total$sample_size <- NULL  
      updateNumericInput(session, "stratum_sizet", value = 0)
      updateNumericInput(session, "estimated_variancet", value = 0)
      updateNumericInput(session, "costst", value = 0)
      output$error_message <- renderText("")
      output$error_messaget <- renderText("")
    }
    # Si el tipo es "Uniform Assignment", "Proportional Assignment" o "Neyman Assignment"
    else if (input$Type_C %in% c("Uniform Assignment", "Proportional Assignment", "Neyman Assignment")) {
      if (nrow(values_total$data) == input$num_stratat && sum(values_total$data$StratumSize) == input$population_sizeMEt) {
        update_sample_sizet()  # Recalcula el tamaño de muestra
        output$error_message <- renderText("")  # Limpia cualquier mensaje de error previo
      } else {
        # Mensaje de error si los datos no son válidos
        output$error_message <- renderText("")
        # output$error_message <- renderText("Error: The strata data is incomplete or inconsistent. Please verify.")
      }
    }
  })
  observeEvent(input$Costt, {
    if (input$Type_C == "Optimal Minimum Variance and Fixed Cost" &&
        nrow(values_total$data) == input$num_stratat && sum(values_total$data$StratumSize) == input$population_sizeMEt) {
      update_sample_sizet()
    }
  })
  update_sample_sizet <- function() {
    N <- input$population_sizeMEt
    k <- input$num_stratat
    Ni <- values_total$data$StratumSize
    s2 <- values_total$data$EstimatedVariance
    z_alpha_2 <- qnorm((1 + input$confidenceMEt / 100) / 2)
    e <- input$precisionMEt
    RCi <- sqrt(values_total$data$Costs)
    C <- input$Costt
    if (input$Type_C == "Uniform Assignment") {
      numerator <- sum(as.numeric(Ni)^2 * as.numeric(s2))
      denominator <- ( e^2 / z_alpha_2^2) + sum(as.numeric(Ni) * as.numeric(s2))
      n <- ceiling(k * numerator / denominator)
      values_total$sample_size <- n
    } else if (input$Type_C == "Proportional Assignment") {
      # Proportional Assignment (versión segura)
      numerator <- as.numeric(N) * sum(as.numeric(Ni) * as.numeric(s2))
      denominator <- ( e^2 / z_alpha_2^2) + sum(as.numeric(Ni) * as.numeric(s2))
      n <- ceiling(numerator / denominator)
      values_total$sample_size <- n
    } else if (input$Type_C == "Neyman Assignment") {
      numerator <- (sum(as.numeric(Ni) * sqrt(as.numeric(s2))))^2
      denominator <- ( e^2 / z_alpha_2^2) + sum(as.numeric(Ni) * as.numeric(s2))
      n2=(numerator/denominator)
      
      n <- ceiling(n2)
      
      values_total$sample_size <- n
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      numerator <- sum(as.numeric(Ni) * sqrt(as.numeric(s2)) * RCi) * sum(as.numeric(Ni) * sqrt(as.numeric(s2)) / RCi)
      denominator <- ( e^2 / z_alpha_2^2) + sum(as.numeric(Ni) * as.numeric(s2))
      n2=numerator / denominator
      
      n <- ceiling(n2)
      
      values_total$sample_size <- n
    } else if (input$Type_C == "Optimal Minimum Variance and Fixed Cost") {
      Wi <- (as.numeric(Ni) * sqrt(as.numeric(s2))) / RCi
      numerator <- as.numeric(C) * sum(Wi)
      denominator <- sum(as.numeric(Ni) * sqrt(as.numeric(s2)) * RCi)
      n <- ceiling(numerator / denominator)
      values_total$sample_size <- n
    }
    
  }
  clear_datat <- function() {
    values_total$data <- data.frame(
      Stratum = integer(0),
      StratumSize = numeric(0),
      EstimatedVariance = numeric(0),
      Costs = numeric(0),
      stringsAsFactors = FALSE
    )
    values_total$sample_size <- NULL
  }
  output$sample_sizet <- renderText({
    if (!is.null(values_total$sample_size)) {
      # Solo una vez y sin acumulaciones
      paste0("Sample size: ", values_total$sample_size,
             "\nThe sample size obtained corresponds to the nearest upper integer.")
    } else {
      ""
    }
  })
  output$table_datat <- renderPrint({
    if (nrow(values_total$data) > 0) {
      cat("Information about the strata\n")
      if (input$Type_C %in% c("Optimal Fixed Variance and Minimum Cost", "Optimal Minimum Variance and Fixed Cost")) {
        print(values_total$data)
      } else {
        print(values_total$data[, -which(names(values_total$data) == "Costs")])
      }
      if (!is.null(values_total$sample_size)) {
        cat("\nSample Size:", values_total$sample_size, "\n")
        cat("\nSample Size of Strata:\n")
        if (input$Type_C == "Uniform Assignment") {
          print(data.frame(
            Stratum = values_total$data$Stratum,
            `Sample Size of Stratum` = ceiling(values_total$sample_size / input$num_stratat)
          ))
        } else if (input$Type_C == "Proportional Assignment") {
          print(data.frame(
            Stratum = values_total$data$Stratum,
            `Sample Size of Stratum` = ceiling(values_total$sample_size * (values_total$data$StratumSize / input$population_sizeMEt))
          ))
        } else if (input$Type_C == "Neyman Assignment") {
          print(data.frame(
            Stratum = values_total$data$Stratum,
            `Sample Size of Stratum` = ceiling((values_total$sample_size * values_total$data$StratumSize * sqrt(values_total$data$EstimatedVariance)) / (sum(values_total$data$StratumSize * sqrt(values_total$data$EstimatedVariance))))
          ))
        } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
          print(data.frame(
            Stratum = values_total$data$Stratum,
            `Sample Size of Stratum` = ceiling((values_total$sample_size * (values_total$data$StratumSize * sqrt(values_total$data$EstimatedVariance) / sqrt(values_total$data$Costs)) / sum((values_total$data$StratumSize * sqrt(values_total$data$EstimatedVariance) / sqrt(values_total$data$Costs)))))
          ))
        } else {
          print(data.frame(
            Stratum = values_total$data$Stratum,
            `Sample Size of Stratum` = ceiling(values_total$sample_size * (values_total$data$StratumSize * sqrt(values_total$data$EstimatedVariance) / sqrt(values_total$data$Costs)) / sum((values_total$data$StratumSize * sqrt(values_total$data$EstimatedVariance) / sqrt(values_total$data$Costs))))
          ))
        }
        
        cat("\nThe sample size obtained for each stratum is the nearest upper integer\nof the calculated value. Therefore, the sum of the sample sizes for\n each stratum may differ from the total calculated sample size.")
      }
      if (input$Type_C != "Optimal Minimum Variance and Fixed Cost") {
        cat("\nPopulation Size:", input$population_sizeMEt, "\n")
        cat("Precision:", input$precisionMEt, "\n")
        cat("Confidence:", input$confidenceMEt, "\n")
      }else{
        print(input$costt)
        cat("\nPopulation Size:", input$population_sizeMEt, "\n")
        cat("Total cost:", input$Costt, "\n")
      }
    }
    
  })
  output$equamet <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type_C == "Uniform Assignment") {
      equations <- c("","$$n = \\frac{k \\sum_{i=1}^{k} N_i^2 s_i^2}{\\frac{e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{n}{k}$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Uniform Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_C == "Proportional Assignment") {
      equations <- c("","$$n = \\frac{N \\sum_{i=1}^{k} N_i s_i^2}{\\frac{ e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{N_i }{N} n$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Proportional Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_C == "Neyman Assignment") {
      equations <- c("","$$n = \\frac{(\\sum_{i=1}^{k} N_i s_i)^2}{\\frac{ e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{N_i s_i}{ \\sum_{i=1}^{k} N_i s_i}n$$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Neyman Allocation",
                      "Sample Size for stratum i")
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      equations <- c("","$$n =\\frac{\\sum_{i=1}^{k} N_i s_i \\sqrt{C_i}\\sum_{i=1}^{k}\\frac{N_i s_i}{\\sqrt{C_i}}} { \\frac{ e^2}{z_{\\alpha/2}^2} + \\sum_{i=1}^{k} N_i s_i^2}$$",
                     "$$n_i = \\frac{\\frac { N_i s_i}{\\sqrt{C_i} }}{\\sum_{i=1}^{k}\\frac { N_i s_i}{\\sqrt{C_i} }} n $$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Optimal Fixed Variance and Minimum Cost",
                      "Sample Size for stratum i")
    } else {
      equations <- c("","$$n =\\frac{ C \\sum_{i=1}^{k} \\frac{N_i s_i}{\\sqrt{C_i}}}{\\sum_{i=1}^{k}N_i s_i \\sqrt{C_i }} $$",
                     "$$n_i = \\frac{\\frac { N_i s_i}{\\sqrt{C_i} }}  {\\sum_{i=1}^{k} \\frac{N_i s_i}{\\sqrt{C_i} }} n $$")
      paragraphs <- c("","Sample Size for Estimating the Mean in Stratified Sampling with Optimal Minimum Variance and Fixed Cost",
                      "Sample Size for stratum i")
    }
    paragraphs2 <- c("Where:",
                     "is the total sample size.",
                     "is the sample size for stratum i.",
                     "is the population size.",
                     "is the total size of stratum i.",
                     "is the stratum number.",
                     "is the estimated variance of the characteristic of interest in the stratum i.",
                     "is the z-score corresponding to the desired confidence level.",
                     "is the maximum permissible absolute error (or desired absolute precision).")
    equations2 <- c("$$ $$",
                    "$$n$$",
                    "$$n_i$$",
                    "$$N$$",
                    "$$N_i$$",
                    "$$k$$",
                    "$$s_i^2$$",
                    "$$z_{(\\alpha/2)}$$",
                    "$$e$$")
    if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      paragraphs2 <-c(paragraphs2, "is the cost to obtain a unit from stratum i")
      equations2 <- c(equations2, "$$C_i$$")
    }
    if (input$Type_C == "Optimal Minimum Variance and Fixed Cost") {
      paragraphs2 <- c("Where:",
                       "is the total sample size.",
                       "is the sample size for stratum i.",
                       "is the total cost",
                       "is the cost to obtain a unit from stratum i",
                       "is the total size of stratum i.",
                       "is the estimated variance of the characteristic of interest in the stratum i.")
      equations2 <- c("$$ $$",
                      "$$n$$",
                      "$$n_i$$",
                      "$$C$$",
                      "$$C_i$$",
                      "$$N_i$$",
                      "$$s_i^2$$")
    }
    if (input$Type_C == "Uniform Assignment") {
      title<- "Equation of Sample Size Calculation for Estimating The Total using Uniform Assignment "
    } else if (input$Type_C == "Proportional Assignment") {
      title<-"Equation of Sample Size Calculation for Estimating The Total using Proportional Assignment "
    } else if (input$Type_C == "Neyman Assignment") {
      title<- "Equation of Sample Size Calculation for Estimating The Total using Neyman Assignment "
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      title<-"Equation of Sample Size Calculation for Estimating The Total using Optimal Fixed Variance and Minimum Cost "
    } else {
      title<-"Equation of Sample Size Calculation for Estimating The Total using Optimal Minimum Variance and Fixed Cost "
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  output$informmet <- renderUI({
    equations <- c(
      "",
      "$$\\bar{y_i} = \\frac{1}{n_i} \\sum_{h=1}^{n_i} y_{ih}$$",
      "$$\\hat{t} = \\sum_{i=1}^{k}N_i \\bar{y_i}$$",
      "$$\\hat{V}(\\hat{t}) = \\sum_{i=1}^{k} \\left(1-\\frac{n_i}{N_i}\\right) N_i^2 \\frac{s_i^2}{n_i}$$")
    paragraphs <- c("",
                    "Estimator of the mean of stratum i.",
                    "Estimator of the population total.",
                    "Estimator of the variance of the estimator of the population mean.")
    paragraphs2 <- c("Where:",
                     "is the estimator of the population total.",
                     "is the estimator of the mean of stratum i.",
                     "is the estimator of the variance of the estimator of the population mean.",
                     "is the sample size for stratum i.",
                     "is the population size.",
                     "is the total size of stratum i.",
                     "is the stratum number.",
                     "is the estimated variance of the characteristic of interest in the stratum i.")
    equations2 <- c("$$ $$",
                    "$$\\hat{t}$$",
                    "$$\\bar{y_i}$$",
                    "$$\\hat{V}(\\bar{y})$$",
                    "$$n_i$$",
                    "$$N$$",
                    "$$N_i$$",
                    "$$k$$",
                    "$$s_i^2$$")
    if (input$Type_C == "Uniform Assignment") {
      title <- "Stratified Random Sampling of the Total with Uniform Allocation"
    } else if (input$Type_C == "Proportional Assignment") {
      title <- "Stratified Random Sampling of the Total with Proportional Allocation"
    } else if (input$Type_C == "Neyman Assignment") {
      title <- "Stratified Random Sampling of the Total with Neyman Allocation"
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      title <- "Stratified Random Sampling of the Total with Optimal Fixed Variance and Minimum Cost"
    } else {
      title <- "Stratified Random Sampling of the Total with Optimal Minimum Variance and Fixed Cost"
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  output$plan_title_t <- renderText({
    if (input$Type_C == "Uniform Assignment") {
      "Stratified Sampling: Estimating the Total with Uniform Assignment"
    } else if (input$Type_C == "Proportional Assignment") {
      "Stratified Sampling: Estimating the Total with Proportional Assignment"
    } else if (input$Type_C == "Neyman Assignment") {
      "Stratified Sampling: Estimating the Total with Neyman Assignment"
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      "Stratified Sampling: Estimating the Total with Optimal Fixed Variance and Minimum Cost"
    } else {
      "Stratified Sampling: Estimating the Total with Optimal Minimum Variance and Fixed Cost"
    }
  })
  output$examplemet <- renderUI({
    # Define el contenido del ejemplo
    if (input$Type_C == "Uniform Assignment") {
      example_title <- "Example of estimating the total using uniform allocation within the strata"
    }else if (input$Type_C == "Proportional Assignment") {
      example_title <- "Example of estimating the total using proportional allocation within the strata"
    } else if (input$Type_C == "Neyman Assignment") {
      example_title <- "Example of estimating the total using Neyman allocation within the strata"  
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      example_title <- "Example of estimating the total using optimal fixed variance and minimum cost allocation within the strata" 
    } else {
      example_title <- "Example of estimating the total using optimal minimum variance and fixed cost allocation within the strata"
    }
    example_html <- NULL
    
    example_description <- paste(
      "In a given region, there are 1000 ranches which have been stratified according",
      "to their size (small, medium, and large), and the objective is to estimate the",
      "total number of cattle heads across these ranches."
    )
    example_description2 <- paste(
      "From a preliminar Survey, the following information about the variances was obtained:"
    )
    
    if (input$Type_C == "Uniform Assignment") {
      example_description3 <- paste(
        "What should be the sample size to estimate the total number of cattle heads with a precision of plus or minus 50000",
        "cattle heads and a 95% confidence level? A uniform allocation within the strata is desired."
      )
    } else if (input$Type_C == "Proportional Assignment") {
      example_description3 <- paste(
        "What should be the sample size to estimate the total number of cattle heads with a precision of plus or minus 50000",
        "cattle heads and a 95% confidence level? A proportional allocation within the strata is desired. "
        
      )
    } else if (input$Type_C == "Neyman Assignment") {
      example_description3 <- paste(
        "What should be the sample size to estimate the total number of cattle heads with a precision of plus or minus 50000",
        "cattle heads and a 95% confidence level? A Neyman allocation within the strata is desired."
      )
    } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
      example_description3 <- paste(
        "What should be the sample size to estimate the total number of cattle heads with a precision of plus or minus 50000",
        "cattle heads and a 95% confidence level? An optimal fixed variance and minimum cost is desired."
        
      )
    } else {
      example_description3 <- paste(
        "What should be the sample size to estimate the total number of cattle heads with a precision of plus or minus 50000",
        "cattle heads and a 95% confidence level?. An optimal minimum variance and fixed cost is desired.The total allocated budget",
        "for the sampling study is $5000.00 ."
      )
    }
    if (input$Type_C %in% c("Uniform Assignment", "Proportional Assignment",
                            "Neyman Assignment")) {
      example_table <- tags$table(
        style = "width: 70%; border-collapse: collapse; text-align: center;",
        tags$thead(
          tags$tr(
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum"),
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum Size"),
            tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Estimated Variance")
            
          )
        ),
        tags$tbody(
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "1"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "500"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "10000")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "2"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "300"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "15000")
          ),
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "3"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "200"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "20000")
          ),
          
          tags$tr(
            tags$td(style = "border: 1px solid black; padding: 1px;", "Total"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "1000"),
            tags$td(style = "border: 1px solid black; padding: 1px;", "")
          )
        )
      )
    }else {example_table <- tags$table(
      style = "width: 70%; border-collapse: collapse; text-align: center;",
      tags$thead(
        tags$tr(
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Stratum Size"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Estimated Variance"),
          tags$th(style = "border: 1px solid black; padding: 1px; text-align: center;", "Costs per Unit")
          
        )
      ),
      tags$tbody(
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "1"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "500"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "10000"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "134")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "2"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "300"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "15000"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "163")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "3"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "200"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "20000"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "180")
        ),
        tags$tr(
          tags$td(style = "border: 1px solid black; padding: 1px;", "Total"),
          tags$td(style = "border: 1px solid black; padding: 1px;", "1000"),
          tags$td(style = "border: 1px solid black; padding: 1px;", ""),
          tags$td(style = "border: 1px solid black; padding: 1px;", "")
        )
      )
    )}
    
    example_html <- tags$div(
      tags$h4(example_title,class = "custom-title-bold" ),
      tags$p(HTML(example_description)),
      tags$p(HTML(example_description2)),
      example_table,
      tags$p(HTML(example_description3)),
      
      tags$h6("."),
      tags$h4("Result:",class = "custom-title-bold"),
      
      if (input$Type_C == "Uniform Assignment") {
        tags$h4("Stratified Sampling: Estimating the Total with Uniform Assignment",class = "custom-title-bold")
        
      } else if (input$Type_C == "Proportional Assignment") {
        tags$h4("Stratified Sampling: Estimating the Total with Proportional Assignment",class = "custom-title-bold")
      } else if (input$Type_C == "Neyman Assignment") {
        tags$h4("Stratified Sampling: Estimating the Total with Neyman Assignment",class = "custom-title-bold")
      } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
        tags$h4("Stratified Sampling: Estimating the Total with Optimal Fixed Variance and Minimum Cost",class = "custom-title-bold")
      } else {
        tags$h4("Stratified Sampling: Estimating the Total with Optimal Minimum Variance and Fixed Cost",class = "custom-title-bold")
      },
      if (input$Type_C == "Uniform Assignment") {
        tags$p(paste("Sample size:", 21))
        
      } else if (input$Type_C == "Proportional Assignment") {
        tags$p(paste("Sample size:", 21))
      } else if (input$Type_C == "Neyman Assignment") {
        tags$p(paste("Sample size:", 20))
      } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
        tags$p(paste("Sample size:", 20))
      } else {
        tags$p(paste("Sample size:", 33))
      },
      
      tags$p("The sample size obtained corresponds to the nearest upper integer."),
      tags$p("Information about the strata"),
      
      if (input$Type_C %in% c("Uniform Assignment", "Proportional Assignment",
                              "Neyman Assignment")) {
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "StratumSize"),
              tags$th(style = "padding: 1px; text-align: center;", "EstimatedVariance")
              
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "500"),
              tags$td(style = "padding: 1px;", "10000")
              
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "300"),
              tags$td(style = "padding: 1px;", "15000")
              
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "200"),
              tags$td(style = "padding: 1px;", "20000")
              
            ),
            
            tags$tr(
              tags$td(style = "padding: 1px;", "Total"),
              tags$td(style = "padding: 1px;", "1000"),
              tags$td(style = "padding: 1px;", "")
            )
          )
        )
      }else {example_table <- tags$table(
        tags$table(
          style = "width: 60%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "StratumSize"),
              tags$th(style = "padding: 1px; text-align: center;", "EstimatedVariance"),
              tags$th(style = "padding: 1px; text-align: center;", "Costs")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "500"),
              tags$td(style = "padding: 1px;", "10000"),
              tags$td(style = "padding: 1px;", "135")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "300"),
              tags$td(style = "padding: 1px;", "15000"),
              tags$td(style = "padding: 1px;", "163")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "200"),
              tags$td(style = "padding: 1px;", "20000"),
              tags$td(style = "padding: 1px;", "180")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "Total"),
              tags$td(style = "padding: 1px;", "1000"),
              tags$td(style = "padding: 1px;", ""),
              tags$td(style = "padding: 1px;", "")
            )
          )
        ))},
      
      
      
      if (input$Type_C == "Uniform Assignment") {
        tags$p(paste("Sample size:", 21))
        
      } else if (input$Type_C == "Proportional Assignment") {
        tags$p(paste("Sample size:", 21))
      } else if (input$Type_C == "Neyman Assignment") {
        tags$p(paste("Sample size:", 20))
      } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
        tags$p(paste("Sample size:", 20))
      } else {
        tags$p(paste("Sample size:", 33))
      },
      
      if (input$Type_C == "Uniform Assignment") {
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "7")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "7")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "7")
            ),
          )
        )
        
      } else if (input$Type_C == "Proportional Assignment") {
        
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "11")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "7")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "5")
            ),
          )
        )
      } else if (input$Type_C == "Neyman Assignment") {
        
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "9")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "7")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "5")
            ),
          )
        )
      } else if (input$Type_C == "Optimal Fixed Variance and Minimum Cost") {
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "10")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "7")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "5")
            ),
          )
        )
      } else {
        tags$table(
          style = "width: 50%; border-collapse: collapse; text-align: center; border: none;",
          tags$thead(
            tags$tr(
              tags$th(style = "padding: 1px; text-align: center;", "Stratum"),
              tags$th(style = "padding: 1px; text-align: center;", "Sample.Size.of.Stratum")
            )
          ),
          tags$tbody(
            tags$tr(
              tags$td(style = "padding: 1px;", "1"),
              tags$td(style = "padding: 1px;", "16")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "2"),
              tags$td(style = "padding: 1px;", "11")
            ),
            tags$tr(
              tags$td(style = "padding: 1px;", "3"),
              tags$td(style = "padding: 1px;", "8")
            ),
          )
        )
        
      },
      tags$p("The sample size obtained for each stratum is the nearest upper integer of the calculated value. Therefore, the sum of the sample sizes for each stratum may differ from the total calculated sample size."),
      if (input$Type_C != "Optimal Minimum Variance and Fixed Cost") {
        list(
          
          tags$p(paste("Population Size:", 1000)),
          tags$p(paste("Precision:", 50000)),
          tags$p(paste("Confidence:", 95)),
          tags$p(style = "height: 50px;")
        )
      }else{
        list(
          tags$p(paste("Population Size:", 1000)),
          tags$p(paste("Total Cost:", 5000)),
          tags$p(style = "height: 50px;")  # Espacio adicional al final
        ) 
      }
      
      
      
      
    )
    
    return(example_html)
  })
  
  ####################################################################
  ################################Start single stage Cluster Sampling
  #####################################################################
  
  ######################################################################################################
  ################################################ Start single stage sampling mean
  #######################################################################################################
  
  example_description3.5 <- paste("This sampling scheme employs simple random sampling without",
                                  "replacement at the first stage for the selection of clusters,",
                                  "followed by a complete enumeration (census) of all units within",
                                  "each selected cluster.")
  descriptionT <- paste("Note: The estimated total sample size corresponds to the nearest upper integer.")
  descriptionT2 <- paste("Note: The number of clusters in the sample corresponds to the nearest upper integer.")
  descriptionT_div <- tags$div(descriptionT)
  descriptionT2_div <- tags$div(descriptionT2)
  
  sample_calc_mc <- reactive({
    confidencec <- input$Confidence_mc
    precisionc <- input$Precision_mc
    variancec <- input$Variance_mc
    alpha2c <- (1 - confidencec / 100) / 2
    zc <- qnorm(alpha2c, lower.tail = FALSE)
    CSUSc <- input$CSUS_mc
    ICCc <- input$ICC_mc
    if (input$method_mc == "                  Using intracluster correlation     ") {
      
      defc <- 1 + (CSUSc - 1) * ICCc
    } else {
      defc <- input$deff_mc
    }
    if (input$Type_mc == "Infinite Population") {
      nic <- variancec * (zc^2) / (precisionc^2)
      Nc <- NA
      
    } else {
      Nc <- input$N_mc
      n <- variancec * (zc^2) / (precisionc^2)
      nic <- n / (1 + (n / Nc))
    }
    nic=ceiling(nic*defc)
    niclu <- ceiling(nic / CSUSc)
    
    list(nic = nic, defc = defc, Nc = Nc,niclu=niclu)
  })
  ############ Start summary mean
  output$summarymc <- renderUI({
    
    res <- sample_calc_mc()
    output$ni_valuec <- renderText({ res$nic })
    output$nic_valuec <- renderText({ res$niclu })
    output$def_valuec <- renderText({ res$def })
    output$conf_valuec <- renderText({ input$Confidence_mc })
    output$prec_valuec <- renderText({ input$Precision_mc })
    output$var_valuec <- renderText({ input$Variance_mc })
    output$CSUS_valuec <- renderText({ input$CSUS_mc })
    
    
    if (!is.na(res$Nc)) {
      output$N_valuec <- renderText({ res$Nc })
    }
    
    if (input$method_mc == "Using intracluster correlation") {
      output$ICC_valuec <- renderText({  input$ICC_mc})
      
      if (input$Type_mc == "Infinite Population") {
        title <- "Sample Size for Estimating the Mean with Single-Stage Cluster Sampling and Infinite Number of Clusters."
        texts <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample: ", 
          "The confidence level: ",
          "The estimated variance of the characteristic of interest: ",
          "The absolute precision:",
          "The intracluster correlation:",
          "The average cluster size:",  
          "The design effect:"
        )
        dynamics <- c("", "ni_valuec","nic_valuec", "conf_valuec", "var_valuec", 
                      "prec_valuec", "ICC_valuec", "CSUS_valuec", "def_valuec")
      } else {
        title <- "Sample Size for Estimating the Mean with Single-Stage Cluster Sampling and Finite Number of Clusters."
        texts <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample: ", 
          "The total number of clusters in the population:",
          "The confidence level: ",
          "The estimated variance of the characteristic of interest: ",
          "The absolute precision:",
          "The intracluster correlation:", 
          "The average cluster size:", 
          
          
          "The design effect:"
        )
        dynamics <- c("", "ni_valuec", "nic_valuec", "N_valuec", "conf_valuec", "var_valuec",
                      "prec_valuec", "ICC_valuec", "CSUS_valuec", "def_valuec")
      }
      
    }else{
      if (input$Type_mc == "Infinite Population") {
        title <- "Sample Size for Estimating the Mean with Single-Stage Cluster Sampling and Infinite Number of Clusters."
        texts <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample:", 
          "The confidence level:",
          "The estimated variance of the characteristic of interest: ",
          "The absolute precision:",
          "The average cluster size:",  
          "The design effect:"
        )
        dynamics <- c("", "ni_valuec","nic_valuec", "conf_valuec", "var_valuec", 
                      "prec_valuec", "CSUS_valuec", "def_valuec")
      } else {
        title <- "Sample Size for Estimating the Mean with Single-Stage Cluster Sampling and Finite Number of Clusters."
        texts <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample: ", 
          "The total number of clusters in the population:",
          "The Confidence level: ",
          "The estimated variance of the characteristic of interest: ",
          "The absolute precision:", 
          "The average cluster size:", 
          "The design effect:"
        )
        dynamics <- c("", "ni_valuec", "nic_valuec", "N_valuec", "conf_valuec", "var_valuec",
                      "prec_valuec", "CSUS_valuec", "def_valuec")
      }
      
    }
    P1 <- generate_dynamic_lines(dynamics, texts)
    report_f_html <- tagList(
      tags$div(class = "custom-title-bold", title),
      tags$p("This sampling scheme employs simple random sampling without replacement at the first stage for the selection of clusters, followed by a complete enumeration (census) of all units within each selected cluster."),
      P1,
      descriptionT_div,
      descriptionT2_div
    )
    
    
    
    return(report_f_html)
  })
  ############ Start equations for estimating the mean (clusters)
  output$equamc <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type_mc == "Infinite Population") {
      equations <- c("","$$n_0 = \\frac{s^2 z_{(\\alpha/2)}^2}{e^2} deff$$","$$deff=1+(\\bar{M}-1)IIC$$","$$n_c=\\frac{n_0}{\\bar{M}}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate the mean:", "and", "and")
      paragraphs2 <- c("Where:",
                       "is the estimated total sample size to estimate the mean.",
                       "is the number of clusters to be included in the sample.",
                       "is the estimated variance of the characteristic of interest.",
                       "is the z-score corresponding to the desired confidence level.",
                       "is the maximum permissible absolute error (or desired absolute precision).",
                       "is the design effect.",
                       "is the Intracluster correlation.",
                       "is the average of the number of elementary units per cluster."
      )
      
      # Definition of additional explanatory equations
      equations2 <- c(
        "$$ $$",
        "$$n_0$$",
        "$$n_c$$",
        "$$s^2$$",
        "$$z_{(\\alpha/2)}$$",
        "$$e$$",
        "$$deff$$",
        "$$ICC$$",
        "$$\\bar {M}$$"
      )
      
    }else{
      equations <- c("","$$n_0 = \\frac{N s^2 z_{(\\alpha/2)}^2}{N e^2 + s^2 z_{(\\alpha/2)}^2} deff$$","$$deff=1+(\\bar{M}-1)IIC$$","$$n_c=\\frac{n_0}{\\bar{M}}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate the mean of a finite population:","and", "and")
      paragraphs2 <- c("Where:",
                       "is the estimated total sample size to estimate the mean.",
                       "is the number of clusters to be included in the sample.",
                       "is the total number of clusters in the population.",
                       "is the estimated variance of the characteristic of interest.",
                       "is the z-score corresponding to the desired confidence level.",
                       "is the maximum permissible absolute error (or desired absolute precision).",
                       "is the design effect.",
                       "is the Intracluster correlation.",
                       "is the average of the number of elementary units per cluster."
      )
      
      # Definition of additional explanatory equations
      equations2 <- c(
        "$$ $$",
        "$$n_0$$",
        "$$n_c$$",
        "$$N$$",
        "$$s^2$$",
        "$$z_{(\\alpha/2)}$$",
        "$$e$$",
        "$$deff$$",
        "$$ICC$$",
        "$$\\bar {M}$$"
      )
      
    }
    
    if (input$Type_mc == "Infinite Population") {
      title <- "Equation of Sample Size Calculation for Estimating the Mean with Single-Stage Cluster Sampling and Infinite Number of Clusters."
    }else{
      title <- "Equation of Sample Size Calculation for Estimating the Mean with Single-Stage Cluster Sampling and Finite Number of Clusters."
    }
    report_html <- tags$div()
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ############ Start additional information  mean
  output$informmc <- renderUI({
    if (input$Type_mc == "Infinite Population") {
      equations <- c(
        "",
        "$$\\bar{y_i} = \\frac{1}{M_i} \\sum_{h=1}^{M_i} y_{ih}$$",
        "$$\\bar{\\bar{y}} = \\frac{\\sum_{i=1}^{n_c} M_i\\bar{y_i}}{\\sum_{i=1}^{n_c} {M_i}}$$",
        "$$\\hat{V}(\\bar{\\bar{y}}) =\\frac{1}{n_c(n_c-1)} \\sum_{i=1}^{n_c} M_i^2 \\left(\\bar{y_i}-\\bar{\\bar{y}}\\right)^2$$")
      paragraphs2 <- c("Where:",
                       "is the estimator of the mean of cluster i.",
                       "is the value of observation h from stratum i.",
                       "is the estimator of the population mean.",
                       "is the estimator of the variance of the estimator of the population mean.",
                       "is the number of clusters in the sample.",
                       "is the number of elementary units in cluster i (Cluster size)."
                       
                       
      )
      equations2 <- c("$$ $$",
                      "$$\\bar{y_i}$$",
                      "$$y_{ih}$$",
                      "$$\\bar{\\bar{y}}$$",
                      "$$\\hat{V}(\\bar{\\bar{y}})$$",
                      "$$n_c$$",
                      "$$M_i$$"
                      
                      
      )
    }else{
      
      equations <- c(
        "",
        "$$\\bar{y_i} = \\frac{1}{M_i} \\sum_{h=1}^{M_i} y_{ih}$$",
        "$$\\bar{\\bar{y}} = \\frac{\\sum_{i=1}^{n_c} M_i\\bar{y_i}}{\\sum_{i=1}^{n_c} {M_i}}$$",
        "$$\\hat{V}(\\bar{\\bar{y}}) = \\left(1 - \\frac{n_c}{M} \\right) \\cdot \\frac{1}{n_c(n_c-1)} \\sum_{i=1}^{n_c} M_i^2 \\left(\\bar{y_i}-\\bar{\\bar{y}}\\right)^2$$")
    }
    paragraphs <- c("",
                    "Estimator of the mean of cluster i",
                    "Estimator of the population mean (Horwitz-Thompson estimator)",
                    "Estimator of the variance of the estimator of the population mean")
    
    
    paragraphs2 <- c("Where:",
                     "is the estimator of the mean of cluster i.",
                     "is the value of observation h from stratum i.",
                     "is the estimator of the population mean.",
                     "is the estimator of the variance of the estimator of the population mean.",
                     "is the number of clusters in the sample.",
                     "is the number of elementary units in cluster i (Cluster size).",
                     "is the total number of clusters in the population."
                     
    )
    equations2 <- c("$$ $$",
                    "$$\\bar{y_i}$$",
                    "$$y_{ih}$$",
                    "$$\\bar{\\bar{y}}$$",
                    "$$\\hat{V}(\\bar{\\bar{y}})$$",
                    "$$n_c$$",
                    "$$M_i$$",
                    "$$M$$"
                    
    )
    if (input$Type_mc == "Infinite Population") {
      title <- "Single-Stage Cluster Sampling for Estimating the Mean with Infinite Number of Clusters."
    }else{
      title <- "Single-Stage Cluster Sampling for Estimating the Mean with Finite Number of Clusters."  
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  ################# Start example mean
  output$examplemc <- renderUI({
    # Define the content of the example
    
    if (input$Type_mc == "Finite Population") {
      example_title <- "Example: Estimating the Mean with Single-Stage Cluster Sampling and Finite Number of Clusters"
      example_description <- paste(
        "A research company wants to estimate the average amount per transaction by a supermarket chain",
        "in a specific region over a year. This supermarket chain has 300 branches throughout the",
        "region. On average, each branch performs 50 daily transactions."
      )
      example_description2 <- paste(
        "The company plans to use a",
        "single-stage cluster sampling design, where each branch is considered a cluster, and each daily transaction",
        "is an observation unit."
      )
      example_description3 <- paste(
        "The following historical data on daily revenues is available:"
      )
      
      example_description4 <- paste(
        "The variance between branches in the average amount per transaction is 1000"
      )
      if (input$method_mc == "Using intracluster correlation") { 
        example_description5 <- paste(
          "The intracluster correlation is 0.01"
        )} else { example_description5 <- paste(
          "Similar studies had a deff of 1.49"
        )}
      example_description6 <- paste(
        "The company wants the estimate to have a margin of error of $5 in the estimate",
        "of the average annual revenue for the entire region and seeks a 95% confidence level."
        
      )
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating the Mean with Single-Stage Cluster Sampling and Finite Number of Clusters"
      if (input$method_mc == "Using intracluster correlation") { 
        example_result <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample :",
          "The total number of clusters in the population:",
          "The Confidence level :",
          "The estimated variance of the characteristic of interest:",
          "The absolute precision:",
          "The Intracluster correlation:",
          "The Average cluster size:",
          
          "The design effect:"
        )
        result_numbers <- c("" ,152,4,300,95,1000,5,0.01, 50,1.49)
      }else{
        example_result <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample :",
          "The total number of clusters in the population:",
          "The Confidence level :",
          "The estimated variance of the characteristic of interest:",
          "The absolute precision:",
          "The Average cluster size:",
          "The design effect:"
        )
        result_numbers <- c("" ,152,4,300,95,1000,5, 50,1.49) 
      }
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(example_description2)),
        tags$p(HTML(example_description3)),
        tags$p(HTML(example_description4)),
        tags$p(HTML(example_description5)),
        tags$p(HTML(example_description6)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description3.5)),
        table_html,
        tags$div(descriptionT),
        tags$div(descriptionT2),
        
      )
      
      return(example_html)
    } else {
      example_title <- "Example: Estimating the Mean with Single-Stage Cluster Sampling and Infinite Number of Clusters"
      example_description <- paste(
        "A group of researchers wants to estimate the average weekly fuel expenditure of",
        "school buses in a large city. In this city, there are approximately 33,000 bus stations",
        "(considered clusters), and each station services an average of 50 buses."
      )
      example_description2 <- paste(
        "The researchers plan to use a single-stage cluster sampling design, where they will",
        "randomly select a certain number of stations and record the fuel expenditure of each",
        "bus at the selected stations."
      )
      example_description3 <- paste(
        "Based on historical data, the researchers have estimated that:"
      )
      example_description4 <- paste(
        "The variance of teh weekly fuel expenditure is 1000."
      )
      if (input$method_mc == "Using intracluster correlation") { 
      example_description5 <- paste(
        "The intracluster correlation is 0.01"
         )} else { example_description5 <- paste(
        "Similar studies had a deff of 1.49"
        )}
      example_description6 <- paste(
        "They want the mean estimate to have a margin of error of $5 and a 95% confidence level."
      )
      
      
      
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating the Mean with Single-Stage Cluster Sampling and Infinite Number of Clusters"
      if (input$method_mc == "Using intracluster correlation") { 
        example_result <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample:",
          "The Confidence level :",
          "The estimated variance of the characteristic of interest:",
          "The absolute precision:",
          "The Intracluster correlation:",
          "The Average cluster size:",
          "The design effect:"
        )
        result_numbers <- c("",229,5,95,1000,5,0.01, 50,1.49)
      }else{
        example_result <- c(
          "",
          "The estimated total sample size to estimate the mean:",
          "The number of clusters in the sample:",
          "The Confidence level :",
          "The estimated variance of the characteristic of interest:",
          "The absolute precision:",
          "The Average cluster size:",
          "The design effect:"
        )
        result_numbers <- c("",229,5,95,1000,5, 50,1.49)
      }
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(example_description2)),
        tags$p(HTML(example_description3)),
        tags$p(HTML(example_description4)),
        tags$p(HTML(example_description5)),
        tags$p(HTML(example_description6)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description3.5)),
        table_html,
        tags$div(descriptionT),
        tags$div(descriptionT2)
      )
      
      return(example_html)
    }
  })
  ######################################################################################################
  ################################################ Start single stage sampling with proportions(cluster)
  #######################################################################################################
  ############ Start summary proportion
  output$summarypc <- renderUI({
    output$conf_valuepp <- renderText({ input$Confidence_pc })
    output$prec_valuepp <- renderText({ input$Precision_pc })
    output$var_valuepp <- renderText({ input$Proportion_pc })
    output$CSUS_valuepp <- renderText({ input$CSUS_pc })
    
    confidencepp <- input$Confidence_pc
    precisionpp <- input$Precision_pc
    ppp <- input$Proportion_pc
    Npp<-input$N_pc
    alpha2p <- (1 - confidencepp / 100) / 2
    zpp <- qnorm(alpha2p, lower.tail = FALSE)
    CSUSpp <- input$CSUS_pc
    if (input$method_pc == "Using intracluster correlation") {
      output$ICC_valuepp <- renderText({ input$ICC_pc })
      ICCpp <- input$ICC_pc
      defpp <- 1 + (CSUSpp - 1) * ICCpp
    } else {
      defpp <-input$deff_pc
    }
    
    #defpp=1+(CSUSpp-1)*ICCpp
    if (input$Type_pc == "Infinite Population") {
      nipp <- (ppp*(1-ppp) * (zpp^2) )/ (precisionpp^2)
      output$N_valuepp <- renderText({ input$N_pc })
      
    } else{
      npp <- (ppp*(1-ppp) * (zpp^2) )/ (precisionpp^2)
      nipp <- npp / (1 + (npp / Npp))
      
    }
    nipp<-nipp*defpp
    nipp <- ceiling(nipp)
    nippclu<-ceiling(nipp/CSUSpp)
    output$ni_valuepp <- renderText(nipp)
    output$niclu_valuepp <- renderText(nippclu)
    output$def_valuepp <- renderText( defpp )
    if (input$method_pc == "Using intracluster correlation") {
      
      if (input$Type_pc == "Infinite Population") {
        texts <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The confidence level: ",
          "The estimated proportion of the studied characteristic: ",
          "The absolute precision:",
          "The Intracluster correlation:",
          "The average cluster size",
          "The design effect:"
        )
        
        title <- "Sample Size for Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters"
        
        dynamics <- c("","ni_valuepp","niclu_valuepp", "conf_valuepp","var_valuepp", "prec_valuepp",
                      "ICC_valuepp","CSUS_valuepp",  "def_valuepp")
      }else{
        texts <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The total number of clusters in the population:",
          "The confidence level: ",
          "The estimated proportion of the studied characteristic: ",
          "The absolute precision:",
          "The Intracluster correlation:",
          "The average cluster size:",
          "The design effect:"
        )
        title <- "Sample Size for Estimating a Proportion with Single-Stage Cluster Sampling and Finite Number of Clusters"
        dynamics <- c("","ni_valuepp","niclu_valuepp","N_valuepp", "conf_valuepp","var_valuepp",
                      "prec_valuepp","ICC_valuepp","CSUS_valuepp",  "def_valuepp")
      }
      P1 <- generate_dynamic_lines(dynamics, texts)
      report_f_html <- tagList(
        tags$div(class = "custom-title-bold", title),
        tags$p("This sampling scheme employs simple random sampling without replacement at the first stage for the selection of clusters, followed by a complete enumeration (census) of all units within each selected cluster."),
        P1,
        descriptionT_div,
        descriptionT2_div
      )
      
    } else{
      if (input$Type_pc == "Infinite Population") {
        texts <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The confidence level : ",
          "The estimated proportion of the studied characteristic : ",
          "The absolute precision :",
          "The average cluster size:",
          "The design effect:"
          
        )
        
        title <- "Sample Size for Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters"
        dynamics <- c("","ni_valuepp","niclu_valuepp", "conf_valuepp","var_valuepp", "prec_valuepp","CSUS_valuepp",
                      "def_valuepp")
      }else{
        texts <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The total number of clusters in the population:",
          "The confidence level: ",
          "The estimated proportion of the studied characteristic: ",
          "The absolute precision:",
          "The average cluster size",
          "The design effect:"
          
        )
        size_c<-  c("The average cluster size:")
        title <- "Sample Size for Estimating a Proportion with Single-Stage Cluster Sampling and Finite Number of Clusters"
        dynamics <- c("","ni_valuepp","niclu_valuepp","N_valuepp", "conf_valuepp","var_valuepp",
                      "prec_valuepp","CSUS_valuepp",  "def_valuepp")
      }
      P1 <- generate_dynamic_lines(dynamics, texts)
      report_f_html <- tagList(
        tags$div(class = "custom-title-bold", title),
        tags$p("This sampling scheme employs simple random sampling without replacement at the first stage for the selection of clusters, followed by a complete enumeration (census) of all units within each selected cluster."),
        P1,
        descriptionT_div,
        descriptionT2_div
      )
      
    }
    
    return(report_f_html)
    
  })
  ############ Start equations proportion
  output$equapc <- renderUI({
    # Depending on the type of population, define the corresponding equations and paragraphs
    if (input$Type_pc == "Infinite Population") {
      equations <- c("","$$n_0 = \\frac{p(1-p) z_{(\\alpha/2)}^2}{e^2} deff$$","$$deff=1+(\\bar{M}-1)IIC$$","$$n_c=\\frac{n_0}{\\bar{M}}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate a proportion:", "and","and" )
      paragraphs2 <- c("Where:",
                       "is the estimated total sample size to estimate a proportion.",
                       "is the number of clusters to be included in the sample.",
                       "is the estimator of the population proportion.",
                       "is the z-score corresponding to the desired confidence level.",
                       "is the maximum permissible absolute error (or desired absolute precision).",
                       "is the design effect",
                       "is the Intracluster correlation.",
                       "is the average of the number of elementary units per cluster."
      )
      # Definition of additional explanatory equations
      equations2 <- c(
        "$$ $$",
        "$$n_0$$",
        "$$n_c$$",
        "$$p$$",
        "$$z_{(\\alpha/2)}$$",
        "$$e$$",
        "$$deff$$",
        "$$ICC$$",
        "$$\\bar{M}$$"
      )
      
      title <- "Equation of Sample Size Calculation for Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters."
      
    }else{
      equations <- c("","$$n = \\frac{N p (1-p) z_{(\\alpha/2)}^2}{N e^2 + p (1-p) z_{(\\alpha/2)}^2} deff$$","$$deff=1+(\\bar {M}-1)IIC$$","$$n_c=\\frac{n_0}{\\bar{M}}$$")
      paragraphs <- c("","Equation for calculating the sample size to estimate a proportion:", "and", "and")
      
      # Definition of additional explanatory paragraphs
      paragraphs2 <- c("Where:",
                       "is the estimated total sample size to estimate a proportion.",
                       "is the number of clusters to be included in the sample.",
                       "is the total number of clusters in the population.",
                       "is the estimator of the population proportion.",
                       "is the z-score corresponding to the desired confidence level.",
                       "is the maximum permissible absolute error (or desired absolute precision).",
                       "is the design effect.",
                       "is the Intracluster correlation.",
                       "is the average of the number of elementary units per cluster."
      )
      
      # Definition of additional explanatory equations
      equations2 <- c(
        "$$ $$",
        "$$n_0$$",
        "$$n_c$$",
        "$$N$$",
        "$$p$$",
        "$$z_{(\\alpha/2)}$$",
        "$$e$$",
        "$$deff$$",
        "$$ICC$$",
        "$$\\bar{M}$$"
      )
      
      title <- "Equation of Sample Size Calculation for Estimating a Proportion with Single-Stage Cluster Sampling and Finite Number of Clusters."
    }
    report_html <- tags$div()
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ############ Start additional information proportion
  output$informpc <- renderUI({
    if (input$Type_pc == "Infinite Population") {
      equations <- c(
        "",
        "$$\\hat{p_i} = \\frac{1}{M_i} \\sum_{h=1}^{M_i} y_{ih}$$",
        "$$ y_{ih} =
            \\begin{cases}
            1 & \\text{If the characteristic of interest is present} \\\\
            0 & \\text{If the characteristic of interest is not present}
           \\end{cases}
           $$",
        "$$\\hat{p} = \\frac{\\sum_{i=1}^{n_c} M_i\\hat{p_i}}{\\sum_{i=1}^{n_c} {M_i}}$$",
        
        "$$\\hat{V}(\\hat{p}) = \\frac{1}{n_c(n_c-1)} \\sum_{i=1}^{n_c} M_i^2\\left(\\hat{p_i}-\\hat{p}\\right)^2$$")
      paragraphs <- c("",
                      "Estimator of the proportion of cluster i",
                      "Where: ",
                      "Estimator of the population proportion",
                      "Estimator of the variance of the estimator of the population proportion")
      paragraphs2 <- c("Where:",
                       "is the estimator of the proportion of cluster i.",
                       "is the estimator of the population proportion.",
                       "is the estimator of the variance of the estimator of the population proportion.",
                       "is the number of clusters in the sample.",
                       "is the number of elementary units in cluster i (Cluster size).")
      
      
      equations2 <- c("$$ $$",
                      "$$\\hat{p_i}$$",
                      "$$\\hat{p}$$",
                      "$$\\hat{V}(\\hat{p})$$",
                      "$$n_c$$",
                      "$$M_i$$")
      
      title <- "Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters."
    }else {
      equations <- c(
        "",
        "$$\\hat{p_i} = \\frac{1}{M_i} \\sum_{h=1}^{M_i} y_{ih}$$",
        "$$ y_{ih} =
            \\begin{cases}
            1 & \\text{If the characteristic of interest is present} \\\\
            0 & \\text{If the characteristic of interest is not present}
           \\end{cases}
           $$",
        "$$\\hat{p} = \\frac{\\sum_{i=1}^{n_c} M_i\\hat{p_i}}{\\sum_{i=1}^{n_c} {M_i}}$$",
        
        "$$\\hat{V}(\\hat{p}) = \\left(1 - \\frac{n_c}{M} \\right) \\cdot\\frac{1}{n_c(n_c-1)} \\sum_{i=1}^{n_c} M_i^2\\left(\\hat{p_i}-\\hat{p}\\right)^2$$")
      paragraphs <- c("",
                      "Estimator of the proportion of cluster i",
                      "Where: ",
                      "Estimator of the population proportion",
                      "Estimator of the variance of the estimator of the population proportion")
      paragraphs2 <- c("Where:",
                       "is the estimator of the proportion of cluster i.",
                       "is the estimator of the population proportion.",
                       "is the estimator of the variance of the estimator of the population proportion.",
                       "is the number of clusters in the sample.",
                       "is the number of elementary units in cluster i (Cluster size).",
                       "is the total number of clusters in the population.")
      
      
      equations2 <- c("$$ $$",
                      "$$\\hat{p_i}$$",
                      "$$\\hat{p}$$",
                      "$$\\hat{V}(\\hat{p})$$",
                      "$$n_c$$",
                      "$$M_i$$",
                      "$$M$$")
      
      title <- "Estimating a Proportion with Single-Stage Cluster Sampling and Finite Number of Clusters."
      
    }
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title) #title_html <- tags$h4(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    return(report_f_html)
  })
  ################# Start example proportion
  output$examplepc <- renderUI({
    # Define the content of the example
    
    if (input$Type_pc == "Finite Population") {
      example_title <- "Example: Estimating a Proportion with Single-Stage Cluster Sampling and Finite Number of Clusters" 
      example_description <- paste(
        "A city is divided into 600 blocks (clusters), each with approximately the same number",
        "of households. The goal is to estimate the proportion of households that have internet",
        "access."
        
      )
      example_description2 <- paste(
        "A single-stage cluster sampling design is to be used: a number of blocks will be selected",
        "at random, and all households within each selected block will be surveyed."
      )
      example_description3 <- paste(
        "It is desired that the margin of error for the estimate does not exceed 4 percentage",
        "points (i.e., 0.04), with a 95% confidence level. "
      )
      example_description4 <- paste(
        "Previous studies suggest that the proportion of households with internet access is",
        "approximately 0.8, and the intra-cluster correlation coefficient (ρ) is around 0.01,",
        "with 100 households per block."
      )
      example_description5 <- paste(
        "How many blocks (clusters) must be selected to satisfy the desired level of precision?"
      )
      example_description6 <- paste(
        " "
      )
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating a Proportion with Single-Stage Cluster Sampling and Finite Number of Clusters"
      if (input$method_pc == "Using intracluster correlation") {
        example_result <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The total number of clusters in the population:",
          "The Confidence level :",
          "The estimated proportion of of the studied characteristic:",
          "The absolute precision:",
          "The Intracluster correlation",
          "The Average cluster size",
          "The design effect:"
          
        )
        result_numbers <- c("",467,5, 600, 95, 0.8,0.04,0.01,100,1.99)
      }else{ 
        example_title <- "Example: Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters"
        example_result <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The total number of clusters in the population:",
          "The Confidence level :",
          "The estimated proportion of of the studied characteristic:",
          "The absolute precision:",
          
          "The Average cluster size",
          "The design effect:"
          
        )
        result_numbers <- c("",467,5, 600, 95, 0.8,0.04,100,1.99)
        
        
      }
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(example_description2)),
        tags$p(HTML(example_description3)),
        tags$p(HTML(example_description4)),
        tags$p(HTML(example_description5)),
        tags$p(HTML(example_description6)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description3.5)),
        table_html,
        tags$div(descriptionT),
        tags$div(descriptionT2)
      )
      
      return(example_html)
    } else {
      example_title <- "Example: Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters" 
      example_description <- paste(
        "A public health agency aims to estimate the proportion of students in rural schools",
        "who have received at least one dose of a certain vaccine. The region under study contains",
        "thousands of rural schools (considered infinite for sampling purposes), and each school",
        "has approximately 100 students."
      )
      example_description2 <- paste(
        "The agency plans to use single-stage cluster sampling, where entire schools are selected",
        "at random, and all students in each selected school are surveyed."
      )
      example_description3 <- paste(
        "From past experience, the expected proportion of vaccinated students is about 0.8,",
        "and the intra-cluster correlation coefficient (ρ) is approximately 0.01. The agency",
        "wants the estimate to have a margin of error of no more than 4 percentage points (0.04)",
        "at a 95% confidence level."
      )
      example_title2 <- "Result:"
      example_title3 <- "Sample Size for Estimating a Proportion with Single-Stage Cluster Sampling and Infinite Number of Clusters"
      if (input$method_pc == "Using intracluster correlation") {
        example_result <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The confidence level :",
          "The estimated proportion of the studied characteristic :",
          "The absolute precision :",
          "The intracluster correlation :",
          "The average cluster size :",
          "The design effect :"
          
        )
        result_numbers <- c("",765,8, 95,0.8, .04, 0.01, 100, 1.99)
      }else{
        example_result <- c(
          "",
          "The estimated total sample size:",
          "The number of clusters in the sample:",
          "The confidence level :",
          "The estimated proportion of the studied characteristic :",
          "The absolute precision :",
          
          "The average cluster size :",
          "The design effect :"
          
        )
        result_numbers <- c("",765,8, 95,0.8, .04, 100, 1.99)
      }
      table_html <- tags$table(
        lapply(seq_along(example_result), function(i) {
          result_html <- HTML(example_result[i])
          text_html <- HTML(result_numbers[i])
          tags$tr(
            tags$td(result_html, style = "padding-right: 20px;"),
            tags$td(text_html)
          )
        })
      )
      
      blanco<- " "
      example_html <- tags$div(
        title_html <- tags$div(class = "custom-title-bold", example_title),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description)),
        tags$p(HTML(example_description2)),
        tags$p(HTML(example_description3)),
        tags$p(HTML(blanco)),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title2),
        tags$p(HTML(blanco)),
        tags$div(class = "custom-title-bold",example_title3),
        tags$p(HTML(blanco)),
        tags$p(HTML(example_description3.5)),
        table_html,
        tags$div(descriptionT),
        tags$div(descriptionT2)
      )
      
      return(example_html)
    }
  })
  ##########################################################################################
  ################################################ Start cluster single stage with the total
  ##########################################################################################
  ############ Start summary total
  output$summarytc <- renderUI({
    output$conf_valuett <- renderText({ input$Confidence_tc })
    output$prec_valuett <- renderText({ input$Precision_tc})
    output$var_valuett <- renderText({ input$Variance_tc })
    output$CSUS_valuett <- renderText({ input$CSUS_tc })
    output$ICC_valuett <- renderText({ input$ICC_tc })
    output$N_valuett <- renderText({ input$N_tc })
    Ntt <- input$N_tc
    confidencett <- input$Confidence_tc
    precisiontt <- input$Precision_tc
    variancett <- input$Variance_tc
    alphatt <- (1 - confidencett / 100) / 2
    ztt <- qnorm(alphatt, lower.tail = FALSE)
    CSUStt <- input$CSUS_tc
    if (input$method_pc == "Using intracluster correlation") {
      
      ICCtt <- input$ICC_tc
      deftt <- 1 + (CSUStt - 1) * ICCtt
    } else {
      deftt <-input$deff_tc
    }
    nitt <- ((Ntt^2) * variancett * (ztt^2)) / (precisiontt^2 +  variancett * (ztt^2))
    nitt <- ceiling(nitt*deftt)
    nittclu<-ceiling(nitt/CSUStt)
    output$ni_valuett <- renderText(nitt)
    output$nic_valuett <- renderText(nittclu)
    output$def_valuett <- renderText( deftt )
    
    if (input$method_tc == "Using intracluster correlation") {
      texts <- c(
        "",
        "The estimated total sample size to estimate the total:",
        "The number of clusters to be included in the sample:",
        "The total number of clusters: ",
        "The confidence level: ",
        "The estimated variance of the characteristic of interest:",
        "The absolute precision: ",
        "The intracluster correlation:",
        "The average cluster size:",
        
        "The design effect:"
      )
      
      title <- "Sample Size for Estimating the Total with Single-Stage Cluster Sampling and Finite Number of Cluster."
      dynamics <- c("", "ni_valuett","nic_valuett","N_valuett", "conf_valuett", "var_valuett", "prec_valuett","ICC_valuett","CSUS_valuett","def_valuett")
    }else{
      texts <- c(
        "",
        "The estimated total sample size to estimate the total:",
        "The estimated total sample sample size number of clusters in the sample:",
        "The total number of clusters in the population: ",
        "The confidence level: ",
        "The estimated variance of the characteristic of interest:",
        "The absolute precision: ",
        "The average cluster size:",
        "The design effect:"
      )
      
      title <- "Sample Size for Estimating the Total with Single-Stage Cluster Sampling and Finite Number of Cluster."
      dynamics <- c("", "ni_valuett","nic_valuett","N_valuett", "conf_valuett", "var_valuett", "prec_valuett","CSUS_valuett","def_valuett")
    }
    
    lines <- lapply(seq_along(dynamics), function(i) {
      fluidRow(
        column(10, tags$p(HTML(texts[i]))),
        column(2, textOutput(dynamics[i]))
      )
    })
    P1 <- do.call(tagList, lines)
    
    report_f_html <- tagList(
      tags$div(class = "custom-title-bold", title),
      tags$p("This sampling scheme employs simple random sampling without replacement at the first stage for the selection of clusters, followed by a complete enumeration (census) of all units within each selected cluster."),
      P1,
      descriptionT_div,
      descriptionT2_div
    )
    
    
    
    return(report_f_html)
  })
  ############ Start equations total
  output$equatc <- renderUI({
    equations <- c("","$$n_0 = \\frac{N^2 S^2 z_{(\\alpha/2)}^2}{e^2 + S^2 z_{(\\alpha/2)}^2}deff$$","$$deff=1+(\\bar{M}-1)IIC$$","$$n_c=\\frac{n_0}{\\bar{M}}$$")
    paragraphs <- c("","Equation for calculating the sample size to estimate the total of a finite population:","and","and" )
    
    paragraphs2 <- c(
      "Where:",
      "is the estimated total sample size to estimate the total.",
      "is the number of clusters to be included in the sample to estimate the total of a finite population.",
      "is the total number of clusters in the population.",
      "is the estimated variance of the characteristic of interest.",
      "is the z-score corresponding to the desired confidence level.",
      "is the maximum permissible absolute error (or desired absolute precision).",
      "is the design effect",
      "is the Intracluster correlation"
    )
    
    equations2 <- c("$$ $$", "$$n_0$$","$$n_c$$", "$$N$$", "$$S^2$$", "$$z_{(\\alpha/2)}$$", "$$e$$", "$$deff$$","$$ICC$$")
    
    # Combine the equations and paragraphs into the UI components
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    
    report_f_html <- tags$div()
    title<-"Equation of Sample Size Calculation for Estimating the Total with Single-Stage Cluster Sampling and Finite Number of Cluster."
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ############ Start additional information total
  output$informtc <- renderUI({
    
    equations <- c(
      "",
      "$$\\bar{y_i} = \\frac{1}{M_i} \\sum_{h=1}^{M_i} y_{ih}$$",
      "$$\\bar{\\bar{y}} = \\frac{\\sum_{i=1}^{n_c} M_i\\bar{y_i}}{\\sum_{i=1}^{n_c} {M_i}}$$",
      "$$\\hat{t} = M\\bar{\\bar{y}}$$",
      "$$\\hat{V}(\\hat{t}) = \\left(1 - \\frac{n_c}{M} \\right) \\cdot\\frac{M^2}{n_c(n_c-1)} \\sum_{i=1}^{n_c} \\left(\\bar{y_i}-\\bar{\\bar{y}}\\right)^2$$"
    )
    paragraphs <- c(
      "",
      "Estimator of the mean of cluster i",
      "Estimator of the population mean (Horwitz-Thompson estimator)",
      "Estimator of the population total:",
      "Estimator of the variance of the estimator of the population total:"
    )
    
    paragraphs2 <- c("Where:",
                     "is the estimator of the mean of cluster i.",
                     "is the value of observation h from stratum i.",
                     "is the estimator of the population mean.",
                     "is the estimator of the total.",
                     "is the estimator of the variance of the estimator of the population total.",
                     "is the number of elementary units in cluster i (Cluster size).",
                     "is the number of clusters in the sample.",
                     "is the number of clusters in the population."
    )
    equations2 <- c("$$ $$",
                    "$$\\bar{y_i}$$",
                    "$$y_{ih}$$",
                    "$$\\bar{\\bar{y}}$$",
                    "$$\\hat{t}$$",
                    "$$\\hat{V}(\\hat{t})$$",
                    "$$M_i$$",
                    "$$n_c$$",
                    "$$M$$"
    )
    
    title <- "Estimating the Total with with Single-Stage Cluster Sampling and Finite Number of Cluster."
    
    P1 <- generate_text_with_equation(equations, paragraphs)
    P2 <- generate_text_with_equation_1(equations2, paragraphs2)
    report_f_html <- tags$div()
    title_html <- tags$div(class = "custom-title-bold", title)#tags$h5(title)
    report_f_html <- tagAppendChild(report_f_html, title_html)
    report_f_html <- tagAppendChild(report_f_html, P1)
    report_f_html <- tagAppendChild(report_f_html, P2)
    
    return(report_f_html)
  })
  ################# Start example total
  output$exampletc <- renderUI({
    example_title <- "Example: Estimating the Total with Single-Stage Cluster Sampling and Finite Number of Clusters"
    example_description <- paste(
      "A research company wants to estimate the total revenue generated by a supermarket chain",
      "in a specific region over a year. This supermarket chain has 500 branches throughout the",
      "region. On average, each branch performs 30 daily transactions."
    )
    example_description2 <- paste(
      "The company plans to use a",
      "cluster sampling design, where each branch is considered a cluster, and each daily transaction",
      "is an observation unit."
    )
    example_description3 <- paste(
      "The following historical data on daily revenues is available:"
    )
    example_description4 <- paste(
      "The variance estimated of the daily revenues is 100"
    )
    example_description5 <- paste(
      "The intracluster correlation is 0.05"
    )
    example_description6 <- paste(
      "The company wants the estimate to have a margin of error of $1000 in the total annual revenue",
      "estimate for the entire region and seeks a confidence level of 95%"
    )
    example_title2 <- "Result:"
    example_title3 <- "Sample Size for Estimating the Mean for Estimating the Total with Single-Stage Cluster Sampling and Finite Number of Cluster."
    if (input$method_tc == "Using intracluster correlation") {
      example_result <- c(
        "",
        "The estimated total sample size to estimate the total:",
        "The number of clusters in the sample:",
        "The total number of clusters:",
        "The confidence level :",
        "The estimated variance of the characteristic of interest:",
        "The absolute precision:",
        "The intracluster correlation",
        "The average cluster size",
        "The design effect:"
      )
      result_numbers <- c("",236,8, 500,95,100,1000, 0.05, 30, 2.45)
    }else {
      example_result <- c(
        "",
        "The estimated total sample size to estimate the total:",
        "The number of clusters in the sample:",
        "The total number of clusters:",
        "The confidence level :",
        "The estimated variance of the characteristic of interest:",
        "The absolute precision:",
        "The average cluster size",
        "The design effect:"
      )
      result_numbers <- c("",236,8, 500,95,100,1000, 30, 2.45)
    }
    table_html <- tags$table(
      lapply(seq_along(example_result), function(i) {
        result_html <- HTML(example_result[i])
        text_html <- HTML(result_numbers[i])
        tags$tr(
          tags$td(result_html, style = "padding-right: 20px;"),
          tags$td(text_html)
        )
      })
    )
    
    blanco<- " "
    example_html <- tags$div(
      title_html <- tags$div(class = "custom-title-bold", example_title),#tags$h5(title) tags$h4(example_title),
      tags$p(HTML(blanco)),
      tags$p(HTML(example_description)),
      tags$p(HTML(example_description2)),
      tags$p(HTML(example_description3)),
      tags$p(HTML(example_description4)),
      tags$p(HTML(example_description5)),
      tags$p(HTML(example_description6)),
      
      tags$p(HTML(blanco)),
      tags$p(HTML(blanco)),
      tags$div(class = "custom-title-bold",example_title2),
      tags$p(HTML(blanco)),
      tags$div(class = "custom-title-bold",example_title3),
      tags$p(HTML(blanco)),
      tags$p(HTML(example_description3.5)),
      table_html,
      tags$div(descriptionT),
      tags$div(descriptionT2)
    )
    
    return(example_html)
  })
}

shinyApp(ui = ui, server = server)
