# gt helpers for Card (1993) replication tables.
source(here("04-topics/rep-ak1991/Rcode/ak1991-gt-quarto.R"))

card93_digits <- 3L

card93_fmt_num <- function(x, digits = card93_digits) {
  sprintf(paste0("%.", digits, "f"), as.numeric(x))
}

card93_coef_cell <- function(estimate, std.error, digits = card93_digits) {
  if (is.na(estimate) || is.na(std.error)) {
    return("--")
  }
  paste0(
    card93_fmt_num(estimate, digits),
    "<br>(",
    card93_fmt_num(std.error, digits),
    ")"
  )
}

card93_fix_gt_tbl <- function(x) {
  ak91_fix_gt_tbl(x, disable_quarto = TRUE)
}

# Quarto-safe gt finish: no tab_header / table.width pct (avoids 10000px layout bug).
card93_gt_standard <- function(
    gt_tbl,
    stub_col = 1L,
    data_cols = NULL,
    header_rows = NULL) {
  col_names <- names(gt_tbl[["_data"]])
  if (is.null(data_cols)) {
    data_cols <- if (is.character(stub_col)) {
      setdiff(col_names, stub_col)
    } else {
      col_names[-stub_col]
    }
  }
  data_col_names <- if (is.numeric(data_cols)) {
    col_names[data_cols]
  } else {
    data_cols
  }
  out <- gt_tbl |>
    cols_align(align = "left", columns = all_of(stub_col)) |>
    cols_align(align = "center", columns = all_of(data_col_names)) |>
    fmt_markdown(columns = all_of(data_col_names)) |>
    opt_row_striping() |>
    tab_options(
      table.font.size = px(13),
      column_labels.font.weight = "bold",
      data_row.padding = px(5),
      quarto.disable_processing = TRUE
    )
  if (!is.null(header_rows) && length(header_rows) > 0L) {
    out <- out |>
      tab_style(
        style = cell_fill(color = "#f0f0f0"),
        locations = cells_body(rows = header_rows)
      ) |>
      tab_style(
        style = cell_text(weight = "bold"),
        locations = cells_body(rows = header_rows)
      )
  }
  out
}

# Left-align footer footnotes and source notes (gt default can appear centered in Quarto).
card93_gt_finalize <- function(gt_tbl) {
  gt_tbl |>
    tab_style(
      style = cell_text(align = "left"),
      locations = cells_footnotes()
    ) |>
    tab_style(
      style = cell_text(align = "left"),
      locations = cells_source_notes()
    )
}

# Row index in table_data matching exact stub label(s).
card93_stub_rows <- function(table_data, stub) {
  if (length(stub) == 1L) {
    which(table_data$stub == stub)
  } else {
    which(table_data$stub %in% stub)
  }
}

card93_gt_source_notes <- function(gt_tbl, notes) {
  for (note in notes) {
    gt_tbl <- gt_tbl |> tab_source_note(source_note = md(note))
  }
  gt_tbl
}

card93_gt_stub_footnote <- function(gt_tbl, table_data, stub, footnote) {
  rows <- card93_stub_rows(table_data, stub)
  gt_tbl |>
    tab_footnote(
      footnote = md(footnote),
      locations = cells_body(columns = stub, rows = rows)
    )
}

card93_gt_col_footnote <- function(gt_tbl, columns, footnote) {
  gt_tbl |>
    tab_footnote(
      footnote = md(footnote),
      locations = cells_column_labels(columns = all_of(columns))
    )
}
