# moorfields-table.R
# Rebuilds Table 1 from part 3 for the export examples in part 5.
# Creates: cohort, tbl (a gtsummary table), and table_gt (the styled gt table).
# Run it from the lesson folder, with moorfields_baseline.csv in data/.

library(gtsummary)

cohort <- read.csv("data/moorfields_baseline.csv", na.strings = c("", "NA"))
cohort$sex <- factor(cohort$sex, levels = c("Female", "Male"))
cohort$baseline_vision <- factor(
  cohort$baseline_vision,
  levels = c("Poor", "Intermediate", "Good")
)

tbl <- tbl_summary(
  cohort,
  by = baseline_vision,
  include = c(age, sex, baseline_va),
  type = list(sex ~ "categorical"),
  label = list(
    age ~ "Recorded baseline age, years",
    sex ~ "Sex",
    baseline_va ~ "Baseline visual acuity, ETDRS letters"
  ),
  statistic = list(
    all_continuous() ~ "{mean} ({sd})",
    all_categorical() ~ "{n} ({p}%)"
  ),
  digits = list(all_continuous() ~ 1),
  missing_text = "Missing"
) |>
  add_overall() |>
  add_n(col_label = "**Available N**") |>
  bold_labels() |>
  modify_header(label ~ "**Characteristic**")

table_gt <- as_gt(tbl) |>
  gt::tab_header(
    title = gt::md("**Table 1. The Moorfields teaching cohort**"),
    subtitle = "Baseline characteristics by visual acuity"
  ) |>
  gt::tab_spanner(
    label = "Baseline visual acuity",
    columns = c(stat_1, stat_2, stat_3)
  ) |>
  gt::cols_align(align = "center", columns = c(n, stat_0, stat_1, stat_2, stat_3)) |>
  gt::tab_source_note(
    "Teaching analysis of public Moorfields data (Fasler et al., 2019). One baseline record per patient; age values are coarsened."
  ) |>
  gt::tab_source_note(
    "Vision groups: Poor ≤35; Intermediate >35 and <70; Good ≥70 ETDRS letters."
  ) |>
  gt::opt_row_striping() |>
  gt::tab_options(
    heading.align = "left",
    table.font.names = c("Arial", "sans-serif"),
    table.font.size = gt::px(13),
    table.font.color = "#243746",
    table.background.color = "#FFFFFF",
    column_labels.background.color = "#003B49",
    column_labels.border.bottom.color = "#00A6A6",
    row.striping.background_color = "#F0F7F7",
    data_row.padding = gt::px(8)
  ) |>
  gt::tab_style(
    style = gt::cell_text(color = "#FFFFFF", weight = "bold"),
    locations = gt::cells_column_labels()
  )
