# # install.packages(c("pxweb","dplyr"))
# library(pxweb)
# library(dplyr)
# 
# url <- "https://www.pxweb.bfs.admin.ch/api/v1/de/px-x-1305000000_101/px-x-1305000000_101.px"
# 
# pxq <- pxweb_query(list(
#   "Beobachtungseinheit"             = c("1"),          # Anzahl Renten
#   "Rententyp"                       = c("10"),         # Altersrente
#   "Wohnsitzstaat (Kategorie)"       = c("1","2"),      # 1=Schweiz, 2=Ausland  (Total = ¯99999)
#   "Staatsangehörigkeit (Kategorie)" = c("1"),          # Total
#   "Geschlecht"                      = c("1"),          # Total
#   "Jahr"                            = as.character(2002:2024)
# ))
# 
# pxd <- pxweb_get(url, query = pxq)
# 
# # Use TEXT column names so we can regex-match, but keep CODE values (1/2) for easy recoding.
# df_raw <- as.data.frame(pxd, column.name.type = "text", variable.value.type = "code")
# 
# # Identify columns
# dom_col  <- grep("^Wohnsitzstaat", names(df_raw), value = TRUE)
# year_col <- "Jahr"
# # The measure/value column is always the last one returned by pxweb::as.data.frame()
# val_col  <- tail(names(df_raw), 1)
# 
# df <- df_raw |>
#   transmute(
#     year      = as.integer(.data[[year_col]]),
#     domicile  = recode(.data[[dom_col]], `1` = "Schweiz", `2` = "Ausland"),
#     n_pensions = as.numeric(.data[[val_col]])
#   ) |>
#   arrange(domicile, year)
# 
# # YoY growth by domicile
# growth <- df |>
#   group_by(domicile) |>
#   arrange(year, .by_group = TRUE) |>
#   mutate(growth_pct = 100 * (n_pensions / dplyr::lag(n_pensions) - 1)) |>
#   ungroup()
# 
# growth
# 
# 
# pxd <- pxweb_get(url, query = pxq)
# 
# # Use TEXT column names so we can regex-match, but keep CODE values (1/2) for easy recoding.
# df_raw <- as.data.frame(pxd, column.name.type = "text", variable.value.type = "code")

RENTEN <- 
  read_delim("~/data/appl-wb/20_staff/kjo/px-x-1305000000_101_20250924-114029.csv", 
             delim = ";") %>% 
  pivot_longer(cols = `2001`:`2024`, names_to = "Jahr", values_to = "n") %>% 
  summarize(n = sum(n), .by = c("Wohnsitzstaat", "Jahr")) %>% 
  mutate(w_pen = (n / lag(n) - 1) * 100) %>% 
  filter(Jahr >= 2002)

ggplot(RENTEN, aes(x = as.factor(Jahr), y = w_pen, fill = Wohnsitzstaat)) +
  geom_col(position = "dodge") +
  theme(axis.text.x = element_text(angle = 45, vjust = .5))
