# =============================================================================
# Reyes et al. | Reproducible analyses from repository workbook
# Input: Data_availability_REYES_revisado.xlsx (same working directory)
#
# IMPORTANT:
# - Only quantified values are positive; reported nd and <LC / <LOQ are set to 0.
# - Uncollected site-campaign samples are not added as zeros.
# - PCA and HCA are DESCRIPTIVE (5 site-level observations; no causal inference).
# - The HI calculations are supplied as spreadsheet formulas in HI_por_campaña,
#   not as R analyses. The paired physicochemical comparisons are a separate script.
# =============================================================================

library(readxl)
library(dplyr)
library(tidyr)
library(stringr)
library(tibble)
library(ggplot2)
library(ggrepel)
library(vegan)
library(pheatmap)
library(RColorBrewer)

input_file <- "Data_availability_REYES_revisado.xlsx"
output_dir <- "R_outputs"
dir.create(output_dir, showWarnings = FALSE, recursive = TRUE)
stopifnot(file.exists(input_file))
sites <- paste0("S", 1:5)

# Numeric parser. Zero applies ONLY to analyzed samples flagged nd/<LC/<LOQ.
# Missing cells remain NA; do not treat unsampled events as nondetects.
as_lab_numeric <- function(x) {
  s <- trimws(gsub(",", ".", as.character(x), fixed = TRUE))
  censored <- grepl("^(nd|<lc|<loq)", tolower(s))
  result <- suppressWarnings(as.numeric(s))
  result[censored & !is.na(censored)] <- 0
  result
}
mean_available <- function(x) if (all(is.na(x))) NA_real_ else mean(x, na.rm = TRUE)

# ---- 1. Pest-number and Pest-index ------------------------------------------
water <- read_excel(input_file, sheet = "Pesticides in water") %>%
  filter(Site %in% sites)
pesticide_columns <- names(water)[match("Azoxystrobin", names(water)):
                                   match("AMPA", names(water))]
water_clean <- water %>%
  mutate(across(all_of(pesticide_columns), as_lab_numeric))

pest_summary <- water_clean %>%
  select(Site, all_of(pesticide_columns)) %>%
  pivot_longer(-Site, names_to = "Pesticide", values_to = "Concentration_ug_L") %>%
  group_by(Site, Pesticide) %>%
  summarise(Total_ug_L = sum(Concentration_ug_L, na.rm = TRUE),
            .groups = "drop") %>%
  filter(Total_ug_L > 0) %>%
  group_by(Site) %>%
  mutate(p_i = Total_ug_L / sum(Total_ug_L)) %>%
  summarise(Pest_number = n(),
            Pest_index = -sum(p_i * log2(p_i)), .groups = "drop")
print(pest_summary)
write.csv(pest_summary, file.path(output_dir, "Pest_number_Pest_index.csv"),
          row.names = FALSE)

# ---- 2. Figure 2: water pesticide heatmap -----------------------------------
heatmap_data <- water_clean %>%
  group_by(Site) %>%
  summarise(across(all_of(pesticide_columns), mean_available), .groups = "drop") %>%
  pivot_longer(-Site, names_to = "Pesticide", values_to = "Concentration") %>%
  mutate(Pesticide = ifelse(Pesticide == "2,4D", "2,4-D", Pesticide),
         Concentration = Concentration * 1000) %>%   # µg/L to ng/L
  group_by(Pesticide) %>%
  filter(any(Concentration > 0, na.rm = TRUE)) %>%
  ungroup() %>%
  mutate(Concentration = ifelse(Concentration == 0, NA_real_, Concentration))
p2 <- ggplot(heatmap_data, aes(Pesticide, Site, fill = Concentration)) +
  geom_tile(color = "white", linewidth = 0.5) +
  scale_fill_viridis_c(
    name = "Concentration\n(ng L-1, log10 scale)",
    option = "viridis", na.value = "grey85",
    trans = "log10", breaks = c(10, 100, 1000)) +
  scale_y_discrete(limits = rev(sites)) +
  labs(x = "Pesticide", y = "Site") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1,
                                   size = 10, face = "italic"),
        panel.grid = element_blank())
ggsave(file.path(output_dir, "Fig2_Heatmap_Corregida.tiff"),
       p2, width = 8, height = 4, dpi = 300, bg = "white")

# ---- 3. Figure 3: exploratory PCA -------------------------------------------
# This is a preassembled matrix with mixed sampling periods. Date labels are
# descriptive; they do NOT denote simultaneous measurements of all parameters.
pca_raw <- read_excel(input_file, sheet = "PCA") %>%
  filter(Site %in% sites)   # exclude annotations below the 10 data rows
pca_pesticides <- names(pca_raw)[match("AMPA", names(pca_raw)):
                                  match("Pyroxasulfone", names(pca_raw))]
pca_environment <- names(pca_raw)[match("pH", names(pca_raw)):
                                   match("Hg", names(pca_raw))]
pca_clean <- pca_raw %>%
  mutate(across(all_of(pca_pesticides), as_lab_numeric),
         across(all_of(pca_environment), as_lab_numeric)) %>%
  mutate(across(all_of(pca_pesticides), ~ .x * 1000)) %>%  # µg/L -> ng/L
  group_by(Site) %>%
  summarise(across(all_of(c(pca_pesticides, pca_environment)),
                   mean_available), .groups = "drop")
pca_num <- pca_clean %>%
  column_to_rownames("Site") %>%
  select(where(~ all(!is.na(.x)) && is.finite(var(.x)) && var(.x) > 0))
message("PCA: ", nrow(pca_num), " sites x ", ncol(pca_num), " variables.")
stopifnot(nrow(pca_num) == 5)
pca_result <- vegan::rda(pca_num, scale = TRUE)
var_exp <- round(100 * vegan::eigenvals(pca_result) /
                   sum(vegan::eigenvals(pca_result)), 1)
message("PCA variance: PC1 = ", var_exp[1], "%; PC2 = ", var_exp[2], "%.")

site_scores <- as.data.frame(vegan::scores(pca_result,
                        display = "sites", scaling = 2)) %>%
  rownames_to_column("Site") %>%
  mutate(Tipo = ifelse(Site %in% c("S1", "S2"),
                      "Sites with lower impact",
                      "Sites immersed in an agricultural-livestock matrix"))
variable_scores <- as.data.frame(vegan::scores(pca_result,
                        display = "species", scaling = 2)) %>%
  rownames_to_column("Variable")

# Cosmetic scaling for biplot layout only; unmodified scores exported below.
var_plot <- variable_scores %>%
  mutate(PC1 = PC1 * 3.2, PC2 = PC2 * 3.2,
         PC1_text = case_when(
           Variable %in% c("Glyphosate","Methoxyfenozide","Imidacloprid") ~ PC1 + 1.2,
           Variable == "TSS" ~ PC1 - 0.4,
           TRUE ~ PC1),
         PC2_text = case_when(
           Variable %in% c("Glyphosate","Methoxyfenozide","Imidacloprid") ~ PC2 + 0.8,
           Variable %in% c("TSS","TP") ~ PC2 - 0.4,
           TRUE ~ PC2))
site_plot <- site_scores %>%
  mutate(PC1 = PC1 * 1.8,
         PC2 = case_when(
           Site == "S3" ~ PC2 * 1.8 + 0.5,
           Site == "S1" ~ PC2 * 1.8 + 0.3,
           TRUE ~ PC2 * 1.8),
         nudge_x = ifelse(Site == "S3", 0, -0.25),
         nudge_y = ifelse(Site == "S3", 0.3, 0.25))

p3 <- ggplot() +
  geom_hline(yintercept = 0, linetype = "dashed", linewidth = 0.5) +
  geom_vline(xintercept = 0, linetype = "dashed", linewidth = 0.5) +
  geom_segment(data = var_plot, aes(x = 0, y = 0, xend = PC1, yend = PC2),
               arrow = arrow(length = grid::unit(0.2, "cm")),
               color = "lightsteelblue3", linewidth = 0.6) +
  geom_text_repel(data = var_plot,
             aes(x = PC1_text, y = PC2_text, label = Variable),
             color = "steelblue4", size = 4.2, max.overlaps = Inf,
             box.padding = 0.6, point.padding = 0.2,
             segment.color = NA, force = 2, direction = "both") +
  geom_point(data = site_plot, aes(PC1, PC2, fill = Tipo), shape = 21,
             color = "black", size = 4.5, stroke = 0.8) +
  scale_fill_manual(values = c(
      "Sites with lower impact" = "white",
      "Sites immersed in an agricultural-livestock matrix" = "black")) +
  geom_text(data = site_plot,
            aes(x = PC1 + nudge_x, y = PC2 + nudge_y, label = Site),
            fontface = "bold", size = 5) +
  scale_x_continuous(limits = c(-4.5, 5.5), breaks = seq(-4, 4, 2)) +
  scale_y_continuous(limits = c(-4.5, 2.5), breaks = seq(-4, 2, 2)) +
  labs(x = paste0("PC1 (", var_exp[1], "%)"),
       y = paste0("PC2 (", var_exp[2], "%)")) +
  theme_classic() + theme(legend.position = "none",
                          axis.title = element_text(size = 15),
                          axis.text = element_text(size = 13))
ggsave(file.path(output_dir, "Fig3_PCA_Corregido_Final.tiff"),
       p3, width = 7.5, height = 8.5, dpi = 300, bg = "white")
write.csv(site_scores, file.path(output_dir, "PCA_site_scores.csv"),
          row.names = FALSE)
write.csv(variable_scores, file.path(output_dir, "PCA_variable_scores.csv"),
          row.names = FALSE)
write.csv(data.frame(PC = paste0("PC", seq_along(var_exp)),
                     Explained_variance_percent = var_exp),
          file.path(output_dir, "PCA_variance.csv"), row.names = FALSE)

# ---- 4. Figure 4: standardized heatmap and Ward.D2 clustering ----------------
# NOTE: spreadsheet source tab is named "Dedrogram" (not "dendrograma").
cluster_raw <- read_excel(input_file, sheet = "Dedrogram") %>%
  filter(Site %in% sites)
cluster_variables <- c("pH", "COND", "DO", "SAT", "T", "AMO", "TP",
                       "TSS", "BOD", "As", "Cr", "Pb", "Cu", "Hg",
                       "pest number", "pest index")
cluster_data <- cluster_raw %>%
  mutate(across(all_of(cluster_variables), as_lab_numeric)) %>%
  group_by(Site) %>%
  summarise(across(all_of(cluster_variables), mean_available),
            .groups = "drop") %>%
  rename(Pest_number = `pest number`,
         Pest_index = `pest index`, Temp = T) %>%
  select(Site, pH, DO, SAT, COND, Temp, AMO, TP, TSS, BOD,
         Pest_number, Pest_index, As, Cr, Pb, Cu) %>%
  column_to_rownames("Site")
stopifnot(all(complete.cases(cluster_data)))
zs <- as.data.frame(scale(cluster_data))
heatmap_matrix <- t(zs)
p4 <- pheatmap::pheatmap(
  heatmap_matrix,
  scale = "none",
  cluster_rows = FALSE,
  cluster_cols = TRUE,
  clustering_distance_cols = "euclidean",
  clustering_method = "ward.D2",
  color = colorRampPalette(rev(RColorBrewer::brewer.pal(7, "RdBu")))(100),
  border_color = "grey80", cellwidth = 45, cellheight = 22,
  angle_col = 45, fontsize = 12, fontsize_row = 12, fontsize_col = 13
)
ggsave(file.path(output_dir, "Fig4_Heatmap_Final.tiff"),
       p4$gtable, width = 7, height = 6.5, dpi = 300, bg = "white")
write.csv(zs, file.path(output_dir, "HCA_site_Zscores.csv"),
          row.names = TRUE)

# ---- 5. Igeo ----------------------------------------------------------------
igeo_raw <- read_excel(input_file, sheet = "Igeo", range = "A1:F6") %>%
  filter(Site %in% sites) %>%
  mutate(across(-Site, as_lab_numeric))
igeo_results <- igeo_raw %>%
  pivot_longer(-Site, names_to = "Metal", values_to = "Hmi") %>%
  mutate(Bn = case_when(
    Metal == "As" ~ 13, Metal == "Cr" ~ 90,
    Metal == "Cu" ~ 45, Metal == "Pb" ~ 20,
    Metal == "Hg" ~ 0.4, TRUE ~ NA_real_
  ),
  Igeo = ifelse(is.na(Hmi) | Hmi <= 0, NA_real_,
                log2(Hmi / (1.5 * Bn)))) %>%
  select(Site, Metal, Igeo) %>%
  pivot_wider(names_from = Metal, values_from = Igeo)
print(igeo_results)
write.csv(igeo_results, file.path(output_dir, "Igeo_results.csv"),
          row.names = FALSE)

message("Done. Outputs written to: ", output_dir)
