# 1. 必要なライブラリ
library(FactoMineR)
library(ggplot2)
library(dplyr)
## 
## 次のパッケージを付け加えます: 'dplyr'
## 以下のオブジェクトは 'package:stats' からマスクされています:
## 
##     filter, lag
## 以下のオブジェクトは 'package:base' からマスクされています:
## 
##     intersect, setdiff, setequal, union
library(ggrepel)

# 2. キャプション定義 (AONF format)
AONF_CAPTION <- "Archives from 2026 Onward and Notes for the Future\n2026年以降の記録 | https://ab.cocolog-nifty.com/note/"

# 3. データの読み込み
# 列名がどう化けていても、1列目を強制的に "Municipality" に固定します
load_and_fix <- function(path) {
  df <- read.csv(path, check.names = FALSE, fileEncoding = "UTF-8-BOM")
  if (ncol(df) <= 1) df <- read.csv(path, check.names = FALSE, fileEncoding = "UTF-8")
  colnames(df)[1] <- "Municipality" 
  return(df)
}

# --- 2024年データ準備 ---
data2024 <- load_and_fix("data11ku_PC_fixed.csv") %>%
  rename(自民党=LDP, 民主党=DPP, 共産党=JCP, 維新=JIP, 社民党=SDP, れいわ=RS, 参政=SAN, 立憲_24=CDP, 公明_24=NKP) %>%
  mutate(Municipality_ID = paste0(Municipality, "_24"),
         Tsuji=0.1, Inoue=0.1, 保守党=0.1, 中道=0.1, ゆうこく連合=0.1, みらい=0.1) 
         # ※ 0ではなく0.1(微小値)を入れることで、2024年基準の空間に「存在」させます

# --- 2026年データ準備 ---
data2026 <- load_and_fix("fukuoka11ku2026_merged_a.csv") %>%
  mutate(Municipality_ID = paste0(Municipality, "_26"), 立憲_24=0, 公明_24=0)

# --- 列順の統一と結合 ---
col_order <- c("Municipality_ID", "Tsuji", "Takeda", "Shiki", "Inoue", "Murakami", 
               "れいわ", "保守党", "自民党", "中道", "ゆうこく連合", "みらい", 
               "社民党", "維新", "参政", "民主党", "共産党", "立憲_24", "公明_24")

fukuoka_combined <- rbind(data2024[, col_order], data2026[, col_order])
row.names(fukuoka_combined) <- fukuoka_combined$Municipality_ID
fukuoka_matrix <- as.data.frame(fukuoka_combined[, -1])

# 4. 投影分析 (CA) の実行
# 2024年(1-15行)を基準に、2026年(16-30行)を投影
res_ca <- CA(fukuoka_matrix, row.sup = 16:30, graph = FALSE)

# 5. 可視化データの作成
plot_data <- rbind(
  as.data.frame(res_ca$row$coord) %>% mutate(Type = "2024自治体", Label = rownames(.)),
  as.data.frame(res_ca$row.sup$coord) %>% mutate(Type = "2026自治体", Label = rownames(.)),
  as.data.frame(res_ca$col$coord) %>% mutate(Type = "政党・候補者", Label = rownames(.))
)

# 6. ggplot2 による描画
ggplot(plot_data, aes(x = `Dim 1`, y = `Dim 2`, color = Type)) +
  geom_hline(yintercept = 0, linetype = "dashed", alpha = 0.3) +
  geom_vline(xintercept = 0, linetype = "dashed", alpha = 0.3) +
  geom_point(aes(shape = Type), size = 3) +
  geom_text_repel(aes(label = Label), family = "HiraKakuProN-W3", size = 3, max.overlaps = 25) +
  scale_color_manual(values = c("2024自治体" = "blue", "2026自治体" = "darkblue", "政党・候補者" = "red")) +
  theme_minimal(base_family = "HiraKakuProN-W3") +
  theme(legend.position = "bottom", plot.caption = element_text(size = 8)) +
  labs(title = "2024 Baseline Correspondence Analysis: Fukuoka 11th District",
       subtitle = "2024年の構造を物差しに、2026年の『地殻変動』を捉える",
       caption = AONF_CAPTION)

# 1. 第2次元・第3次元のプロット用データ抽出
# ※ res_ca は前回の計算結果(CAオブジェクト)をそのまま使用します
plot_data_23 <- rbind(
  as.data.frame(res_ca$row$coord) %>% mutate(Type = "2024自治体", Label = rownames(.)),
  as.data.frame(res_ca$row.sup$coord) %>% mutate(Type = "2026自治体", Label = rownames(.)),
  as.data.frame(res_ca$col$coord) %>% mutate(Type = "政党・候補者", Label = rownames(.))
)

# 2. ggplot2 による描画 (Dim 2 vs Dim 3)
p23 <- ggplot(plot_data_23, aes(x = `Dim 2`, y = `Dim 3`, color = Type)) +
  geom_hline(yintercept = 0, linetype = "dashed", alpha = 0.3) +
  geom_vline(xintercept = 0, linetype = "dashed", alpha = 0.3) +
  geom_point(aes(shape = Type), size = 3) +
  geom_text_repel(aes(label = Label), family = "HiraKakuProN-W3", size = 3, max.overlaps = 25) +
  scale_color_manual(values = c("2024自治体" = "blue", "2026自治体" = "darkblue", "政党・候補者" = "red")) +
  theme_minimal(base_family = "HiraKakuProN-W3") +
  theme(legend.position = "bottom", 
        plot.caption = element_text(size = 8, hjust = 1)) +
  labs(title = "2024 Baseline CA: Dimension 2 vs Dimension 3",
       subtitle = "第1次元の巨大な変動(時系列差)を除いた、より詳細な勢力構造の分析",
       x = paste0("Dimension 2 (", round(res_ca$eig[2, 2], 1), "%)"),
       y = paste0("Dimension 3 (", round(res_ca$eig[3, 2], 1), "%)"),
       caption = AONF_CAPTION)

print(p23)