# Mixed ANOVA Analysis for Domain Means
# EOHI Experiment Data Analysis - Domain Level Analysis
# Variables: NPast_mean_pref, NPast_mean_pers, NPast_mean_val, NPast_mean_life
#           NFut_mean_pref, NFut_mean_pers, NFut_mean_val, NFut_mean_life

# Load required libraries
library(tidyverse)
library(ez)
library(car)
library(nortest)      # For normality tests
library(ggplot2)      # For plotting
library(emmeans)      # For post-hoc comparisons

# Read the data
data <- read.csv("eohi1/exp1.csv")

# Display basic information about the dataset
print(dim(data))
print(length(unique(data$pID)))

# Check experimental conditions
print(table(data$GROUP, data$TEMPORAL_DO, data$ITEM_DO))

# Check what domain mean columns are available
domain_mean_cols <- colnames(data)[grepl("mean_(pref|pers|val|life)", colnames(data))]
print(domain_mean_cols)

# Verify the specific variables we need
required_vars <- c("NPast_mean_pref", "NPast_mean_pers", "NPast_mean_val", "NPast_mean_life",
                   "NFut_mean_pref", "NFut_mean_pers", "NFut_mean_val", "NFut_mean_life")

missing_vars <- required_vars[!required_vars %in% colnames(data)]
if (length(missing_vars) > 0) {
  print(paste("Warning: Missing variables:", paste(missing_vars, collapse = ", ")))
} else {
  print("All required domain mean variables found!")
}

# Define domain mapping
domain_mapping <- data.frame(
  variable = c("NPast_mean_pref", "NPast_mean_pers", "NPast_mean_val", "NPast_mean_life",
               "NFut_mean_pref", "NFut_mean_pers", "NFut_mean_val", "NFut_mean_life"),
  time = c(rep("Past", 4), rep("Future", 4)),
  domain = rep(c("Preferences", "Personality", "Values", "Life"), 2),
  stringsAsFactors = FALSE
)

print(domain_mapping)

# Function to pivot data to long format
pivot_domain_means <- function(data, domain_mapping) {
  long_data <- data.frame()
  
  for (i in 1:nrow(domain_mapping)) {
    var_name <- domain_mapping$variable[i]
    time_level <- domain_mapping$time[i]
    domain_level <- domain_mapping$domain[i]
    
    # Check if variable exists
    if (!var_name %in% colnames(data)) {
      cat("Warning: Variable", var_name, "not found in data\n")
      next
    }
    
    # Create subset for this variable
    subset_data <- data[, c("pID", "ResponseId", "GROUP", "TEMPORAL_DO", "ITEM_DO", var_name)]
    subset_data$TIME <- time_level
    subset_data$DOMAIN <- domain_level
    subset_data$MEAN_DIFFERENCE <- subset_data[[var_name]]
    subset_data[[var_name]] <- NULL  # Remove original column
    
    # Add to long data
    long_data <- rbind(long_data, subset_data)
  }
  
  # Convert to factors with proper levels
  long_data$TIME <- factor(long_data$TIME, levels = c("Past", "Future"))
  long_data$DOMAIN <- factor(long_data$DOMAIN, levels = c("Preferences", "Personality", "Values", "Life"))
  long_data$pID <- as.factor(long_data$pID)
  long_data$GROUP <- as.factor(long_data$GROUP)
  long_data$TEMPORAL_DO <- as.factor(long_data$TEMPORAL_DO)
  long_data$ITEM_DO <- as.factor(long_data$ITEM_DO)
  
  return(long_data)
}

# Pivot data to long format
cat("\nPivoting data to long format...\n")
tryCatch({
  long_data <- pivot_domain_means(data, domain_mapping)
  cat("Data pivoting completed successfully.\n")
}, error = function(e) {
  cat("Error in data pivoting:", e$message, "\n")
  stop("Cannot proceed without proper data structure")
})

cat("Long format data dimensions:", dim(long_data), "\n")
cat("Unique participants:", length(unique(long_data$pID)), "\n")
cat("TIME levels:", paste(levels(long_data$TIME), collapse = ", "), "\n")
cat("DOMAIN levels:", paste(levels(long_data$DOMAIN), collapse = ", "), "\n")

# Check data types
cat("\nData types check:\n")
cat("TIME is factor:", is.factor(long_data$TIME), "\n")
cat("DOMAIN is factor:", is.factor(long_data$DOMAIN), "\n")
cat("pID is factor:", is.factor(long_data$pID), "\n")
cat("MEAN_DIFFERENCE is numeric:", is.numeric(long_data$MEAN_DIFFERENCE), "\n")

# Show first 20 rows
cat("\nFirst 20 rows of long_data:\n")
print(utils::head(long_data, 20))

# Display structure and sample
cat("\nLong data structure:\n")
str(long_data)

cat("\nFirst 10 rows of long_data:\n")
print(utils::head(long_data, 10))

# Show example data for one participant
cat("\nExample: Participant 1 across all domains and times:\n")
participant_1_data <- long_data[long_data$pID == 1, c("pID", "GROUP", "TEMPORAL_DO", "ITEM_DO", "TIME", "DOMAIN", "MEAN_DIFFERENCE")]
print(participant_1_data)

