# Load necessary libraries
library(ggplot2)
library(dplyr)
library(viridis)  # For color palettes

# Load the dataset
data <- read.csv("pax_all_agreements_data_v8.csv")

# Convert the 'Dat' column to Date type
data$Dat <- as.Date(data$Dat, format = "%Y-%m-%d")

# Extract the year from the 'Dat' column
data$Year <- format(data$Dat, "%Y")

# Aggregate data by year
data_summary <- data %>%
  group_by(Year) %>%
  summarise(Agreements = n()) %>%
  arrange(Year)

# Define the maximum number of units per row
units_per_row <- 10

# Create a new data frame to hold positions for each agreement
unit_data <- data.frame()

# Loop through each year to create unit positions
for (i in 1:nrow(data_summary)) {
  year <- data_summary$Year[i]
  agreements <- data_summary$Agreements[i]
  rows <- ceiling(agreements / units_per_row)
  for (r in 1:rows) {
    for (c in 1:units_per_row) {
      if ((r - 1) * units_per_row + c <= agreements) {
        unit_data <- rbind(unit_data, data.frame(
          Year = year,
          Row = r,
          Column = c
        ))
      }
    }
  }
}

# Convert 'Year' to factor to maintain order in the plot
unit_data$Year <- factor(unit_data$Year, levels = unique(data_summary$Year))

# Create the unit chart with compact arrangement and color gradient
ggplot(unit_data, aes(x = Column, y = -Row, fill = Year)) +
  geom_tile(color = "white") +
  scale_fill_viridis_d() +  # Use a dynamic color scale for categorical data
  facet_wrap(~ Year, ncol = 6) +  # Group years horizontally to reduce vertical space
  labs(title = "Number of Peace Agreements Signed Per Year",
       x = NULL,
       y = NULL) +
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    strip.text = element_text(size = 8, face = "bold"),
    plot.margin = margin(5, 15, 15, 15)  # Increase right margin to fit the legend
  )