
# THE DAWN OF WELL-BEING: THE DEVELOPMENT AND VALIDATION OF DAILY ASSESSMENT
# OF WELL-BEING NAVIGATION
# AUTHORS OF MANUSCRIPT: Petra Hubatka, Tomáš Řiháček, Michal Čevelíček,
# Natálie Macošková, Adam Klocek #
# AUTHOR OF THE ANALYTICAL CODE: Petra Hubatka (petra.hubatka@mail.muni.cz)
# DATE: 2026-02-16

# ---- 1. PACKAGES AND DATA LOADING ----
  library(dplyr)
  library(tidyr)
  library(psych)
  library(purrr)
  library(ggplot2)
  library(stringr)
  library(corrplot)
  library(lme4)
  library(performance)
  library(correlation)
  library(patchwork)
  library(car)
  library(tibble)

data <- read.csv("ema_data_2025_12_08_SIMPLE.csv", sep = ";") # load data
data <- data %>% filter(daily_measurement_withinperson_order <= 7) # filter only the first week

# Columns' names
components = paste0("nowcomponents_i", 1:15) # Components Block
strategies = paste0("nowstrategies_i", 1:18)  # strategies Block 
all_items <- c(components, strategies) # Components and Strategies together

components_rep = paste0("nowcomponents_repeated_i", 1:15) # Retest, Components Block
strategies_rep = paste0("nowstrategies_repeated_i", 1:18) # Retest, Strategies Block

demographics <- c("id", "age", "demo_gender", "demo_nationality", "demo_field_of_study",
                  "demo_financial_situation", "demo_partner", "demo_household") # demographic items

comp_durations <- paste0(components, "_duration") # Components Block duration
strat_durations <- paste0(strategies, "_duration") # Strategies Block duration
all_durations <- c(comp_durations, strat_durations) # Components and Strategies together

# Items' names
components_name <- c("Sleep", "Energy", "Calm", "Positive Emotions", "Interest", "Fulfilment", "Positive Outlook", "Self-Confidence", 
                     "Positive Self-Regard", "Sense of Autonomy", "Authenticity", "Sense of Social Support", "Interpersonal Closeness", "Resilience", "Flow")
strategies_name <- c("Problem Confrontation", "Emotional Awareness", "Modification of Negative Emotions", "Tolerance of Negative Emotions", "Understand Emotions", 
                     "Body Awareness", "Self-Support", "Attention Regulation", "Putting Things into Perspective", "Planning", "Reflection", 
                     "Distraction Seeking", "Simply Being", "Acceptance", "Self-Compassion", "Emotional Expression", "Seeking Social Support", "Mentalization")

names(components_name) <- components
names(strategies_name) <- strategies

# ---- 2. DATA PREPARATION AND QUALITY ANALYSIS ----
data <- data %>%
  mutate(across(
    .cols = all_of(c(components, components_rep, strategies, strategies_rep)),
    .fns = ~ifelse(. == 999, NA, .)
  )) # recode "999" to NA

# Define function for checking valid values 
check_range <- function(data, min_val, max_val, columns_to_control, id, measurement_occasion) {
  data_control <- data %>%
    select(all_of(c(id, measurement_occasion, columns_to_control)))
    data_long <- data_control %>%
    pivot_longer(
      cols = all_of(columns_to_control),
      names_to = "Variable",
      values_to = "Value")
  out_of_range <- data_long %>%
    filter(!is.na(Value) & (Value < min_val | Value > max_val)) %>%
    select(all_of(id), all_of(measurement_occasion), Variable, Value)
    if (nrow(out_of_range) > 0) {
    cat("**The following values are outside the specified range (", min_val, " - ", max_val, "):**\n", sep = "")
    out_of_range_output <- out_of_range %>%
      rename(
        ID = all_of(id),
        Measurement_Occasion = all_of(measurement_occasion),
        Out_of_Range_Value = Value)
    
    print(out_of_range_output)
    return(out_of_range)}
  
  else {cat("*All controlled values are within range** (", min_val, " - ", max_val, ").\n", sep = "")
    return(invisible(NULL))}}

check_range(data = data, min_val = 0, max_val = 100, 
            columns_to_control = c(components, strategies), # checking valid values for components and strategies
            id = "id", measurement_occasion = "daily_measurement_withinperson_order")

# ---- 2.1 Attrition and missing values ----
# Count rowwise the NAs for components, strategies, and components and strategies combined
data <- data %>%
  rowwise() %>%
  mutate(
    # Count NAs only for components
    missing_components = sum(is.na(c_across(all_of(components)))),
    
    # Count NAs only for strategies
    missing_strategies = sum(is.na(c_across(all_of(strategies)))),
    
    # Count NAs componenets + strategies
    missing_total = missing_strategies + missing_components,
    
    filled = if_else(missing_total == 33, 0, 1)
  ) %>%
  ungroup()

# What is the count of completed days per participant?
participant_summary <- data %>%
  group_by(id) %>%
  summarise(total_filled = sum(filled == 1, na.rm = TRUE)) %>%
  ungroup()

# How many participants started a measurement occasion?
participant_summary %>% count(total_filled)

# Graph: The counts of filled measurements
ggplot(participant_summary, aes(x = total_filled)) +
  geom_bar(fill = "#3498db", color = "white") +
  theme_minimal() +
  labs(
    title = "Distribution of Participant Engagement",
    x = "Total Days Completed",
    y = "Number of Participants"
  ) +
  # Set breaks for every single day on the x-axis
  scale_x_continuous(breaks = seq(0, 7, by = 1)) +
  theme(panel.grid.minor.x = element_blank())

# Remove participants who completed 0 measurement from data
ids_to_remove <- participant_summary %>%
  filter(total_filled == 0) %>%
  pull(id)

cat("Participants to be removed (0 measurements filled):", ids_to_remove, "\n")

data <- data %>%
  filter(!(id %in% ids_to_remove))

# How many participant completed the measurement each day?
completion_summary <- data %>%
  group_by(daily_measurement_withinperson_order) %>%
  summarise(
    filled_count = sum(filled == 1, na.rm = TRUE),
    not_filled_count = sum(filled == 0, na.rm = TRUE),
    completion_rate_pct = round((filled_count / n()) * 100, 2)
  ) %>%
  ungroup()

print(completion_summary)

# Graph: Participation over time
ggplot(completion_summary, aes(x = daily_measurement_withinperson_order, y = filled_count)) +
  geom_line() +
  geom_point() +
  scale_y_continuous(limits = c(0, max(completion_summary$filled_count))) +
  theme_minimal() +
  labs(
    title = "Attrition trend",
    x = "Measurement occasion",
    y = "Number of participants"
  )

# Is the distribution of NAs different across measurement occasions?
df <- data %>% filter(filled == 1)

m0 <- glm(missing_total ~ daily_measurement_withinperson_order, family = "poisson", data = df)
m1 <- glmer(missing_total ~ daily_measurement_withinperson_order + (1 | id), 
                    data = df, family = "poisson")
anova(m1, m0, test = "Chisq")D
summary(m1)
Anova(m1)
exp(fixef(m1)["daily_measurement_withinperson_order"])

# ---- 3. SAMPLE ----
sample_demographics <- data %>% filter(daily_measurement_withinperson_order == 1) %>%
  select(all_of(c(demographics)))

sample_demographics$demo_gender <- factor(x = sample_demographics$demo_gender, 
                                levels = c("1", "2", "99"),
                                labels = c("woman", "man", "other"))

sample_demographics$demo_nationality <- factor(x = sample_demographics$demo_nationality, 
                                     levels = c("1", "2", "3", "99"),
                                     labels = c("Czech", "Slovak", "Ukranian", "Other"))

sample_demographics$demo_field_of_study <- factor(x = sample_demographics$demo_field_of_study, 
                                    levels = as.character(c(1:10)),
                                    labels = c("Humanities and Social Sciences",
                                               "Legal Sciences or Law", 
                                               "Economics and Management", 
                                               "Natural Sciences", 
                                               "Informatics and Cybernetics", 
                                               "Technical Fields or Engineering", 
                                               "Agriculture, Forestry, and Veterinary Sciences", 
                                               "Health Care and Medical Sciences", 
                                               "Arts Fields", 
                                               "Military and Security Fields"))

sample_demographics$demo_financial_situation <- factor(x = sample_demographics$demo_financial_situation, 
                                        levels = c("1", "2", "3", "4"),
                                        labels = c("I am financially secure and money is not a concern for me.", 
                                                   "I am usually doing well financially, but I sometimes have concerns.", 
                                                   "I often worry about money and have to manage my finances carefully.", 
                                                   "I frequently experience financial difficulties and have trouble covering basic needs."))

sample_demographics$demo_partner <- factor(x = sample_demographics$demo_partner, 
                                             levels = c("1", "2", "3"),
                                             labels = c("I have a partner.", 
                                                        "I don't have any partner.", 
                                                        "It's complicated."))
sample_demographics$demo_household <- factor(x = sample_demographics$demo_household, 
                                 levels = c("1", "2", "3", "4", "5"),
                                 labels = c("Alone", 
                                            "With a partner", 
                                            "With roommates", 
                                            "With parents", 
                                            "Other"))
# Sample demographics
describe(sample_demographics$age)
sample_demographics %>% count(demo_gender) %>% mutate(n/sum(n)*100)
sample_demographics %>% count(demo_nationality) %>% mutate(n/sum(n)*100)
sample_demographics %>% count(demo_partner) %>% mutate(n/sum(n)*100)
sample_demographics %>% count(demo_financial_situation) %>% mutate(n/sum(n)*100)
sample_demographics %>% count(demo_household) %>% mutate(n/sum(n)*100)
sample_demographics %>% count(demo_field_of_study) %>% mutate(n/sum(n)*100)

# ---- 4. ANALYSIS ----
df <- data %>% filter(filled == 1)

# ---- 4.1 Descriptive statistics ----
# Descriptive statistics across all measurement occasions and participants
describe(df[,components])
describe(df[,strategies])

# Components items' distribution across all measurement occasions and participants
comp_long <- df %>%
  select(all_of(components)) %>%
  pivot_longer(cols = everything(), names_to = "item", values_to = "rating") %>%
  filter(!is.na(rating)) %>%
  mutate(item = factor(item, levels = components))

ggplot(comp_long, aes(x = rating)) +
  geom_bar(fill = "#56B4E9", color = "white") +
  facet_wrap(~item, 
             ncol = 3, 
             scales = "free_y", 
             labeller = labeller(item = components_name)) +
  theme_minimal() +
  labs(
    title = "Distribution of Responses: Components",
    subtitle = "Responses across participants and measurement occasions",
    x = "Response Value",
    y = "Count"
  ) +
  theme(
    strip.background = element_rect(fill = "#f0f0f0"),
    strip.text = element_text(face = "bold", size = 8)
  )

# Strategies items' distribution across all measurement occasions and participants
strat_long <- df %>%
  select(all_of(strategies)) %>%
  pivot_longer(cols = everything(), names_to = "item", values_to = "rating") %>%
  filter(!is.na(rating)) %>%
  mutate(item = factor(item, levels = strategies))

ggplot(strat_long, aes(x = rating)) +
  geom_bar(fill = "#E69F00", color = "white") +
  facet_wrap(~item, ncol = 3, scales = "free_y",
             labeller = labeller(item = strategies_name)) +
  theme_minimal() +
  labs(
    title = "Distribution of Responses: Strategies",
    subtitle = "Responses across participants and measurement occasions",
    x = "Response Value",
    y = "Count"
  ) +
  theme(
    strip.background = element_rect(fill = "#f0f0f0"),
    strip.text = element_text(face = "bold")
  )

# For each measurement occasion
analyze_single_occasion <- function(occ_id, data, save_csv = TRUE, file_prefix = "descriptives_day_",
                                    save_plot = TRUE, plot_prefix = "plot_day_",
                                    plot_width = 10, plot_height = 12) {
  day_data <- data %>%
    filter(daily_measurement_withinperson_order == occ_id)
  
  if(nrow(day_data) == 0) {
    stop(paste("For measurement occasion", occ_id, "no data."))
  }
  
  # Components 
  stats_comp <- describe(day_data[, components]) %>%
    as.data.frame() %>%
    rownames_to_column(var = "Item") %>%
    mutate(Type = "Component") %>%
    select(Type, Item, n, mean, sd, median, min, max, skew, kurtosis)
  
  # Strategies
  stats_strat <- describe(day_data[, strategies]) %>%
    as.data.frame() %>%
    rownames_to_column(var = "Item") %>%
    mutate(Type = "Strategy") %>%
    select(Type, Item, n, mean, sd, median, min, max, skew, kurtosis)
  
  # One table
  final_table <- bind_rows(stats_comp, stats_strat)
  print(final_table %>% select(Type, Item, mean, sd, median))
  
  # Save
  if (save_csv) {
    file_name <- paste0(file_prefix, occ_id, ".csv")
    write.csv(final_table, file = file_name, row.names = FALSE)
        cat("\n[OK] Table was saved to the file:", file_name, "\n")
  }
  
  # 3. Graph (Components)
  comp_long <- day_data %>%
    select(all_of(components)) %>%
    pivot_longer(cols = everything(), names_to = "item", values_to = "rating") %>%
    filter(!is.na(rating)) %>%
    mutate(item = factor(item, levels = components))
  
  names(components_name) <- components
  
  p_comp <- ggplot(comp_long, aes(x = rating)) +
    geom_bar(fill = "#56B4E9", color = "white") +
    facet_wrap(~item, 
               ncol = 3, 
               scales = "free_y", 
               labeller = labeller(item = components_name)) +
    theme_minimal() +
    labs(
      title = paste("Distribution: Components (Day", occ_id, ")"),
      subtitle = paste("Responses for measurement occasion", occ_id),
      x = "Response Value",
      y = "Count"
    ) +
    theme(
      strip.background = element_rect(fill = "#f0f0f0"),
      strip.text = element_text(face = "bold", size = 8)
    )
  
  # 4. Graph (Strategies)
  strat_long <- day_data %>%
    select(all_of(strategies)) %>%
    pivot_longer(cols = everything(), names_to = "item", values_to = "rating") %>%
    filter(!is.na(rating)) %>%
    mutate(item = factor(item, levels = strategies))
  
  names(strategies_name) <- strategies
  
  p_strat <- ggplot(strat_long, aes(x = rating)) +
    geom_bar(fill = "#E69F00", color = "white") +
    facet_wrap(~item, 
               ncol = 3, 
               scales = "free_y",
               labeller = labeller(item = strategies_name)) +
    theme_minimal() +
    labs(
      title = paste("Distribution: Strategies (Day", occ_id, ")"),
      subtitle = paste("Responses for measurement occasion", occ_id),
      x = "Response Value",
      y = "Count"
    ) +
    theme(
      strip.background = element_rect(fill = "#f0f0f0"),
      strip.text = element_text(face = "bold", size = 8)
    )
  
  if (save_plot) {
    fname_comp <- paste0(plot_prefix, "components_", occ_id, ".png")
    fname_strat <- paste0(plot_prefix, "strategies_", occ_id, ".png")
    
    ggsave(filename = fname_comp, plot = p_comp, width = plot_width, height = plot_height, dpi = 300)
    ggsave(filename = fname_strat, plot = p_strat, width = plot_width, height = plot_height, dpi = 300)
    
    cat("[OK] Graphs were saved to:", fname_comp, "a", fname_strat, "\n")
  }
  
  return(list(comp_plot = p_comp, strat_plot = p_strat))
}

for (i in 1:7) {
analyze_single_occasion(i, df)}

# ---- 4.2 Research question 2: Within- and between-person variability ----
results_lmm_icc <- NULL
data$id <- as.factor(data$id)

for (item in c(components, strategies)) {
  formula <- as.formula(paste(item, "~ 1 + (1 | id)"))
  model <- lmer(formula, data = data)
  icc_value <- icc(model)$ICC_adjusted
  results_lmm_icc <- rbind(results_lmm_icc, c(item, icc_value))}

print(results_lmm_icc)

# ---- 4.3 Research question 3: Inter-item relationship ----
# Correlations within each measurement; than to Fisher scores, means and back
all_items <- c(components, strategies)

calculate_z_matrix <- function(day_data) {
  cor_matrix <- cor(day_data[, all_items], use = "pairwise.complete.obs", method = "pearson")
  z_matrix <- atanh(cor_matrix)
  return(z_matrix)
}

unique_days <- sort(unique(data$daily_measurement_withinperson_order))
z_matrices_list <- list()

for (day in unique_days) {
  day_subset <- data[data$daily_measurement_withinperson_order == day, ]
  
  if (nrow(day_subset) > 3) {
    z_matrices_list[[as.character(day)]] <- calculate_z_matrix(day_subset)
  }
}

stacked_z <- simplify2array(z_matrices_list)
mean_z_matrix <- apply(stacked_z, 1:2, mean, na.rm = TRUE)

final_cor_table <- tanh(mean_z_matrix)

final_cor_table <- as.data.frame(final_cor_table)

final_cor_export <- cbind(item = rownames(final_cor_table), final_cor_table)

write.table(final_cor_export, 
            file = "average_correlation_matrix.csv", 
            sep = ";", 
            row.names = FALSE, 
            col.names = TRUE, 
            fileEncoding = "UTF-8",
            dec = ",")

# ---- 4.4 RQ4: Reliability -----
data_first <- data %>% filter(daily_measurement_withinperson_order == 1) # filter only the first measurement
data_last <- data %>% filter(daily_measurement_withinperson_order == 7) # filter only the first measurement

# ---- Reliability: Test-retest ----
test_retest_mo1 <- tibble(
  Var_X = c(components, strategies),
  Var_Y = c(components_rep, strategies_rep))

test_retest_mo1 <- test_retest_mo1 %>%
  mutate(reliability = map2_dbl(
      .x = Var_X,
      .y = Var_Y,
      .f = ~ cor(
        x = data_first[[.x]], 
        y = data_first[[.y]],
        use = "pairwise.complete.obs"))) %>%
  select(Var_X, reliability)

# ---- Reliability: Test-retest (last day) ----
test_retest_mo7 <- tibble(
  Var_X = c(components, strategies),
  Var_Y = c(components_rep, strategies_rep))

test_retest_mo7 <- test_retest_mo7 %>%
  mutate(reliability = map2_dbl(
    .x = Var_X,
    .y = Var_Y,
    .f = ~ cor(
      x = data_last[[.x]], 
      y = data_last[[.y]],
      use = "pairwise.complete.obs"))) %>%
  select(Var_X, reliability)

# ---- Day 1 vs. Day 7: Test-retest stability (Components)----
plot_data <- data %>%
  filter(daily_measurement_withinperson_order %in% c(1, 7)) %>%
  mutate(Day = factor(daily_measurement_withinperson_order, labels = c("Day 1", "Day 7")))

df_test <- plot_data %>%
  select(id, Day, all_of(components)) %>%
  pivot_longer(cols = all_of(components), names_to = "orig_item", values_to = "test_val") %>%
  mutate(item_num = as.integer(str_extract(orig_item, "\\d+")))

df_retest <- plot_data %>%
  select(id, Day, all_of(components_rep)) %>%
  pivot_longer(cols = all_of(components_rep), names_to = "orig_rep", values_to = "retest_val") %>%
  mutate(item_num = as.integer(str_extract(orig_rep, "\\d+")))


final_df <- left_join(df_test, df_retest, by = c("id", "Day", "item_num"))

labels_df <- tibble(
  item_num = 1:15,
  item_label = components_name
)

final_df <- final_df %>%
  left_join(labels_df, by = "item_num") %>%
  mutate(item_label = factor(item_label, levels = components_name))

ggplot(final_df, aes(x = test_val, y = retest_val, color = Day, fill = Day)) +
  geom_jitter(size = 1.5, width = 0.2, height = 0.2) + 
  geom_smooth(method = "lm", se = TRUE, alpha = 0.2) +

  facet_wrap(~item_label, ncol = 5) +
  theme_minimal() +

  labs(
    title = "Test-Retest Stability: Day 1 vs. Day 7",
    subtitle = "Components",
    x = "First Measurement (Test)",
    y = "Repeated Measurement (Retest)",
    color = "Measurement Day",
    fill = "Measurement Day"
  ) +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 9, face = "bold"))

# ---- Day 1 vs. Day 7: Test-retest stability (Strategies)----
df_test <- plot_data %>%
  select(id, Day, all_of(strategies)) %>%
  pivot_longer(cols = all_of(strategies), names_to = "orig_item", values_to = "test_val") %>%
  mutate(item_num = as.integer(str_extract(orig_item, "\\d+")))

df_retest <- plot_data %>%
  select(id, Day, all_of(strategies_rep)) %>%
  pivot_longer(cols = all_of(strategies_rep), names_to = "orig_rep", values_to = "retest_val") %>%
  mutate(item_num = as.integer(str_extract(orig_rep, "\\d+")))


final_df <- left_join(df_test, df_retest, by = c("id", "Day", "item_num"))

labels_df <- tibble(
  item_num = 1:18,
  item_label = strategies_name
)

final_df <- final_df %>%
  left_join(labels_df, by = "item_num") %>%
  mutate(item_label = factor(item_label, levels = strategies_name))

ggplot(final_df, aes(x = test_val, y = retest_val, color = Day, fill = Day)) +
  geom_jitter(size = 1.5, width = 0.2, height = 0.2) + 
  geom_smooth(method = "lm", se = TRUE, alpha = 0.2) +
  
  facet_wrap(~item_label, ncol = 6) +
  theme_minimal() +
  
  labs(
    title = "Test-Retest Stability: Day 1 vs. Day 7",
    subtitle = "Strategies",
    x = "First Measurement (Test)",
    y = "Repeated Measurement (Retest)",
    color = "Measurement Day",
    fill = "Measurement Day"
  ) +
  theme(
    legend.position = "bottom",
    strip.text = element_text(size = 9, face = "bold"))

# ---- 4.4. Exploratory N = 1 analysis ---- 
# Identify people with all seven measurements
completers_ids <- data %>%
  group_by(id) %>%
  summarise(
    n_measures = n(),
    all_filled = all(filled == 1, na.rm = TRUE)
  ) %>%
  filter(n_measures == 7, all_filled == TRUE) %>%
  pull(id)

completers_ids <- as.character(completers_ids)

# Randomly sample one of the participants
seed = 123489
target_id <- sample(completers_ids, 1)

# Filter data for the selected participant
participant_profile <- function(data, target_id) {
  
  cat("Analyzing pariticipant with ID:", target_id, "\n")
  
  p_data <- data %>% 
    filter(id == target_id) %>%
    arrange(daily_measurement_withinperson_order)
  
  # Long format data
  long_comp <- p_data %>%
    select(daily_measurement_withinperson_order, all_of(components)) %>%
    pivot_longer(cols = -daily_measurement_withinperson_order, names_to = "item", values_to = "rating") %>%
    mutate(item = factor(item, levels = components))
  
  long_strat <- p_data %>%
    select(daily_measurement_withinperson_order, all_of(strategies)) %>%
    pivot_longer(cols = -daily_measurement_withinperson_order, names_to = "item", values_to = "rating") %>%
    mutate(item = factor(item, levels = strategies))
  
  p_stats <- describe(p_data %>% select(all_of(c(components, strategies))))
  print(p_stats %>% select(n, mean, sd, median, min, max, range))
  
  plot_fluctuation_data <- p_data %>%
    select(daily_measurement_withinperson_order, all_of(c(components, strategies))) %>%
    pivot_longer(cols = -daily_measurement_withinperson_order, 
                 names_to = "item", 
                 values_to = "rating") %>%
    group_by(item) %>%
    mutate(item_mean = mean(rating, na.rm = TRUE)) %>% 
    ungroup() %>%
    mutate(
      section = if_else(item %in% components, "Components", "Strategies"),
      
      item_label_text = case_when(
        item %in% components ~ components_name[as.character(item)],
        item %in% strategies ~ strategies_name[as.character(item)],
        TRUE ~ item
      ),
      
      item_label = factor(item_label_text, levels = c(unname(components_name), unname(strategies_name)))
    )
  
  # ---- COMPONENTS ----
  graph_comp <- ggplot(filter(plot_fluctuation_data, section == "Components"), aes(x = daily_measurement_withinperson_order, y = rating)) +
    geom_hline(aes(yintercept = item_mean), color = "orange", linetype = "dashed") +
    geom_line(color = "#2980b9") +
    geom_segment(aes(xend = daily_measurement_withinperson_order, yend = item_mean), color = "gray60") +
    geom_point(color = "#2980b9", size = 2.5) +
    
    facet_wrap(~item_label, ncol = 5) + 
    scale_x_continuous(breaks = 1:7) +
    scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 20)) +
    theme_minimal() +
    labs(
      title = paste("Fluctuation around the mean: Components (ID:", target_id, ")"),
      subtitle = "Orange line = item's mean for 7 days | Blue point = daily rating",
      x = "Measurement occasion",
      y = "Rating"
    ) +
    theme(strip.text = element_text(size = 7, face = "bold"))
  
  # ---- STRATEGIES ----
  graph_strat <- ggplot(filter(plot_fluctuation_data, section == "Strategies"), aes(x = daily_measurement_withinperson_order, y = rating)) +
    geom_hline(aes(yintercept = item_mean), color = "orange", linetype = "dashed") +
    geom_line(color = "#2980b9") +
    geom_segment(aes(xend = daily_measurement_withinperson_order, yend = item_mean), color = "gray60") +
    geom_point(color = "#2980b9", size = 2.5) +
    
    facet_wrap(~item_label, ncol = 6) + 
    scale_x_continuous(breaks = 1:7) +
    scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 20)) +
    theme_minimal() +
    labs(
      title = paste("Fluctuation around the mean: Strategies (ID:", target_id, ")"),
      subtitle = "Orange line = item's mean for 7 days | Blue point = daily rating",
      x = "Measurement occasion",
      y = "Rating"
    ) +
    theme(strip.text = element_text(size = 7, face = "bold"))
  
  return(list(comp = graph_comp, strat = graph_strat, p_stats = p_stats))
  
}

picked_participant <- participant_profile(data = data, target_id = target_id)
picked_participant$comp
picked_participant$strat

# AUTOCORRELATIONS
autocor <- function(data, target_id) {
  
  all_items <- c(components, strategies)
  
  p_data <- data %>% 
    filter(id == target_id) %>%
    arrange(daily_measurement_withinperson_order)
  
  autocorrelations <- p_data %>%
    select(daily_measurement_withinperson_order, all_of(all_items)) %>%
    pivot_longer(cols = -daily_measurement_withinperson_order, 
                 names_to = "item", 
                 values_to = "rating") %>%
    group_by(item) %>%
    summarise(
      ar1 = cor(rating, lag(rating), use = "pairwise.complete.obs"),
      n_pairs = sum(!is.na(rating) & !is.na(lag(rating)))
    )
  
  autocorrelations <- autocorrelations %>%
    mutate(
      item_label = case_when(
        item %in% components ~ components_name[as.character(item)],
        item %in% strategies ~ strategies_name[as.character(item)],
        TRUE ~ item
      )
    )
  
  return(autocorrelations = autocorrelations)}

picked_participant_AC <- autocor(data, target_id)

stats_clean <- picked_participant$p_stats %>%
  as.data.frame() %>%
  rownames_to_column(var = "item") %>%
  select(item, n, mean, sd, median, min, max, range)

combined_table <- stats_clean %>%
  left_join(picked_participant_AC, by = "item") %>%

  select(
    item, 
    item_label, 
    mean, sd, median, min, max, range,
    ar1, n_pairs                       
  ) %>%
  mutate(across(where(is.numeric), ~ round(., 2)))

print(combined_table)
