library(widr)

# ── .wid() ────────────────────────────────────────────────────────────────────
# Returns a wid_df with n rows PER country.
#   n         : rows per country (default 2; ensures resolve_var multi-var test works)
#   type      : series-type letter   (default "s")
#   countries : country codes        (default "US")
#
# Year sequence starts at 2020 and increments by 1 for each row within a country,
# so all countries share the same set of years — required by wid_plot_compare.
#
# Examples:
#   .wid()                       → 2 rows, US, years 2020–2021
#   .wid(5)                      → 5 rows, US, years 2020–2024
#   .wid(3, type = "a")          → 3 rows, US, type "a"
#   .wid(5, countries = c("US","FR"))  → 10 rows, 5 per country, years 2020–2024
.wid <- function(n = 2L, type = "s", countries = "US") {
  yrs <- as.character(seq(2020L, length.out = n))
  df  <- data.frame(
    country    = rep(countries, each = n),
    variable   = paste0(type, "ptinc992j"),
    percentile = "p99p100",
    year       = rep(yrs, times = length(countries)),
    value      = seq(0.2, length.out = n * length(countries), by = 0.01),
    age        = "992",
    pop        = "j",
    stringsAsFactors = FALSE
  )
  widr:::new_wid_df(df)
}

# ── .wid_dist() ───────────────────────────────────────────────────────────────
# share-series wid_df with three percentile bands for one country and one year.
# Defaults: country="US", years=2020L  →  exactly 3 rows.
#
# Value layout:  p0p50 → 0.50 | p50p90 → 0.10 | p90p100 → 0.40
# wid_top_share(.wid_dist(), top=0.1)  →  share = 0.40, top = 0.1  (scalar)
#
# Build multi-country/year data by calling repeatedly:
#   rbind(.wid_dist("US"), .wid_dist("FR"))
#   rbind(.wid_dist("US", 2019L), .wid_dist("US", 2020L))
.wid_dist <- function(country = "US", years = 2020L) {
  bands <- list(c("p0p50", 0.50), c("p50p90", 0.10), c("p90p100", 0.40))
  rows  <- do.call(rbind, lapply(years, function(yr)
    do.call(rbind, lapply(bands, function(b)
      data.frame(
        country    = country,
        variable   = "sptinc992j",
        percentile = b[[1L]],
        year       = as.character(yr),
        value      = as.numeric(b[[2L]]),
        age        = "992",
        pop        = "j",
        stringsAsFactors = FALSE
      )))))
  widr:::new_wid_df(rows)
}

# ── .wid_t() ──────────────────────────────────────────────────────────────────
# threshold-series wid_df with p10 / p50 / p90 rows.
# P90/P10 = 200000/10000 = 20;   P90/P50 = 200000/50000 = 4.
.wid_t <- function(country = "US", year = "2020") {
  widr:::new_wid_df(data.frame(
    country    = country,
    variable   = "tptinc992j",
    percentile = c("p10", "p50", "p90"),
    year       = year,
    value      = c(10000, 50000, 200000),
    age        = "992",
    pop        = "j",
    stringsAsFactors = FALSE
  ))
}