
library(dplyr)
library(ggplot2)

# ============================================================
# 1. CALCULATE MEAN GENETIC VALUES
# ============================================================

mean_gv <- results_df %>%
  group_by(scenario, rep, cycle, environment) %>%
  summarise(
    mean_gv = mean(gv),
    .groups = "drop"
  )

# ============================================================
# 2. CALCULATE GENETIC GAIN RELATIVE TO CYCLE 0
# ============================================================

gain_df <- mean_gv %>%
  group_by(scenario, rep, environment) %>%
  mutate(
    genetic_gain = mean_gv - mean_gv[cycle == 0]
  ) %>%
  ungroup()

# Add TPE average (equal weighting across environments)
gain_tpe <- gain_df %>%
  group_by(scenario, rep, cycle) %>%
  summarise(
    genetic_gain = mean(genetic_gain),
    .groups = "drop"
  ) %>%
  mutate(environment = "TPE")

gain_df <- bind_rows(gain_df, gain_tpe)

# Order environments
gain_df$environment <- factor(
  gain_df$environment,
  levels = c(paste0("Env", seq_len(nEnv)), "TPE")
)

# Average across replicates
gain_summary <- gain_df %>%
  group_by(scenario, cycle, environment) %>%
  summarise(
    mean_gain = mean(genetic_gain),
    sd_gain = sd(genetic_gain),
    .groups = "drop"
  )

# ============================================================
# 3. GENETIC GAIN OVER CYCLES
# ============================================================

gain_cycles <- ggplot(
  gain_summary,
  aes(x = cycle, y = mean_gain, colour = scenario)
) +
  geom_line(linewidth = 1) +
  geom_point(size = 1.5) +
  facet_wrap(~ environment) +
  labs(
    x = "Selection cycle",
    y = "Mean genetic gain",
    colour = "Selection scenario",
    title = "Genetic gain across selection cycles"
  ) +
  theme_bw()

# ============================================================
# 4. FINAL GENETIC GAIN ACROSS ENVIRONMENTS + TPE
# ============================================================

gain_final <- gain_summary %>%
  filter(cycle == max(cycle)) %>%
  ggplot(
    aes(x = environment, y = mean_gain,
        colour = scenario, group = scenario)
  ) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.5) +
  labs(
    x = "Environment",
    y = "Mean genetic gain",
    colour = "Selection scenario",
    title = "Final genetic gain across environments and TPE"
  ) +
  theme_bw()
