# T-Value Analysis: Four Brain Regions Integration

# Load required packages
pacman::p_load(
  tidyverse,
  gt,
  psych,
  ggdist,
  gghalves,
  patchwork)

# Data Loading and Integration

# Set base directory path
base_dir <- "/Users/tohokusla/Dropbox/fMRI_VWFA/Python_Code_Komuro/20251019/Results"

# Define file paths for all four brain regions
file_paths <- list(
  Left_Fusiform = file.path(base_dir, "Left_Fusiform_default_thr04_patch4mm/Localizer_ROI_Results/Group/All_subjects_BEST_clusters.csv"),
  Left_Occipital_Fusiform = file.path(base_dir, "Left_Occipital_Fusiform_default_thr04_patch4mm/Localizer_ROI_Results/Group/All_subjects_BEST_clusters.csv"),
  Right_Fusiform = file.path(base_dir, "Right_Fusiform_default_thr04_patch4mm/Localizer_ROI_Results/Group/All_subjects_BEST_clusters.csv"),
  Right_Occipital_Fusiform = file.path(base_dir, "Right_Occipital_Fusiform_default_thr04_patch4mm/Localizer_ROI_Results/Group/All_subjects_BEST_clusters.csv"))


# Load data and add brain region label
data_list <- map2(file_paths, names(file_paths), function(path, roi_name) {
  read_csv(path, show_col_types = FALSE) |>
    mutate(brain_region = roi_name)
})

# Combine all data
combined_data <- bind_rows(data_list)

# Extract cross-language responses
cross_language <- combined_data |>
  select(subject_id, language, brain_region, peak_x, peak_y, peak_z,
         mean_t_English, mean_t_Kanji, mean_t_Katakana,
         peak_t_English, peak_t_Kanji, peak_t_Katakana) |>
  rename(roi_language = language) |>
  pivot_longer(
    cols = starts_with("mean_t_"),
    names_to = "stimulus_language",
    values_to = "mean_t_value",
    names_prefix = "mean_t_") |>
  pivot_longer(
    cols = starts_with("peak_t_"),
    names_to = "stim_lang_peak",
    values_to = "peak_t_value",
    names_prefix = "peak_t_") |>
  filter(stimulus_language == stim_lang_peak) |>
  select(-stim_lang_peak) |>
  filter(!is.na(mean_t_value)) |>
  mutate(condition_type = "Cross Language")

# Extract same-language responses from mean_t column
same_language <- combined_data |>
  select(subject_id, language, brain_region, peak_x, peak_y, peak_z,
         mean_t, peak_t) |>
  rename(
    roi_language = language,
    mean_t_value = mean_t,
    peak_t_value = peak_t) |>
  mutate(
    stimulus_language = roi_language,
    condition_type = "Same Language")

# Combine both datasets
long_data <- bind_rows(cross_language, same_language) |>
  mutate(
    roi_stim_pair = paste0(roi_language, " ROI × ", stimulus_language, " Stim"),
    brain_region = factor(brain_region, levels = c(
      "Left_Fusiform",
      "Left_Occipital_Fusiform",
      "Right_Fusiform",
      "Right_Occipital_Fusiform")),
    roi_language = factor(roi_language, levels = c("English", "Kanji", "Katakana")),
    stimulus_language = factor(stimulus_language, levels = c("English", "Kanji", "Katakana")),
    condition_type = factor(condition_type, levels = c("Same Language", "Cross Language")))

# Define color palette for brain regions
region_colors <- c(
  "Left_Fusiform" = "#E74C3C",
  "Left_Occipital_Fusiform" = "#F39C12",
  "Right_Fusiform" = "#3498DB",
  "Right_Occipital_Fusiform" = "#9B59B6")

# Mean T-values with both conditions (using shapes to distinguish)
long_data |>
  group_by(brain_region, roi_language, stimulus_language, condition_type) |>
  summarise(
    mean_t = mean(mean_t_value, na.rm = TRUE),
    se_t = sd(mean_t_value, na.rm = TRUE) / sqrt(n()),
    .groups = "drop") |> 
  ggplot(aes(x = stimulus_language, y = mean_t, 
             color = brain_region, group = brain_region)) +
  geom_line(linewidth = 1, position = position_dodge(width = 0.2)) +
  geom_point(aes(shape = condition_type), size = 3.5, 
             position = position_dodge(width = 0.2)) +
  geom_errorbar(aes(ymin = mean_t - se_t, ymax = mean_t + se_t),
                width = 0.2, linewidth = 0.8, 
                position = position_dodge(width = 0.2)) +
  facet_wrap(~ roi_language, ncol = 3, scales = "free_y") +
  scale_color_manual(values = region_colors, name = "Brain Region") +
  scale_shape_manual(values = c("Same Language" = 19, "Cross Language" = 17),
                     name = "Condition Type") +
  labs(
    title = "Mean T-Values: Same-Language vs. Cross-Language",
    subtitle = "Filled circles = Same Language, Triangles = Cross Language",
    x = "Stimulus Language",
    y = "Mean T-Value") +
  theme_bw(base_size = 12) +
  theme(
    legend.position = "top",
    legend.box = "vertical",
    legend.title = element_text(face = "bold"),
    strip.text = element_text(face = "bold", size = 11),
    strip.background = element_rect(fill = "gray90", color = NA),
    panel.grid.major.x = element_blank(),
    plot.title = element_text(face = "bold", size = 15),
    plot.subtitle = element_text(size = 11, color = "gray40"))