# ============================================================
# 1. CALCULATE SELECTION INDEX
# ============================================================

# Function to calculate index for any population
calc_index <- function(gv, lambda) {
  
  # Mean performance across environments
  mean_gv <- rowMeans(gv)
  
  # Variance of genetic values across environments
  stability <- apply(gv, 1, var)
  
  # Selection index
  data.frame(
    mean_gv = mean_gv,
    stability = stability,
    index = mean_gv - lambda * sqrt(stability)
  )
}


# ============================================================
# 2. FIND BEST GENOTYPES
# ============================================================

best_results <- list()
best_profiles <- list()
counter <- 1

for (scen in names(lambda_scenarios)) {
  
  lambda <- lambda_scenarios[[scen]]
  
  for (rep in seq_len(nRep)) {
    
    # Compare all populations when evaluating mean performance
    if (scen == "zero") {
      pops_to_compare <- names(lambda_scenarios)
    } else {
      pops_to_compare <- c("zero", scen)
    }
    
    for (pop in pops_to_compare) {
      
      gv <- final_pops[[pop]][[rep]]
      
      # Evaluate with same index
      scores <- calc_index(gv, lambda)
      
      # Identify highest ranking genotype
      best <- which.max(scores$index)
      
      # Save its index components
      best_results[[counter]] <- data.frame(
        scenario = scen,
        rep = rep,
        population = pop,
        genotype = best,
        scores[best, ]
      )
      
      # Save its genetic values across environments
      best_profiles[[counter]] <- data.frame(
        scenario = scen,
        rep = rep,
        population = pop,
        genotype = best,
        environment = paste0("Env", seq_len(nEnv)),
        gv = as.numeric(gv[best, ])
      )
      
      counter <- counter + 1
    }
  }
}

best_df <- bind_rows(best_results)
best_gv_df <- bind_rows(best_profiles)


best_df$scenario <- factor(best_df$scenario,
                           levels = c("high", "med", "low", "zero"))

best_gv_df$scenario <- factor(best_gv_df$scenario,
                              levels = c("high", "med", "low", "zero"))
# ============================================================
# 3. SUMMARISE BEST INDEX VALUES
# ============================================================

# Order scenarios and populations
scenario_order <- c("zero", "low", "med", "high")

best_df$scenario <- factor(best_df$scenario,
                           levels = scenario_order)
best_df$population <- factor(best_df$population,
                             levels = scenario_order)

best_gv_df$scenario <- factor(best_gv_df$scenario,
                              levels = scenario_order)
best_gv_df$population <- factor(best_gv_df$population,
                                levels = scenario_order)

# Colours for each breeding population
pop_colours <- c(
  zero = "steelblue",
  low  = "forestgreen",
  med  = "orange",
  high = "firebrick"
)

best_summary <- best_df %>%
  group_by(scenario, population) %>%
  summarise(
    mean_index = mean(index),
    se_index = sd(index) / sqrt(n()),
    .groups = "drop"
  )


# ============================================================
# 4. PLOT BEST INDEX VALUES
# ============================================================

best_genotype_index <- ggplot(
  best_summary,
  aes(x = scenario, y = mean_index,
      colour = population, group = population)
) +
  geom_point(size = 3,
             position = position_dodge(width = 0.5)) +
  geom_errorbar(
    aes(ymin = mean_index - se_index,
        ymax = mean_index + se_index),
    width = 0.15,
    position = position_dodge(width = 0.5)
  ) +
  scale_colour_manual(values = pop_colours) +
  labs(
    x = "Stability index evaluated",
    y = "Best genotype index value",
    colour = "Breeding population",
    title = "Does selecting for stability produce better genotypes?"
  ) +
  theme_bw()


# ============================================================
# 5. GENETIC VALUES OF BEST GENOTYPES
# ============================================================

best_gv_summary <- best_gv_df %>%
  group_by(scenario, population, environment) %>%
  summarise(
    mean_gv = mean(gv),
    .groups = "drop"
  )

best_genotype_envs <- ggplot(
  best_gv_summary,
  aes(x = environment, y = mean_gv,
      colour = population, group = population)
) +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  facet_wrap(~ scenario) +
  scale_colour_manual(values = pop_colours) +
  labs(
    x = "Environment",
    y = "Genetic value of best genotype",
    colour = "Breeding population",
    title = "Environmental performance of best genotypes"
  ) +
  theme_bw()



