# ==============================================================================
# 041O_Plot_Taxas_Liquida_Bruta_1992_2025.R
#
# Rascunho: taxas liquida e bruta de matricula na graduacao, 1992-2025,
# com IC 95%. Le a tabela do 041O_Extrair_Taxas_Liquida_Bruta_1992_2025.R;
# a selecao da serie (fonte por ano, geografia, universo) esta em
# 041O_Serie_Padrao.R e segue as convencoes do projeto: PNAD Anual ate 2015,
# PNADC desde 2016, D03 vigente (rural Norte so na PNADC).
# Serie unica, sem sobrepor as duas pesquisas (decisao do autor, 2026-10-10).
# 2025 desenhado como os demais anos; a nota registra que e o primeiro ano da
# nova Amostra Mestra da PNADC (3o tri/2025, NT IBGE 03/2025).
#
# Salva em output/graphs/ (rascunho); nao promove.
# ==============================================================================

suppressPackageStartupMessages({
  library(ggplot2)
  library(patchwork)
  library(dplyr)
})
source(here::here("shared-pipeline", "utils", "plot_theme.R"))
source(here::here("posts", "taxas-liquida-bruta-graduacao", "041O_Serie_Padrao.R"))

# ODA: a tabela de estimativas agregadas (taxa, IC e fonte por ano) e
# redistribuida em data/. Ela sai de 041O_Extrair_Taxas_Liquida_Bruta_1992_2025.R.
tab <- read.csv(here::here("posts", "taxas-liquida-bruta-graduacao", "data",
                           "041O_taxas_liquida_bruta_1992_2025.csv"))

# Rotulos em ingles, como as demais figuras da tese (capitulo 0302).
INDICADORES <- c(bruta_grad = "Gross rate", liquida_grad = "Net rate")
CORES <- c("Gross rate" = PALETA_QUALITATIVA[1], "Net rate" = COR_POSITIVO)
ANO_PROVISORIO <- NA_integer_
PROMOVER <- TRUE

principal <- serie_padrao_041O(tab, names(INDICADORES)) |>
  mutate(serie = factor(INDICADORES[indicador], levels = INDICADORES)) |>
  arrange(serie, ano) |>
  group_by(serie) |>
  mutate(segmento = cumsum(c(1L, diff(ano) > 1L | fonte[-1] != fonte[-n()]))) |>
  ungroup()

# 2025 deixou de ser "provisorio" (2026-10-10): a versao vigente do microdado
# (PNADC_2025_visita1_20260923) e identica a do cache (20260508) em pessoas,
# pesos e V3003A, e a serie usa a mesma ponderacao em todos os anos. A camada
# provisoria fica desligada (ANO_PROVISORIO = NA) e pode ser religada.
firme <- filter(principal, is.na(ANO_PROVISORIO) | ano != ANO_PROVISORIO)
# Segmento de um ano so: a faixa de IC nao aparece com um ponto, entao vira
# barra vertical (hoje nenhum ano cai nesse caso; a camada fica por seguranca).
isolados <- firme |>
  group_by(serie, segmento) |> filter(n() == 1L) |> ungroup()
provisorio <- principal |>
  filter(ano %in% c(ANO_PROVISORIO - 1L, ANO_PROVISORIO))

escala_x <- scale_x_anos_tese(anos = 1992:2025, limits = c(1992, 2025),
                              expand = expansion(mult = c(0.015, 0.02)))

grafico <- ggplot(mapping = aes(ano, taxa_pct, colour = serie, fill = serie)) +
  geom_ribbon(data = firme, aes(ymin = ic_inf, ymax = ic_sup,
              group = interaction(serie, segmento)),
              alpha = 0.22, colour = NA) +
  geom_line(data = firme, aes(group = interaction(serie, segmento)),
            linewidth = 0.7) +
  # show.legend = FALSE: a legenda mostra so linha, ponto e faixa de IC; as
  # camadas de 2025 e dos pontos isolados nao entram nela.
  geom_linerange(data = isolados, aes(ymin = ic_inf, ymax = ic_sup),
                 linewidth = 0.5, show.legend = FALSE) +
  geom_point(data = firme, size = 1.1) +
  geom_line(data = provisorio, aes(group = serie), linewidth = 0.6,
            linetype = "22", show.legend = FALSE) +
  geom_linerange(data = filter(principal, ano == ANO_PROVISORIO),
                 aes(ymin = ic_inf, ymax = ic_sup), linewidth = 0.5,
                 show.legend = FALSE) +
  geom_point(data = filter(principal, ano == ANO_PROVISORIO),
             shape = 21, fill = "white", size = 1.6, stroke = 0.7,
             show.legend = FALSE) +
  escala_x +
  scale_y_continuous(limits = c(0, 52), breaks = seq(0, 50, 10),
                     labels = function(x) paste0(x, "%"),
                     expand = expansion(mult = c(0, 0))) +
  # Identificacao das series em legenda externa, embaixo do painel, e nao em
  # rotulos dentro da imagem (decisao do autor, 2026-10-10; mesmo padrao do
  # Painel B do 222). Cor e preenchimento tem o mesmo nome e os mesmos niveis,
  # entao o ggplot funde as duas escalas numa so legenda (linha + faixa de IC).
  scale_colour_manual(values = CORES, name = NULL) +
  scale_fill_manual(values = CORES, name = NULL) +
  labs(x = NULL, y = "Undergraduate enrollment (% of population aged 18–24)") +
  thesis_theme() +
  theme(panel.grid.minor = element_blank(),
        legend.position = "bottom",
        legend.margin = margin(t = 0))

faixa <- banner_governos(fim_dados = 2025, scale_x = escala_x)
figura <- faixa / grafico + plot_layout(heights = c(1, 12))

salvar_grafico(figura, "041O_Taxas_Liquida_Bruta_1992_2025",
               altura = ALTURA_PADRAO + 0.4)
salvar_grafico(figura, "041O_Taxas_Liquida_Bruta_1992_2025",
               altura = ALTURA_PADRAO + 0.4, formato = "pdf")

if (PROMOVER) {
  finalizar_figura(
    plot = figura,
    fig_label = "taxas-liquida-bruta-graduacao",
    fig_cap = "Net and gross undergraduate enrollment rates, Brazil, 1992–2025.",
    nota = paste0(
      "Net rate: share of 18--24-year-olds attending an undergraduate course. ",
      "Gross rate: undergraduate students of any age as a share of the 18--24 ",
      "population. Graduate study excluded; whole population, including people ",
      "with undeclared income. Shaded bands: 95\\% confidence intervals. ",
      "PNAD through 2015, PNAD Cont\\'{\\i}nua from 2016; the rural North, not ",
      "sampled by PNAD before 2004, is excluded from PNAD and retained in PNAD ",
      "Cont\\'{\\i}nua. 2020--2021 not shown. 2025 is the first year of the new ",
      "PNAD Cont\\'{\\i}nua master sample, phased in from the third quarter. ",
      "Labels along the top mark presidential terms."),
    fonte = "IBGE --- PNAD (1992--2015) and PNAD Contínua (2016--2025)",
    script_path = here::here("posts", "taxas-liquida-bruta-graduacao", "plot.R"),
    altura = ALTURA_PADRAO + 0.4
  )
}
