#' @noRd
bootstrap.ml <- function(nboot, size1, size2, td, start.vals, ages, size0, model, seed=1701,fixed.A,optimizer="L-BFGS-B") {
  set.seed(seed)
  n <- length(size1)

  if (is.null(fixed.A)) {
    ssq.lower <- c(1e-6, 1e-6)
    ml.lower  <- c(1e-6, 1e-6, 1e-6)
  } else {
    ssq.lower <- c(1e-6)
    ml.lower  <- c(1e-6, 1e-6)
  }


  boot_params <- matrix(NA, nrow = nboot, ncol = 3,          # 3 not 2 — now includes sigma
                        dimnames = list(NULL, c("A", "k", "sigma")))
  boot_preds <- matrix(NA, nrow = nboot, ncol = length(ages))

  for (b in 1:nboot) {
    idx    <- sample(1:n, replace = TRUE)
    size1_b <- size1[idx]; size2_b <- size2[idx]; td_b <- td[idx]

    # --- Stage 1: SSQ for robust starting values ---

    if(is.null(fixed.A)==TRUE){
      fit_ssq <- try(
        optim(start.vals[c("A","k")], ssq,  size1 = size1_b, size2 = size2_b, td = td_b,  method = optimizer, lower = ssq.lower,model=model,fixed.A=fixed.A),
        silent = TRUE)}else{
          fit_ssq <- try(
            optim(start.vals[c("k")], ssq,  size1 = size1_b, size2 = size2_b, td = td_b,  method = optimizer, lower = ssq.lower,model=model,fixed.A=fixed.A),
            silent = TRUE)}

    if (inherits(fit_ssq, "try-error")) next   # skip to next bootstrap replicate

    ml.start <- if(is.null(fixed.A)==TRUE){c(fit_ssq$par[1],fit_ssq$par[2],sigma=sqrt(fit_ssq$value/n))}else{
      c(fit_ssq$par[1],sigma=sqrt(fit_ssq$value/n)) }

    # --- Stage 2: ML fit ---
    fit_ml <- try(
      optim(ml.start, ml,
            size1 = size1_b, size2 = size2_b, td = td_b,
            method = optimizer, lower = ml.lower,model=model,fixed.A=fixed.A),
      silent = TRUE)

    if (inherits(fit_ml, "try-error")) next


    if(is.null(fixed.A)==TRUE){
      A_b <-fit_ml$par[1]
      k_b     <- fit_ml$par[2]
      sigma_b <- fit_ml$par[3]}else{
        A_b <- fixed.A
        k_b     <- fit_ml$par[1]
        sigma_b <- fit_ml$par[2]}

    boot_params[b, ] <- c(A_b, k_b, sigma_b)
    boot_preds[b, ]  <- size.at.age(A_b, k_b, ages, size0,model=model)
  }

  pred_lower <- apply(boot_preds, 2, quantile, probs = 0.025, na.rm = TRUE)
  pred_upper <- apply(boot_preds, 2, quantile, probs = 0.975, na.rm = TRUE)

  ci <- cbind.data.frame(ages = ages, upper = pred_upper, lower = pred_lower)

  ci_params <- data.frame(
    param = c("A", "k", "sigma"),
    est   = apply(boot_params, 2, median,   na.rm = TRUE),
    lower = apply(boot_params, 2, quantile, probs = 0.025, na.rm = TRUE),
    upper = apply(boot_params, 2, quantile, probs = 0.975, na.rm = TRUE),
    n_successful = apply(boot_params, 2, function(x) sum(!is.na(x)))
  )

  list(size.ci = ci,params.ci = ci_params)
}
