# Recreate the landing-page figure from the installed release candidate.
library(ggforma)
library(ggplot2)
library(ragg)
library(systemfonts)

args <- commandArgs(TRUE)
out <- if (length(args)) args[1L] else "pkgdown/site-bilingual/figures"
dir.create(out, recursive = TRUE, showWarnings = FALSE)
stopifnot(as.character(packageVersion("ggforma")) == "0.1.0")
counts <- marginSums(datasets::HairEyeColor, c("Hair", "Eye"))
stopifnot(sum(counts) == 592, sum(counts["Blond", ]) == 127, counts["Blond", "Blue"] == 94)
terms <- data.frame(variable = rep(c("Hair", "Eye"), each = 4),
  id = unlist(dimnames(counts), use.names = FALSE), lang = "zh-CN",
  label = c("黑发", "棕发", "红发", "金发", "棕色", "蓝色", "淡褐色", "绿色"))
pal <- grDevices::palette.colors(palette = "Okabe-Ito")
fills <- setNames(pal[c(7, 6, 2, 4)], dimnames(counts)$Eye)
stopifnot(!anyNA(fills))
available <- system_fonts()$family
candidate <- intersect(c("Microsoft YaHei", "Noto Sans CJK SC", "PingFang SC"), available)
if (!length(candidate)) stop("Select an installed font covering Simplified Chinese.")
base <- ggmosaic(counts, shade = "category", category = "Eye", highlighting_fill = fills,
                 gap = 0, label = NULL, labeling = "none", border = "white", linewidth = .65)
for (lang in c("en", "zh")) {
  zh <- lang == "zh"
  face <- if (zh) candidate[1L] else "sans"
  labels <- if (zh) terms$label[1:4] else dimnames(counts)$Hair
  # Column centres are determined by the observed hair-colour margins.
  shares <- rowSums(counts) / sum(counts)
  centres <- cumsum(shares) - shares / 2
  plot <- base + if (zh) locale_forma("zh-CN", dictionary = terms, font_family = face) else locale_forma("en")
  plot <- plot + annotate("text", x = unname(centres), y = 1.055, label = labels,
                          family = face, size = 4.3) +
    coord_cartesian(xlim = c(0, 1), ylim = c(0, 1.12), expand = FALSE) +
    labs(fill = if (zh) "眼睛颜色" else "Eye colour") +
    theme_void(base_family = face) +
    theme(legend.position = "bottom", legend.text = element_text(size = 10),
          legend.title = element_text(size = 10), legend.key.size = grid::unit(.37, "cm"),
          plot.margin = margin(8, 14, 6, 14), plot.background = element_rect(fill = "white", colour = NA))
  ggsave(file.path(out, paste0("hair-eye-", lang, ".png")), plot = plot,
         device = agg_png, width = 5.6, height = 3.5, units = "in", dpi = 160, bg = "white")
}
