# Rscript chart.R data.csv figure.png
args <- commandArgs(trailingOnly = TRUE)
input <- if (length(args) >= 1) args[1] else "data.csv"
output <- if (length(args) >= 2) args[2] else "figure.png"
d <- read.csv(input, colClasses = "character", fileEncoding = "UTF-8")
stopifnot(nrow(d) > 0, all(nzchar(d$label)), all(grepl("^https://", d$source_url)))

ink <- "#142D45"
muted <- "#455566"
first_color <- function(field, fallback) {
  value <- d[[field]][1]
  if (length(value) && !is.na(value) && grepl("^#[0-9a-fA-F]{6}$", value)) value else fallback
}
header <- first_color("figure_header", "#20154A")
header_end <- first_color("figure_header_end", "#51318A")
paper <- first_color("figure_paper", "#F1EDFF")
type <- d$type[1]
n <- nrow(d)
palette <- d$mark_color
if (is.null(palette) || anyNA(palette) || any(!grepl("^#[0-9a-fA-F]{6}$", palette))) {
  palette <- rep_len(c("#6835CB", "#2457C4", "#B1277B", "#00756D", "#A64019"), n)
}
accent <- palette[1]
line <- "#C8D2E5"
blend <- function(color, base, fraction) {
  channels <- as.vector(col2rgb(base)) * (1 - fraction) + col2rgb(color) * fraction
  rgb(channels[1, ], channels[2, ], channels[3, ], maxColorValue = 255)
}
wash <- function(color, fraction = 0.09) blend(color, "white", fraction)
value_ink <- blend(palette, "#071427", 0.73)

png(output, width = 1120, height = 720, res = 120, type = "cairo", bg = paper)
par(mar = rep(0, 4), family = "sans", xaxs = "i", yaxs = "i")
plot.new()
plot.window(c(0, 1120), c(720, 0))

label <- function(x, y, content, size = 1, color = ink, bold = FALSE, align = 0) {
  text(x, y, content, cex = size, col = color, font = if (bold) 2 else 1,
       adj = c(align, 0.5))
}

paragraph <- function(x, y, content, columns, size = 0.92, color = muted, bold = FALSE) {
  lines <- strwrap(content, width = columns)
  if (!length(lines)) return(invisible(0))
  for (i in seq_along(lines)) label(x, y + (i - 1) * 26, lines[i], size, color, bold)
  invisible(length(lines))
}

gradient <- colorRampPalette(c(header, header_end))(160)
rasterImage(as.raster(matrix(gradient, nrow = 1)), 0, 138, 1120, 0)
rect(0, 138, 1120, 142, col = accent, border = NA)
title_lines <- paragraph(45, 52, d$title[1], 57, 1.6, "white", TRUE)
label(45, 74 + title_lines * 26, d$subtitle[1], 0.92, "#F5F5FF")
segments(45, 626, 1075, 626, col = line)
if ("figure_note" %in% names(d)) paragraph(45, 644, d$figure_note[1], 117, 0.76)
label(45, 702, "FARLIGHT NEWS", 0.77, value_ink[1], TRUE)
label(1075, 702, "Source URLs are in the accompanying data", 0.72, muted, align = 1)

if (type %in% c("bar", "composition")) {
  values <- as.numeric(d$value)
  stopifnot(all(is.finite(values)), all(values >= 0), max(values) > 0)
  if (type == "composition") {
    total <- sum(values)
    shares <- values / total
    bounds <- 45 + 1030 * c(0, cumsum(shares))
    label(45, 188, paste0("$", format(total, trim = TRUE), "B"), 2.15, ink, TRUE)
    label(1075, 188, "Modeled receipts", 0.98, muted, align = 1)
    rect(head(bounds, -1), 226, tail(bounds, -1), 276,
         col = palette, border = NA)
    y <- seq(316, 580, length.out = n)
    rect(45, y - 24, 1075, y + 24, col = wash(palette), border = NA)
    rect(45, y - 24, 50, y + 24, col = palette, border = NA)
    points(rep(65, n), y, pch = 16, col = palette, cex = 0.95)
    label(85, y, d$label, 1, ink, TRUE)
    dollars <- ifelse(values < 1, paste0("$", values * 1000, "M"), paste0("$", values, "B"))
    label(895, y, dollars, 1, value_ink, TRUE, 1)
    label(1075, y, sprintf("%.2f%%", shares * 100), 1, muted, align = 1)
  } else {
    step <- if (max(values) >= 100) 50 else 5
    top <- if (d$unit[1] == "Percent of population") 100 else ceiling(max(values) / step) * step
    axis <- unique(c(pretty(c(0, top)), top))
    axis <- axis[axis >= 0 & axis <= top]
    left <- max(170, 62 + strwidth(d$label, units = "user", cex = 1.1, font = 2))
    span <- 975 - left
    x <- left + span * axis / top
    segments(x, 186, x, 552, col = line)
    label(x, 576, axis, 0.78, muted, align = 0.5)
    y <- seq(245, 490, length.out = n)
    ends <- left + span * values / top
    rect(left, y - 25, left + span, y + 25, col = wash(palette, 0.12), border = NA)
    rect(left, y - 25, ends, y + 25, col = palette, border = NA)
    label(45, y, d$label, 1.1, ink, TRUE)
    label(ends + 16, y, d$value, 1.12, value_ink, TRUE)
    label(left, 604, d$unit[1], 0.8, muted)
  }
} else if (type == "timeline") {
  dates <- as.Date(d$value)
  stopifnot(all(!is.na(dates)))
  elapsed <- as.numeric(dates - min(dates))
  points_x <- 60 + 1000 * elapsed / max(1, elapsed)
  segments(60, 189, 1060, 189, col = line, lwd = 2)
  segments(points_x, 174, points_x, 204, col = palette, lwd = 3)
  label(60, 229, format(min(dates), "%b %d"), 0.81, muted)
  label(1060, 229, format(max(dates), "%b %d"), 0.81, muted, align = 1)
  y <- seq(279, 563, length.out = n)
  rect(45, y - 20, 1075, y + 44, col = wash(palette), border = NA)
  rect(45, y - 20, 50, y + 44, col = palette, border = NA)
  label(61, y, format(dates, "%b %d, %Y"), 0.94, value_ink, TRUE)
  label(266, y, d$label, 1.02, ink, TRUE)
  label(266, y + 25, d$detail, 0.78, muted)
} else if (type == "sequence") {
  steps <- seq(62, 1058, length.out = n + 1)
  arrows(steps[1], 249, tail(steps, 1), 249, col = accent, lwd = 2.5, length = 0.12)
  for (i in seq_len(n)) {
    x <- steps[i] + 24
    rect(steps[i]-8, 277, steps[i+1]-14, 507, col = wash(palette[i]), border = NA)
    rect(steps[i]-8, 277, steps[i+1]-14, 282, col = palette[i], border = NA)
    points(x, 249, pch = 16, cex = 2.5, col = palette[i])
    label(x, 249, i, 0.81, "white", TRUE, 0.5)
    paragraph(steps[i], 199, d$value[i], 24, 0.94, value_ink[i], TRUE)
    lines <- paragraph(steps[i], 309, d$label[i], 21, 1.12, ink, TRUE)
    paragraph(steps[i], 324 + 28 * lines, d$detail[i], 27, 0.92)
  }
} else if (type == "topics") {
  columns <- min(n, 3)
  gap <- 15
  width <- (1030 - (columns - 1) * gap) / columns
  multiline <- n > columns
  height <- if (multiline) 210 else 305
  for (i in seq_len(n)) {
    x <- 45 + ((i - 1) %% columns) * (width + gap)
    y <- 160 + ((i - 1) %/% columns) * (height + gap)
    color <- palette[i]
    rect(x, y, x + width, y + height, col = wash(color), border = line)
    rect(x, y, x + width, y + 8, col = color, border = NA)
    prefix <- d$value[i]
    columns_text <- 29
    prefix_lines <- paragraph(x + 14, y + 27, prefix, columns_text, 0.84, value_ink[i], TRUE)
    title_y <- y + 27 + 27 * prefix_lines + 8
    headline <- paragraph(x + 14, title_y, d$label[i], columns_text, 0.98, ink, TRUE)
    paragraph(x + 14, title_y + headline * 26 + 7, d$detail[i], columns_text + 8, 0.78)
  }
} else {
  stop("Unsupported figure type")
}

invisible(dev.off())
