## =============================================================================
## CHART: MVA Quadrant — Management Decisions vs Injury Luck (1995-2025)
## X = avg(success_z + war_z) across eras  (pure management: talent eval + results)
## Y = avg(injury_z)           across eras  (health fortune)
## Single period; no faceting. 4 quadrants immediately tell the story.
## Color = management score (blue = low, red = high)
## =============================================================================

.linkedin_dir <- tryCatch(
  dirname(normalizePath(sub("--file=", "", grep("--file=", commandArgs(FALSE), value = TRUE)[1]))),
  error = function(e) getwd()
)
source(file.path(.linkedin_dir, "chart_theme.R"))

## Aggregate across eras to one composite row per team
mva_all <- team_era3[is.finite(mva_score) & !is.na(tier),
    .(
        mva_base = mean(success_z + war_z, na.rm = TRUE),
        injury_z = mean(injury_z,          na.rm = TRUE),
        short    = short[.N]     ## most recent era label
    ),
    by = teamID
]

## Axis limits — symmetric with padding for labels
x_abs <- max(abs(mva_all$mva_base), na.rm = TRUE) + 0.5
y_abs <- max(abs(mva_all$injury_z),  na.rm = TRUE) + 0.5
x_lim <- c(-x_abs, x_abs)
y_lim <- c(-y_abs, y_abs)

## Quadrant label positions (4 corners of the single panel)
quad_lbl <- data.table(
    x     = c(-x_abs * 0.96,  x_abs * 0.96, -x_abs * 0.96,  x_abs * 0.96),
    y     = c( y_abs * 0.96,  y_abs * 0.96, -y_abs * 0.96, -y_abs * 0.96),
    hjust = c(0, 1, 0, 1),
    vjust = c(1, 1, 0, 0),
    label = c(
        "Health luck covered\npoor decisions",
        "Elite management\n+ stayed healthy",
        "Poor management\ncompounded by injury",
        "Elite management\ngot unlucky"
    )
)

p_quad <- ggplot(mva_all, aes(x = mva_base, y = injury_z)) +
    ## quadrant shading
    annotate("rect", xmin = 0, xmax =  Inf, ymin =  0,   ymax =  Inf,
             fill = "#d9f0e8", alpha = 0.35) +   ## top-right: elite + healthy
    annotate("rect", xmin = 0, xmax =  Inf, ymin = -Inf, ymax =  0,
             fill = "#fff3cd", alpha = 0.35) +   ## bottom-right: elite + unlucky
    annotate("rect", xmin = -Inf, xmax = 0, ymin =  0,   ymax =  Inf,
             fill = "#fce8e8", alpha = 0.35) +   ## top-left: lucky + poor mgmt
    annotate("rect", xmin = -Inf, xmax = 0, ymin = -Inf, ymax =  0,
             fill = "#f0e8f8", alpha = 0.35) +   ## bottom-left: poor + injured
    ## axis lines
    geom_hline(yintercept = 0, linetype = "dashed", colour = "grey50", linewidth = 0.6) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey50", linewidth = 0.6) +
    ## quadrant labels
    geom_text(data = quad_lbl,
              aes(x = x, y = y, label = label, hjust = hjust, vjust = vjust),
              colour = "grey55", size = 3.8, lineheight = 1.2, inherit.aes = FALSE) +
    ## team points — colour by management score (blue=low, red=high), consistent with all slides
    geom_point(aes(colour = mva_base), size = PT_SIZE, alpha = PT_ALPHA) +
    ## team labels using common abbreviations
    ggrepel::geom_label_repel(aes(label = short),
                             size = LBL_SIZE, fontface = "bold",
                             fill = alpha("white", 0.75),
                             label.padding = unit(0.15, "lines"),
                             label.size = NA,
                             seed = 42,
                             max.overlaps = Inf,
                             box.padding = 0.5,
                             point.padding = 0.3,
                             min.segment.length = 0,
                             force = 2,
                             show.legend = FALSE) +
    scale_colour_gradient(low = COL_HI, high = COL_LO,
                          name = "Management score\n(blue = strong)",
                          guide = std_colourbar()) +
    scale_x_continuous(limits = x_lim, breaks = seq(-4, 4, by = 1)) +
    scale_y_continuous(limits = y_lim, breaks = seq(-4, 4, by = 1)) +
    labs(
        title    = "Management Quality vs Injury Luck (1995-2025)",
        subtitle = paste0(
            "Injury luck is the great equalizer: it can make elite managers look average and mask poor decisions entirely.\n",
            "Scores averaged across three eras (1998\u20132024)."
        ),
        caption = paste0(
            "Based on qualifying free-agent contracts (6+ yrs MLB service, salary > $2M/yr, tenure >= 2 yrs).\n",
            "Scores averaged across Pre-Moneyball (1998-2002), Moneyball (2003-2011), and Big Data (2012-2024) eras.\n",
            "Injury proxy: batter G < 60% of 150 expected, or starter GS < 60% of 30 expected.\n",
            AUTHOR_LINE, "  |  Data: Lahman Database, Spotrac, USA Today"
        ),
        x = "Management decisions score (composite z, era-averaged)",
        y = "Injury luck score (z, era-averaged)"
    ) +
    theme_story() +
    theme(
        plot.title = element_text(face = "bold", size = 16, colour = COL_ACCENT,
                                  margin = margin(b = 4))
    )

out_dir <- file.path(path.expand(Sys.getenv("LAHMANS_DBDIR", "~/Documents/Data/baseball")),
                     "charts")
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
ggsave(file.path(out_dir, "mva_quadrant.png"), p_quad, width = 10, height = 7, dpi = 300,
       device = ragg::agg_png)
saveRDS(p_quad, file.path(out_dir, "mva_quadrant.rds"))
