library(ggforma)
library(grid)
library(systemfonts)

options <- list(sans = c("Arial", "Liberation Sans", "DejaVu Sans"), ar = c("Arial", 
"Noto Sans Arabic", "DejaVu Sans"), he = c("Arial", "Noto Sans Hebrew", 
"DejaVu Sans"))
installed <- system_fonts()$family
fonts <- vapply(options, function(x) {
  found <- intersect(x, installed)
  if (!length(found)) stop('Choose a suitable installed local font for ', paste(x, collapse = ', '))
  found[1L]
}, character(1))

sheet <- function(title, subtitle) {
  grid.newpage()
  grid.draw(markup_grob(title, format = "plain", x = .055, y = .925, hjust = 0,
                        size = 22, family = fonts["sans"], face = "bold", colour = "#172C3C"))
  grid.draw(markup_grob(subtitle, format = "plain", x = .055, y = .810, hjust = 0,
                        size = 10, family = fonts["sans"], colour = "#465865"))
  grid.lines(x = c(.055, .945), y = c(.745, .745), gp = gpar(col = "#CED7DA", lwd = .8))
}

note <- function(text, x, y, size = 17, family = fonts["sans"], ...) {
  grid.draw(markup_grob(text, x = x, y = y, size = size, family = family,
                        colour = "#172C3C", hjust = 0, ...))
}

key <- function(text, x, y) note(text, x, y, size = 9, face = "bold", format = "plain")

bidi <- function() {
  sheet("Reading across directions", "Arabic and Hebrew place a series ID, digits and an inline formula inside RTL text.")
  rows <- c(ar = "بيانات <span style='color:#0072B2'>المكتبة</span> (Series A): 2026، المتوسط $bar(x)$.",
            he = "נתונים <span style='color:#0072B2'>לדוגמה</span> (Series B): 2026, הממוצע $bar(x)$.")
  for (i in seq_along(rows)) {
    lang <- names(rows)[i]
    key(c("ARABIC", "HEBREW")[i], .067, c(.63, .365)[i])
    grid.draw(markup_grob(rows[i], format = "mixed", x = .93, y = c(.51, .24)[i],
              hjust = 1, size = 16, family = fonts[lang], lang = lang, text_direction = "rtl"))
  }
}

bidi()
