# ===========================
# Packages
# ===========================
library(dplyr)
library(tidyr)
library(ggplot2)
library(patchwork)   # install.packages("patchwork") if needed

# ===========================
# Data
# ===========================
df <- read.csv("U_SPACE_miniSPACE_Usability_final_withDemographics.csv")

# ===========================
# Harmonise factors
# ===========================
df <- df %>%
  mutate(
    # Gender -> Female/Male (Female left)
    Gender = case_when(
      is.numeric(Gender) ~ ifelse(Gender == 0, "Male", "Female"),
      Gender %in% c("0","1") ~ ifelse(Gender == "0", "Male", "Female"),
      TRUE ~ as.character(Gender)
    ),
    Gender = factor(Gender, levels = c("Female","Male")),
    
    # Supervision: 0=Supervised, 1=Unsupervised
    Supervision = case_when(
      is.numeric(Supervision) ~ ifelse(Supervision == 0, "Supervised", "Unsupervised"),
      Supervision %in% c("0","1") ~ ifelse(Supervision == "0", "Supervised", "Unsupervised"),
      TRUE ~ as.character(Supervision)
    ),
    Supervision = factor(Supervision, levels = c("Supervised","Unsupervised")),
    
    # Age group: prefer AgeGroup if present, else AgeGroup_coded
    AgeGroup_raw = if ("AgeGroup" %in% names(.)) AgeGroup else AgeGroup_coded
  ) %>%
  mutate(
    AgeGroup = if (all(levels(factor(AgeGroup_raw)) %in% c("0","1","2"))) {
      factor(AgeGroup_raw, levels = c("0","1","2"),
             labels = c("20-40","41-60","61-80"))
    } else {
      # if already labeled, just coerce and fix 61-90 -> 61-80
      factor(gsub("61\\s*[-–]\\s*90", "61-80", as.character(AgeGroup_raw)))
    },
    AgeGroup = factor(AgeGroup, levels = c("20-40","41-60","61-80"))
  )

# ===========================
# Unified theme: outer frame + horizontal grid only
# ===========================
theme_paper <- function(base_size = 20) {
  theme_classic(base_size = base_size) +
    theme(
      panel.border = element_rect(color = "black", fill = NA, linewidth = 0.9),
      
      # horizontal grid only
      panel.grid.major.y = element_line(color = "grey85", linewidth = 0.6),
      panel.grid.minor.y = element_line(color = "grey92", linewidth = 0.4),
      panel.grid.major.x = element_blank(),
      panel.grid.minor.x = element_blank(),
      
      axis.line  = element_line(color = "black", linewidth = 0.6),
      axis.ticks = element_line(color = "black", linewidth = 0.6),
      
      strip.text = element_text(face = "bold", size = base_size + 2),
      
      legend.title = element_blank(),
      legend.key = element_blank(),
      legend.background = element_blank(),
      legend.box.background = element_blank(),
      
      axis.title = element_text(size = base_size + 6),
      axis.text  = element_text(size = base_size + 4),
      legend.text = element_text(size = base_size + 4)
    )
}

# ===========================
# Colors (same as your Fig.6)
# ===========================
col_sup <- c("Supervised"   = "#46506B",  # pink/coral
             "Unsupervised" = "#E4B74F")  # teal

# ===========================
# Helper: mean ± SE plot
# ===========================
make_mean_se_plot <- function(data, outcome_col, ylab_text) {
  
  dat_sum <- data %>%
    filter(!is.na(.data[[outcome_col]]),
           !is.na(Gender), !is.na(Supervision), !is.na(AgeGroup)) %>%
    group_by(AgeGroup, Gender, Supervision) %>%
    summarise(
      n    = dplyr::n(),
      mean = mean(.data[[outcome_col]], na.rm = TRUE),
      se   = sd(.data[[outcome_col]],  na.rm = TRUE) / sqrt(n),
      .groups = "drop"
    )
  
  pd <- position_dodge(width = 0.35)
  
  ggplot(dat_sum, aes(x = Gender, y = mean, color = Supervision, group = Supervision)) +
    geom_line(position = pd, linewidth = 1.2) +
    geom_point(position = pd, size = 3.6) +
    geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
                  width = 0.10, position = pd, alpha = 0.95, linewidth = 0.8) +
    facet_wrap(~ AgeGroup, nrow = 1) +
    scale_color_manual(values = col_sup, drop = FALSE) +
    labs(x = "Gender", y = ylab_text) +
    theme_paper(base_size = 20) +
    theme(legend.position = "right")
}

# ===========================
# Build Fig.7 panels
# ===========================
p_sus  <- make_mean_se_plot(df, "sus_score",  "SUS")
p_nasa <- make_mean_se_plot(df, "nasa_score", "NASA-TLX score")

# ===========================
# Combine: SUS left + NASA right (shared legend)
# ===========================
p_fig7 <- p_sus + p_nasa +
  plot_layout(ncol = 2, guides = "collect") &
  theme(legend.position = "right")

print(p_fig7)

# Optional export:
# ggsave("Fig7_SUS_NASA_combined.png", p_fig7, width = 14, height = 5.5, dpi = 300)