library(ggplot2)
library(dplyr)
library(tidyr)
library(scales)
library(patchwork)
library(ggrepel)
library(readr)


deg <- "\u00b0"
BG_DARK   <- "#0D1B2A"
BG_CARD   <- "#1A2B3C"
COL_ORANGE <- "#FF6B35"
COL_TEAL   <- "#00C9A7"
COL_YELLOW <- "#FFD166"
COL_LIGHT  <- "#E8F1F2"
COL_GRAY   <- "#8898AA"
COL_PURPLE <- "#A855F7"

theme_storm <- function() {
  theme_minimal(base_family = "sans") +
  theme(
    plot.background = element_rect(fill = BG_DARK, color = NA),
    panel.background = element_rect(fill = BG_CARD, color = NA),
    panel.grid.major = element_line(color = "#243B53", linewidth = 0.4),
    panel.grid.minor = element_blank(),
    axis.text = element_text(color = COL_GRAY, size = 11),
    axis.title = element_text(color = COL_LIGHT, size = 12, face = "bold"),
    plot.title = element_text(color = COL_LIGHT, size = 18, face = "bold", margin = margin(b = 6)),
    plot.subtitle = element_text(color = COL_TEAL, size = 12, margin = margin(b = 12)),
    plot.caption = element_text(color = COL_GRAY, size = 9),
    legend.background = element_rect(fill = BG_DARK, color = NA),
    legend.text = element_text(color = COL_LIGHT, size = 10),
    legend.title = element_text(color = COL_LIGHT, size = 11, face = "bold"),
    plot.margin = margin(20, 24, 16, 20)
  )
}
set.seed(42)
years <- 1994:2023
n <- length(years)

climate <- read_csv("climate_data.csv")
storms <- read_csv("storm_data.csv")
extreme_weather <- read_csv("extreme_weather_data.csv")
df <- climate %>%
  left_join(storms, by = "year") %>%
  left_join(extreme_weather, by = "year")
# ---- CHART 1 ----
df_temp_smooth <- df %>% mutate(smooth_temp = predict(loess(temp ~ year, span = 0.4)))

p1 <- ggplot(df, aes(x = year)) +
  geom_ribbon(aes(ymin = 0, ymax = temp), fill = COL_ORANGE, alpha = 0.15) +
  geom_hline(yintercept = 0, color = COL_GRAY, linetype = "dashed", linewidth = 0.6, alpha = 0.6) +
  geom_point(aes(y = temp), color = COL_ORANGE, size = 2.5, alpha = 0.6) +
  geom_line(data = df_temp_smooth, aes(y = smooth_temp), color = COL_ORANGE, linewidth = 2.5) +
  geom_point(data = df[df$year == 2023,], aes(y = temp),
             color = COL_YELLOW, size = 5, shape = 21, fill = COL_ORANGE, stroke = 2) +
  annotate("text", x = 2021, y = 1.23,
           label = paste0("+1.17", deg, "C\nin 2023"),
           color = COL_YELLOW, size = 4.5, fontface = "bold", hjust = 1) +
  annotate("text", x = 1994.5, y = 0.12, label = "Pre-industrial baseline",
           color = COL_GRAY, size = 3.5, hjust = 0, fontface = "italic") +
  scale_x_continuous(breaks = seq(1995, 2020, 5)) +
  scale_y_continuous(labels = function(x) paste0("+", x, deg, "C"),
                     breaks = seq(0, 1.2, 0.3)) +
  labs(
    title = paste0("Earth Is Getting Hotter : Fast"),
    subtitle = paste0("Global temperature anomaly vs. 1951\u20131980 average"),
    x = NULL, y = paste0("Temperature Anomaly (", deg, "C)"),
    caption = ""
  ) +
  theme_storm()

ggsave("chart1_temperature.png", p1, width=10, height=5.5, dpi=150, bg=BG_DARK)
p1

# ---- CHART 2 ----
df_storms <- df %>%
  select(year, hurricanes, typhoons) %>%
  pivot_longer(cols=c(hurricanes, typhoons), names_to="type", values_to="count") %>%
  mutate(type=ifelse(type=="hurricanes", "Major Hurricanes (Cat 3-5)", "Typhoons (W. Pacific)"))
 
# Smoothed trend lines for each storm type separately
df_hurr_smooth <- df %>% mutate(smooth=predict(loess(hurricanes~year, span=0.5)))
df_typh_smooth <- df %>% mutate(smooth=predict(loess(typhoons~year,   span=0.5)))
 
temp_scale <- 8; temp_offset <- 20
p2 <- ggplot() +
  geom_col(data=df_storms, aes(x=year, y=count, fill=type),
           position="dodge", alpha=1, width=0.7) +
  # Hurricane trend line — teal dashed
  geom_line(data=df_hurr_smooth, aes(x=year, y=smooth),
            color=COL_TEAL, linewidth=2, alpha=0.55,  linetype="dashed") +
  # Typhoon trend line — purple dashed
  geom_line(data=df_typh_smooth, aes(x=year, y=smooth),
            color=COL_PURPLE, linewidth=2,alpha=0.55, linetype="dashed") +
  # Temperature overlay — solid orange
  geom_line(data=df, aes(x=year, y=temp*temp_scale+temp_offset),
            color=COL_ORANGE, linewidth=2, linetype="solid") +
  geom_point(data=df, aes(x=year, y=temp*temp_scale+temp_offset),
             color=COL_ORANGE, size=2, alpha=0.8) +

  scale_fill_manual(values=c("Major Hurricanes (Cat 3-5)"=COL_TEAL,
                              "Typhoons (W. Pacific)"=COL_PURPLE)) +
  scale_x_continuous(breaks=seq(1995, 2020, 5), limits=c(1994, 2024.5)) +
  scale_y_continuous(
    name="Storm Count",
    sec.axis=sec_axis(~(.-temp_offset)/temp_scale,
                      name=paste0("Temperature Anomaly (", deg, "C)"),
                      labels=function(x) paste0("+", round(x,2), deg, "C"))
  ) +
  annotate("text", x=2014, y=33, label="Rising Temperature \u2192",
           color=COL_ORANGE, size=3.8, fontface="bold", angle=8) +
  labs(title="Hurricane and Typhoon counts closely track the increasing temparature",
       subtitle="",
       x=NULL, fill=NULL,
       caption="") +
  theme_storm() +
  theme(legend.position="bottom",
        axis.title.y.right=element_text(color=COL_ORANGE, size=11, face="bold"),
        axis.text.y.right=element_text(color=COL_ORANGE))
ggsave("chart2_storm_counts.png", p2, width=10, height=5.5, dpi=150, bg=BG_DARK)
ggsave("chart2_storm_counts.png", p2, width=10, height=5.5, dpi=150, bg=BG_DARK)
cat("Chart 2 done\n")
## Chart 2 done
p2

# ---- CHART 3 ----
cor_val <- round(cor(df$temp, df$ace), 2)
df <- df %>% mutate(decade=case_when(
  year<2000~"1994-1999", year<2010~"2000-2009",
  year<2020~"2010-2019", TRUE~"2020-2023"))
decade_colors <- c("1994-1999"="#4A9EFF","2000-2009"=COL_TEAL,
                   "2010-2019"=COL_YELLOW,"2020-2023"=COL_ORANGE)

p3 <- ggplot(df, aes(x=temp, y=ace, color=decade)) +
  geom_smooth(method="lm", se=TRUE, color=COL_ORANGE, fill=COL_ORANGE,
              alpha=0.15, linewidth=1.5, inherit.aes=FALSE, aes(x=temp,y=ace)) +
  geom_point(size=5, alpha=0.9) +
  geom_label_repel(
    data=df %>% filter(year %in% c(2005,2017,2020,2023,1994)),
    aes(label=year), size=3.5, fontface="bold",
    fill=BG_CARD, color=COL_LIGHT, label.size=0.3,
    box.padding=0.4, point.padding=0.3) +
  annotate("text", x=min(df$temp)+0.01, y=max(df$ace)-8,
           label=paste0("Correlation r = ", cor_val),
           color=COL_YELLOW, size=5, fontface="bold", hjust=0) +
  annotate("text", x=min(df$temp)+0.01, y=max(df$ace)-22,
           label="Strong positive relationship",
           color=COL_GRAY, size=3.8, hjust=0, fontface="italic") +
  scale_color_manual(values=decade_colors) +
  scale_x_continuous(labels=function(x) paste0("+", x, deg, "C")) +
  labs(title="Hotter Planet = More Powerful Storms",
       subtitle="Accumulated Cyclone Energy (ACE) vs. global temperature anomaly",
       x=paste0("Global Temperature Anomaly (", deg, "C)"),
       y="Storm Intensity (ACE Index)",
       color="Decade",
       caption="") +
  theme_storm() +
  theme(legend.position="right")
ggsave("chart3_intensity_scatter.png", p3, width=10, height=5.5, dpi=150, bg=BG_DARK)
p3

# ---- CHART 4 ----
df <- df %>% mutate(tornado_roll = stats::filter(tornadoes, rep(1/5,5), sides=2))
p4 <- ggplot(df, aes(x=year)) +
  geom_ribbon(aes(ymin=800, ymax=tornadoes), fill=COL_YELLOW, alpha=0.20) +
  geom_line(aes(y=tornadoes), color=COL_YELLOW, linewidth=1, alpha=0.5) +
  geom_line(aes(y=tornado_roll), color=COL_YELLOW, linewidth=2.5, na.rm=TRUE) +
  geom_line(aes(y=temp*600+700), color=COL_ORANGE, linewidth=1.8, linetype="dashed") +
  annotate("text", x=2008, y=1890, label="2011: Record 1,817 tornadoes",
           color=COL_YELLOW, size=3.8, fontface="bold") +
  annotate("segment", x=2011, xend=2011, y=1817, yend=1760,
           arrow=arrow(length=unit(0.2,"cm")), color=COL_YELLOW) +
  annotate("text", x=2019.5, y=790, label="--- Rising Temperature",
           color=COL_ORANGE, size=3.5, fontface="bold") +
  scale_x_continuous(breaks=seq(1995, 2020, 5)) +
  scale_y_continuous(limits=c(750,1950)) +
  labs(title="The worst seem to be behind us for now",
       subtitle="Tornado numbers fell back to pre 2000s levels",
       x=NULL, y="Number of Tornadoes (USA)",
       caption="") +
  theme_storm()
ggsave("chart4_tornadoes.png", p4, width=10, height=5.5, dpi=150, bg=BG_DARK)
p4

# ---- CHART 5 ----
decade_summary <- df %>%
  group_by(decade) %>%
  summarise(avg_temp=mean(temp), avg_hurricanes=mean(hurricanes),
            avg_ace=mean(ace), avg_tornadoes=mean(tornadoes), .groups="drop")
base <- decade_summary %>% filter(decade=="1994-1999")
decade_norm <- decade_summary %>%
  mutate(temp_pct=(avg_temp/base$avg_temp-1)*100,
         hurr_pct=(avg_hurricanes/base$avg_hurricanes-1)*100,
         ace_pct=(avg_ace/base$avg_ace-1)*100) %>%
  select(decade, temp_pct, hurr_pct, ace_pct) %>%
  pivot_longer(-decade, names_to="metric", values_to="pct_change") %>%
  mutate(
    metric=case_when(
      metric=="temp_pct"~paste0("Temperature (", deg, "C)"),
      metric=="hurr_pct"~"Major Hurricanes",
      metric=="ace_pct"~"Storm Intensity (ACE)"),
    decade=factor(decade, levels=c("1994-1999","2000-2009","2010-2019","2020-2023")))
 
# Build named color vector separately — dynamic names can't be used as keys inside c()
fill_colors <- c(COL_ORANGE, COL_TEAL, COL_YELLOW)
names(fill_colors) <- c(paste0("Temperature (", deg, "C)"), "Major Hurricanes", "Storm Intensity (ACE)")
 
p5 <- ggplot(decade_norm %>% filter(decade!="1994-1999"),
             aes(x=decade, y=pct_change, fill=metric)) +
  geom_col(position="dodge", alpha=0.9, width=0.65) +
  geom_hline(yintercept=0, color=COL_LIGHT, linewidth=0.5) +
  geom_text(aes(label=paste0(ifelse(pct_change>=0,"+",""), round(pct_change,0), "%"),
                vjust=ifelse(pct_change>=0,-0.4,1.3)),
            position=position_dodge(width=0.65),
            color=COL_LIGHT, size=3.5, fontface="bold") +
  scale_fill_manual(values=fill_colors) +
  scale_y_continuous(labels=function(x) paste0(x, "%")) +
  labs(title="Temperature rise drives up storm intensity and major hurricanes",
       subtitle="",
       x=NULL, y="% Change vs. 1994-1999",
       fill=NULL,
       caption="") +
  theme_storm() +
  theme(legend.position="bottom", legend.text=element_text(size=11))
ggsave("chart5_decade_comparison.png", p5, width=10, height=5.5, dpi=150, bg=BG_DARK)
p5