# Load required libraries
pacman::p_load(pacman, tidyverse, tidyr, dplyr, readr, grid, gridExtra, ggplot2, RColorBrewer)

# Display colour choices, used to pick suitable colour schemes
#display.brewer.all()

# Load the 7 CSV files 
emotional_recognition <- read_csv("emotional_recognition_corrected.csv", col_types = cols(
  Recognized_Emotion = col_character(),
  Happy_Target = col_double(),
  Sad_Target = col_double(),
  Angry_Target = col_double()
))

birth_characteristics_hospital <- read_csv("birth_characteristics_hospital_corrected.csv", 
  col_types = cols(.default = col_double(), 
  Hospital = col_character()
))

multi_feature_ttests <- read_csv("multi_feature_ttests_corrected.csv", col_types = cols(
  Group = col_character(),
  Latency_Window = col_character(),
  Stimulus_Type = col_character(),
  Stimulus = col_character(),
  Electrode = col_character(),
  t_value = col_double(),
  significance = col_character(),
  mean = col_double(),
  SD = col_double(),
  CI_lower = col_double(),
  CI_upper = col_double()
))

oddball_ttests <- read_csv("oddball_ttests_corrected.csv", col_types = cols(
  Group = col_character(),
  Latency_Window = col_character(),
  Electrode = col_character(),
  t_value = col_double(),
  significance = col_character(),
  mean = col_double(),
  SD = col_double(),
  CI_lower = col_double(),
  CI_upper = col_double()
))

interaction_effects <- read_csv("interaction_effects_corrected.csv", col_types = cols(
  Latency_Window = col_character(),
  Stimulus = col_character(),
  Electrode1 = col_character(),
  Mean1 = col_double(),
  Electrode2 = col_character(),
  Mean2 = col_double(),
  p_value = col_double()
))

rm_anova_pvalues <- read_csv("rm_anova_pvalues_corrected.csv", col_types = cols(
  Latency_Window = col_character(),
  Stimulus1 = col_character(),
  Stimulus2 = col_character(),
  p_value = col_double()
))

rm_ancova_pvalues <- read_csv("rm_ancova_pvalues_corrected.csv", col_types = cols(
  Latency_Window = col_character(),
  Stimulus1 = col_character(),
  Stimulus2 = col_character(),
  p_value = col_double()
))

# Subtitle: Study Name
Subtitle <- "Clinical Trial: Repeated Parental Singing During Kangaroo Care Improved Neural Processing of Speech Sound Changes in Preterm Infants at Term Age"

# Viz 1: Emotional Recognition - Bar Plot
emotional_recognition_long <- emotional_recognition %>%
  pivot_longer(cols = ends_with("_Target"), names_to = "Target", values_to = "Percentage") %>%
  mutate(Target = gsub("_Target", "", Target))

ggplot(emotional_recognition_long, aes(x = Recognized_Emotion, y = Percentage, fill = Target)) +
  geom_bar(stat = "identity", position = "stack", color = "black") +
  scale_fill_brewer(palette = "Set1") +
  labs(title = "Plot 1: Emotional Recognition Test Results",
       subtitle = Subtitle,
       x = "Recognised Emotion",
       y = "Percentage (%)",
       caption = "Source: Supplementary Table 1") +
  theme_minimal() +
  theme(plot.title = element_text(face = "bold", size = 14),
        axis.text.x = element_text(angle = 45, hjust = 1),
        legend.position = "top")

# Viz 2: Birth Characteristics by Hospital - Box Plots for Key Metrics
birth_metrics <- birth_characteristics_hospital %>%
  select(Hospital, Gestational_weeks_mean, Weight_mean, Height_mean) %>%
  pivot_longer(cols = c(Gestational_weeks_mean, Weight_mean, Height_mean), 
               names_to = "Metric", values_to = "Value")

ggplot(birth_metrics, aes(x = Hospital, y = Value, fill = Hospital)) +
  geom_boxplot(alpha = 0.7) +
  facet_wrap(~ Metric, scales = "free_y", 
             labeller = labeller(Metric = c(Gestational_weeks_mean = "Gestational Weeks",
                                            Weight_mean = "Weight (g)",
                                            Height_mean = "Height (cm)"))) +
  scale_fill_manual(values = c("#FFB6C1", "#87CEEB")) +
  labs(title = "Plot 2: Birth Characteristics by Hospital",
       subtitle = Subtitle,
       x = "Hospital",
       y = "Value",
       caption = "Source: Supplementary Table 2") +
  theme_light() +
  theme(plot.title = element_text(face = "bold", size = 14),
        legend.position = "none")

# Viz 3: Multi-feature T-tests - Line Plot with Error Bars (Happy Stimulus, 200-300 ms)
multi_feature_subset <- multi_feature_ttests %>%
  filter(Stimulus == "Happy", Latency_Window == "200-300 ms")

ggplot(multi_feature_subset, aes(x = Electrode, y = mean, color = Group)) +
  geom_line(aes(group = Group), size = 1) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = CI_lower, ymax = CI_upper), width = 0.2, size = 0.8) +
  scale_color_manual(values = c("#FF4500", "#4682B4")) +
  labs(title = "Plot 3: Mean Responses for Happy Stimulus (200-300 ms)",
       subtitle = Subtitle,
       x = "Electrode",
       y = "Mean Response",
       caption = "Source: Supplementary Table 3a") +
  theme_classic() +
  theme(plot.title = element_text(face = "bold", size = 14))
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# Viz 4: Oddball T-tests - Line Plot with Error Bars (200-300 ms)
oddball_subset <- oddball_ttests %>%
  filter(Latency_Window == "200-300 ms")

ggplot(oddball_subset, aes(x = Electrode, y = mean, color = Group)) +
  geom_line(aes(group = Group), size = 1) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = CI_lower, ymax = CI_upper), width = 0.2, size = 0.8) +
  scale_color_manual(values = c("#FFD700", "#6A5ACD")) +
  labs(title = "Plot 4: Mean Responses in Oddball Paradigm (200-300 ms)",
       subtitle = Subtitle,
       x = "Electrode",
       y = "Mean Response",
       caption = "Source: Supplementary Table 3b") +
  theme_classic() +
  theme(plot.title = element_text(face = "bold", size = 14))

# Viz 5: Interaction Effects - Grouped Bar Plot
interaction_effects_long <- interaction_effects %>%
  pivot_longer(cols = c(Mean1, Mean2), names_to = "Electrode_Type", values_to = "Mean") %>%
  mutate(Electrode = if_else(Electrode_Type == "Mean1", Electrode1, Electrode2))

ggplot(interaction_effects_long, aes(x = Electrode, y = Mean, fill = Stimulus)) +
  geom_bar(stat = "identity", position = "dodge", color = "black") +
  scale_fill_brewer(palette = "Dark2") +
  labs(title = "Plot 5: Interaction Effects: Mean Responses by Electrode and Stimulus",
       subtitle = Subtitle,
       x = "Electrode",
       y = "Mean Response",
       caption = "Source: Supplementary Table 4") +
  theme_minimal() +
  theme(plot.title = element_text(face = "bold", size = 14),
        legend.position = "top")

# Viz 6: RM ANOVA P-values - Heatmap
ggplot(rm_anova_pvalues, aes(x = Stimulus2, y = Stimulus1, fill = p_value)) +
  geom_tile(color = "white") +
  scale_fill_gradient(low = "#CC3300", high = "#CCCCCC", limits = c(0, 0.05)) +
  facet_wrap(~ Latency_Window) +
  labs(title = "Plot 6: RM ANOVA P-values for Stimulus Main Effect",
       subtitle = Subtitle,
       x = "Stimulus 2",
       y = "Stimulus 1",
       caption = "Source: Supplementary Table 6") +
  theme_minimal() +
  theme(plot.title = element_text(face = "bold", size = 14),
        axis.text.x = element_text(angle = 45, hjust = 1))

# Viz 7: RM ANCOVA P-values - Heatmap
ggplot(rm_ancova_pvalues, aes(x = Stimulus2, y = Stimulus1, fill = p_value)) +
  geom_tile(color = "white") +
  scale_fill_gradient(low = "#0033FF", high = "#CCCCCC", limits = c(0, 0.05)) +
  labs(title = "Plot 7: RM ANCOVA P-values for Stimulus Main Effect (550-650 ms)",
       subtitle = Subtitle,
       x = "Stimulus 2",
       y = "Stimulus 1",
       caption = "Source: Supplementary Table 7") +
  theme_minimal() +
  theme(plot.title = element_text(face = "bold", size = 14),
        axis.text.x = element_text(angle = 45, hjust = 1))