library(here)
library(tidyverse)
library(gt)
source(here("04-topics/rep-chv2011/Rcode/chv2011-data-prep.R"))
source(here("04-topics/rep-chv2011/Rcode/chv2011-mte-core.R"))
source(here("04-topics/rep-chv2011/Rcode/chv2011-gt-quarto.R"))

B <- as.integer(Sys.getenv("CHV2011_BOOT", "50"))
res <- run_chv2011_spec("baseline", B_boot = B)

fmt_row <- function(label, est, se = NA, na_col2 = FALSE) {
  tibble(
    parameter = label,
    normal = if (na_col2) "Not Identified" else chv2011_coef_cell(est, se),
    semiparam = chv2011_coef_cell(est, se)
  )
}

norm <- res$normal
semi <- res$semiparam

rows <- c(
  "Average Treatment Effect (ATE)",
  "Treatment on the Treated (TT)",
  "Treatment on the Untreated (TUT)",
  "MPRTE: Z + alpha",
  "MPRTE: P + alpha",
  "MPRTE: (1 + alpha) P",
  "Linear IV (P(Z))",
  "OLS"
)

table_data <- tibble(
  parameter = rows,
  normal = c(
    chv2011_coef_cell(norm$estimate[1], NA),
    chv2011_coef_cell(norm$estimate[2], NA),
    chv2011_coef_cell(norm$estimate[3], NA),
    chv2011_coef_cell(norm$estimate[4], NA),
    chv2011_coef_cell(norm$estimate[5], NA),
    chv2011_coef_cell(norm$estimate[6], NA),
    chv2011_coef_cell(norm$estimate[7], NA),
    chv2011_coef_cell(norm$estimate[8], NA)
  ),
  semiparam = c(
    "Not Identified", "Not Identified", "Not Identified",
    chv2011_coef_cell(semi$estimate[4], semi$se[4]),
    chv2011_coef_cell(semi$estimate[5], semi$se[5]),
    chv2011_coef_cell(semi$estimate[6], semi$se[6]),
    chv2011_coef_cell(semi$estimate[7], semi$se[7]),
    chv2011_coef_cell(semi$estimate[8], semi$se[8])
  )
)

gt_tbl <- table_data |>
  chv2011_quarto_blank_df() |>
  gt() |>
  tab_header(
    title = "Table 5",
    subtitle = "Returns to a year of college (Normal vs semiparametric; annualized)"
  ) |>
  cols_label(
    parameter = " ",
    normal = "Normal model",
    semiparam = "Semiparametric model"
  )

save(table_data, gt_tbl, res, file = here("04-topics/rep-chv2011/Rcode/Table_5.RData"))
