// stats.js - UYAP JSON Robot İstatistikçi (DataTables + XLSX + Uyarılar/Toast)

// Storage keys
const KEY = "json_stats";
const SKEY = "json_stats_aggregates";
const RKEY = "json_stats_rows";
const BACKUP_KEY = "json_stats_backup";
const THEME_KEY = "uyap_theme";

const LOG_CAP = 200;

let filteredRows = null;
let isDetailOpening = false;
let currentUnit = "";

// -------------------- Theme -------------------- //
function applyTheme(theme) {
  const t = (window.setTheme ? window.setTheme(theme) : theme === "light" ? "light" : "dark");
  document.documentElement.setAttribute("data-theme", t);
  try { localStorage.setItem(THEME_KEY, t); } catch (_) {}
  const btn = document.getElementById("themeToggle");
  if (btn) btn.textContent = t === "light" ? "☀️" : "☾";
}

// -------------------- Toast -------------------- //
function ensureToastContainer() {
  let el = document.getElementById("toast-stack");
  if (el) return el;
  el = document.createElement("div");
  el.id = "toast-stack";
  Object.assign(el.style, {
    position: "fixed",
    top: "16px",
    right: "16px",
    zIndex: "99999",
    display: "flex",
    flexDirection: "column",
    gap: "8px"
  });
  document.body.appendChild(el);
  return el;
}

function showToast(msg, type = "info") {
  const stack = ensureToastContainer();
  const item = document.createElement("div");
  item.textContent = msg;
  Object.assign(item.style, {
    padding: "10px 12px",
    borderRadius: "10px",
    color: type === "error" ? "#2c0b0e" : "#041022",
    background: type === "error"
      ? "linear-gradient(135deg,#ff9aa2,#ff6b6b)"
      : "linear-gradient(135deg,#1f91ff,#6ce4ff)",
    boxShadow: "0 8px 20px rgba(0,0,0,0.25)",
    fontWeight: "600",
    minWidth: "240px"
  });
  stack.appendChild(item);
  setTimeout(() => item.remove(), 4000);
}

// -------------------- DataTables helpers -------------------- //
const dataTables = {};
const DT_LANG = {
  emptyTable: "Gösterilecek veri yok",
  info: "_TOTAL_ kayıttan _START_ - _END_ arası",
  infoEmpty: "Kayıt yok",
  infoFiltered: "(_MAX_ kayıt içinden süzüldü)",
  lengthMenu: "_MENU_ satır göster",
  loadingRecords: "Yükleniyor...",
  processing: "İşleniyor...",
  search: "Ara",
  zeroRecords: "Eşleşen kayıt bulunamadı",
  paginate: {
    first: "İlk",
    last: "Son",
    next: "Sonraki",
    previous: "Önceki"
  }
};

const BASE_DT_OPTIONS = {
  paging: true,
  pageLength: 10,
  responsive: true,
  searching: true,
  info: false,
  lengthChange: false,
  language: DT_LANG,
  columnDefs: [{ targets: "_all", className: "dt-center" }],
  layout: {
    topEnd: "search",
    bottomStart: "info",
    bottomEnd: "paging"
  }
};

function ensureDataTable(tableId, options = {}) {
  if (dataTables[tableId]) return dataTables[tableId];
  const cfg = { ...BASE_DT_OPTIONS, ...options };
  const table = new DataTable(`#${tableId}`, cfg);
  dataTables[tableId] = table;
  return table;
}

function exportWithButtons(headers, rows, filename = "export.xlsx", sheetName = "Export") {
  const wrapper = document.createElement("div");
  wrapper.style.position = "fixed";
  wrapper.style.left = "-9999px";
  const table = document.createElement("table");
  const id = `tmpExport_${Date.now()}`;
  table.id = id;
  wrapper.appendChild(table);
  document.body.appendChild(wrapper);

  const dt = new DataTable(`#${id}`, {
    data: rows,
    columns: headers.map(h => ({ title: h.title || h, data: h.key || h })),
    paging: false,
    searching: false,
    info: false,
    ordering: false,
    dom: "B",
    buttons: [{
      extend: "excelHtml5",
      title: sheetName,
      filename: filename.replace(/\.xlsx$/i, ""),
      exportOptions: { columns: headers.map((_, i) => i) }
    }]
  });

  dt.button(0).trigger();
  setTimeout(() => {
    try { dt.destroy(true); } catch (_) {}
    wrapper.remove();
  }, 1000);
}

// -------------------- Helpers -------------------- //
function escapeHtml(str) {
  return String(str ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function fmtDate(v) {
  if (!v) return "";
  try {
    const d = new Date(v);
    if (isNaN(d)) return v;
    const dd = String(d.getDate()).padStart(2, "0");
    const mm = String(d.getMonth() + 1).padStart(2, "0");
    const yy = d.getFullYear();
    return `${dd}.${mm}.${yy}`;
  } catch {
    return v;
  }
}

function normalizeText(str) {
  return String(str || "")
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/ç/g, "c").replace(/ğ/g, "g").replace(/ı/g, "i").replace(/ö/g, "o").replace(/ş/g, "s").replace(/ü/g, "u");
}

// -------------------- Log -------------------- //
function itemHtml(it) {
  const ts  = new Date(it.ts).toLocaleString("tr-TR");
  const c   = it?.picked?.count ?? it.count ?? 0;
  const src = it?.src || "page";
  const ins = it.inserted ?? 0;
  const upd = it.updated  ?? 0;
  const tot = it.total    ?? "";
  const extra = tot
    ? ` +${ins} yeni, ${upd} güncellendi, toplam ${tot} kayıt`
    : ` +${ins} yeni, ${upd} güncellendi`;
  return `<div class="log-row">
    <div><strong>${ts}</strong> • ${src.toUpperCase()}</div>
    <div>${c} kayıt geldi${extra ? " - " + extra : ""}</div>
  </div>`;
}

async function renderList() {
  const obj  = await chrome.storage.local.get(KEY);
  const list = obj[KEY] || [];
  const el   = document.getElementById("list");
  if (!el) return;
  el.innerHTML = list
    .slice()
    .reverse()
    .slice(0, LOG_CAP)
    .map(itemHtml)
    .join("");
}

// -------------------- Aggregates -------------------- //
function between(d, from, to) {
  if (!from && !to) return true;
  if (!d) return false;
  const x = new Date(d).getTime();
  if (!Number.isFinite(x)) return false;
  if (from && x < from) return false;
  if (to && x > to) return false;
  return true;
}

function getStatusText(r) {
  return (
    r.statuAcklm ||
    (r.statuBilgisi && r.statuBilgisi.aciklama) ||
    "-"
  );
}

function buildAggregatesFrom(rows) {
  const ag = { hakim: {}, savci: {}, katip: {}, statu: {} };
  const inc = (m, k) => {
    if (k == null && k !== 0) return;
    const s = String(k).trim();
    if (!s) return;
    m[s] = (m[s] || 0) + 1;
  };
  for (const it of rows) {
    [it.hukumHakimBaskanPId, it.hukumUye1PId, it.hukumUye2PId].forEach(h => inc(ag.hakim, h));
    inc(ag.savci, it.hukumSavciPId);
    inc(ag.katip, it.hukumKatipPId);
    inc(ag.statu, getStatusText(it));
  }
  return ag;
}

function buildYearMap(rows, field) {
  const map = {};
  for (const r of rows) {
    let v = r[field];
    if (field === "dosyaKapanisTarihi") v = r.dosyaKapanisTarihi || r.kapanisTarihi;
    if (!v) continue;
    const d = new Date(v);
    const y = d.getFullYear();
    if (!Number.isFinite(y)) continue;
    map[y] = (map[y] || 0) + 1;
  }
  return map;
}

function buildWarningsList(rows) {
  const list = [];
  const now = Date.now();
  const todayStart = new Date();
  todayStart.setHours(0, 0, 0, 0);
  const todayMs = todayStart.getTime();

  for (const r of rows) {
    const status = getStatusText(r);
    const statusNorm = normalizeText(status);
    const turNorm = normalizeText(r.dosyaTurKodAciklama || "");
    const kapanis = r.dosyaKapanisTarihi || r.kapanisTarihi || null;
    const karar   = r.kararTarihi || null;
    const acilis  = r.dosyaAcilisTarihi || null;
    const talik   = r.talikDurusmaTarihi || null;
    const dosya   = r.dosyaNo || r.esasNo || "";
    const kararNo = r.kararNo || "";

    const kararMs = karar ? new Date(karar).getTime() : null;
    const talikMs = talik ? new Date(talik).getTime() : null;
    const talikPastOrNull = talikMs == null || talikMs < todayMs;
    const talikFuture = talikMs != null && talikMs > todayMs;

    const add = msg => list.push({
      idx: list.length + 1,
      dosya,
      kararNo,
      acilis: fmtDate(acilis),
      karar: fmtDate(karar),
      kapanis: fmtDate(kapanis),
      aciklama: msg
    });

    if (statusNorm.includes("yargitayda") && kapanis) {
      add("Dosya Yargıtay'da gözüküyor ama kapanmış olabilir?");
    }
    if (statusNorm.includes("gerekceli karar yazildi") && karar) {
      const diff = now - new Date(karar).getTime();
      if (diff > 90 * 86400000) add("Bu dosya 3 aydan eski, işlemsiz olabilir mi?");
    }
    if (statusNorm.includes("birlestirilmek uzere kapat") && !kapanis) {
      add("Dosyada kapanma tarihi yok");
    }
    if (statusNorm.includes("istinaftan dondu") || statusNorm.includes("yargitaydan dondu")) {
      add("Dosya kapalı hale gelmemiştir");
    }
    if (statusNorm.includes("nihayi karar kaydedildi")) {
      add("Gerekçeli Karar Yazıldı mı?");
    }

    const statusHasAcilis = statusNorm.includes("acildi") || statusNorm.includes("acilis");
    const statusHasDurusmaYapildi = statusNorm.includes("durusma yapildi");
    const isBasitYargilama = turNorm.includes("basit yargilama");


    if (statusHasAcilis && !isBasitYargilama && talikPastOrNull) {
      add("Dosya duruşma kaçağı olabilir mi?");
    }
    if (statusHasDurusmaYapildi && talikPastOrNull) {
      add("Dosya duruşma kaçağı olabilir mi?");
    }
    /*
    if (!statusHasAcilis && talikFuture && (kararMs == null || (talikMs != null && kararMs < talikMs))) {
      add("Dosya açık gözükmüyor ama duruşma tarihi var");
    }
      */
  }
  return list;
}

// -------------------- Paint tables -------------------- //
function paintYearTableClickable(tableId, map, fieldKey) {
  const entries = Object.entries(map)
    .sort((a, b) => a[0] - b[0])
    .map(([y, c]) => ({ year: y, count: c, fieldKey }));

  const table = ensureDataTable(tableId, {
    columns: [
      { title: "Yıl",   data: "year",  className: "mono" },
      { title: "Adet",  data: "count", className: "mono text-end" }
    ],
    paging: false,
    info: false,
    searching: false,
    lengthChange: false,
    layout: { topEnd: null, bottomStart: null, bottomEnd: null },
    order: [[0, "asc"]]
  });

  table.clear();
  table.rows.add(entries);
  table.order([[0, "asc"]]);
  table.draw();

  if (!table._yearClickBound) {
    table.on("click", "tbody tr", function () {
      const data = table.row(this).data();
      if (!data) return;
      openYearDetail(data.fieldKey, Number(data.year));
    });
    table._yearClickBound = true;
  }
}

function paintAggregateTable(tableId, map, type) {
  const entries = Object.entries(map)
    .sort((a, b) => b[1] - a[1])
    .map(([k, v]) => ({
      label: escapeHtml(String(k ?? "")),
      rawId: String(k ?? ""),
      count: v,
      type
    }));

  const firstTitle = type === "statu" ? "Statü" : "Sicil";

  const table = ensureDataTable(tableId, {
    columns: [
      { title: firstTitle, data: "label", className: "mono" },
      { title: "Adet",     data: "count", className: "mono text-end" }
    ],
    order: [[1, "desc"]]
  });

  table.clear();
  table.rows.add(entries);
  table.order([[1, "desc"]]);
  table.draw();

  table.rows().every(function () {
    const n = this.node();
    const d = this.data();
    if (!n || !d) return;
    n.dataset.type = d.type;
    n.dataset.id = d.rawId;
    n.classList.add("row-click");
  });

  if (!table._rowClickBound && type) {
    table.on("click", "tbody tr", function () {
      const rowData = table.row(this).data();
      if (!rowData) return;
      openDetailFromData(rowData.type, rowData.rawId);
    });
    table._rowClickBound = true;
  }
}

function rebuildStats() {
  const rows = Array.isArray(filteredRows) ? filteredRows : [];
  const ag   = buildAggregatesFrom(rows);
  paintAggregateTable("tblHakim", ag.hakim, "hakim");
  paintAggregateTable("tblSavci", ag.savci, "savci");
  paintAggregateTable("tblKatip", ag.katip, "katip");
  paintAggregateTable("tblStatu", ag.statu, "statu");

  const acMap  = buildYearMap(rows, "dosyaAcilisTarihi");
  const krMap  = buildYearMap(rows, "kararTarihi");
  const kapMap = buildYearMap(rows, "dosyaKapanisTarihi");
  paintYearTableClickable("tblYearAcilis", acMap, "dosyaAcilisTarihi");
  paintYearTableClickable("tblYearKarar",  krMap, "kararTarihi");
  paintYearTableClickable("tblYearKapanis", kapMap, "dosyaKapanisTarihi");
}

// -------------------- JSON Load / Backup -------------------- //
function trimLog(list) {
  if (!Array.isArray(list)) return [];
  if (list.length <= LOG_CAP) return list;
  return list.slice(list.length - LOG_CAP);
}

async function saveBackupIfNotExists() {
  const bk = await chrome.storage.local.get(BACKUP_KEY);
  if (bk && bk[BACKUP_KEY]) return false;
  const st = await chrome.storage.local.get([KEY, SKEY, RKEY]);
  const payload = {
    [BACKUP_KEY]: st,
    [`${BACKUP_KEY}_created`]: new Date().toISOString()
  };
  await chrome.storage.local.set(payload);
  updateBackupUI(true);
  return true;
}

async function restoreBackup() {
  const bk = await chrome.storage.local.get([BACKUP_KEY, `${BACKUP_KEY}_created`]);
  const d = bk[BACKUP_KEY];
  if (!d) {
    showToast("Yedek bulunamadı", "error");
    return;
  }

  await chrome.storage.local.set({
    [KEY]: d[KEY] || [],
    [SKEY]: d[SKEY] || { hakim: {}, savci: {}, katip: {}, statu: {} },
    [RKEY]: d[RKEY] || []
  });

  await renderList();
  await refreshUnits();
  await applyFilters();
  updateBackupUI(true);
  showToast("Yedek geri yüklendi");
}

async function loadRowsFromText(txt) {
  try {
    const parsed = JSON.parse(txt);
    let rows = null;
    if (Array.isArray(parsed)) rows = parsed;
    else if (Array.isArray(parsed.data)) rows = parsed.data;
    else if (Array.isArray(parsed.rows)) rows = parsed.rows;
    else if (Array.isArray(parsed.RKEY)) rows = parsed.RKEY;
    else {
      for (const k in parsed) {
        if (Array.isArray(parsed[k])) { rows = parsed[k]; break; }
      }
    }
    if (!Array.isArray(rows)) throw new Error("Yüklenen JSON beklenen satır listesine sahip değil.");

    await saveBackupIfNotExists();

    const ag = buildAggregatesFrom(rows);
    const st = await chrome.storage.local.get([KEY]);
    const list = st[KEY] || [];
    const newLog = list.concat([{ ts: new Date().toISOString(), picked: { count: rows.length }, src: "file", inserted: rows.length, updated: 0, total: rows.length }]);
    await chrome.storage.local.set({ [KEY]: trimLog(newLog), [SKEY]: ag, [RKEY]: rows });

    await renderList();
    await refreshUnits();
    await applyFilters();
    showToast("JSON yüklendi ve istatistikler güncellendi");
  } catch (e) {
    console.warn("JSON yükleme hatası:", e);
    showToast("JSON yüklenirken hata: " + (e.message || String(e)), "error");
  }
}

function updateBackupUI(exists) {
  const el = document.getElementById("backupStatus");
  const btn = document.getElementById("btnRestoreBackup");
  if (!el || !btn) return;
  if (exists) {
    chrome.storage.local.get(`${BACKUP_KEY}_created`, st => {
      const ts = st[`${BACKUP_KEY}_created`];
      try {
        const d = new Date(ts);
        el.textContent = `Yedek: ${d.toLocaleString()}`;
      } catch {
        el.textContent = "Yedek: mevcut";
      }
      btn.disabled = false;
    });
  } else {
    el.textContent = "Yedek: yok";
    btn.disabled = true;
  }
}

async function ensureInitialBackup() {
  const bk = await chrome.storage.local.get(BACKUP_KEY);
  if (bk && bk[BACKUP_KEY]) { updateBackupUI(true); return; }
  const st = await chrome.storage.local.get([KEY, SKEY, RKEY]);
  const rows = st[RKEY] || [];
  if (rows.length) {
    await chrome.storage.local.set({ [BACKUP_KEY]: st });
    await chrome.storage.local.set({ [`${BACKUP_KEY}_created`]: new Date().toISOString() });
    updateBackupUI(true);
  } else {
    updateBackupUI(false);
  }
}

// -------------------- Units -------------------- //
async function refreshUnits() {
  const st   = await chrome.storage.local.get(RKEY);
  const rows = st[RKEY] || [];

  const sel = document.getElementById("birimSelect");
  if (!sel) return;

  const set = new Set();
  for (const r of rows) if (r.birimAdi) set.add(String(r.birimAdi));
  const units = Array.from(set).sort((a, b) => a.localeCompare(b, "tr-TR"));

  const prev = sel.value;
  sel.innerHTML = `<option value="">Tümü</option>` +
    units.map(u => `<option value="${escapeHtml(u)}">${escapeHtml(u)}</option>`).join("");

  if (prev && set.has(prev)) {
    sel.value = prev;
    currentUnit = prev;
  } else {
    currentUnit = sel.value || "";
  }

  updateBirimInfo(rows);
}

function updateBirimInfo(allRows) {
  const infoEl = document.getElementById("birimInfo");
  if (!infoEl) return;

  const total = allRows.length;
  const unitSet = new Set();
  for (const r of allRows) if (r.birimAdi) unitSet.add(String(r.birimAdi));
  const unitCount = unitSet.size;

  let txt = "";
  if (!total) {
    txt = "Henüz hafızada kayıt yok.";
  } else if (!currentUnit) {
    const fCount = Array.isArray(filteredRows) ? filteredRows.length : 0;
    txt = `Toplam ${unitCount} birimden ${total} kayıt yüklü. Filtre sonrası kayıt sayısı: ${fCount}.`;
  } else {
    const unitName = currentUnit;
    const unitTotal = allRows.filter(r => String(r.birimAdi || "") === unitName).length;
    const fCount = Array.isArray(filteredRows)
      ? filteredRows.filter(r => String(r.birimAdi || "") === unitName).length
      : 0;
    txt = `Seçili birim: ${unitName}. Bu birime ait toplam ${unitTotal} kayıt var. Filtre sonrası kayıt sayısı: ${fCount}.`;
  }

  infoEl.textContent = txt;
}

// -------------------- Filtering -------------------- //
async function applyFilters() {
  const st = await chrome.storage.local.get(RKEY);
  let rows = st[RKEY] || [];

  if (currentUnit) {
    rows = rows.filter(r => String(r.birimAdi || "") === currentUnit);
  }

  const acFromVal = document.getElementById("acilisFrom")?.value || "";
  const acToVal   = document.getElementById("acilisTo")?.value   || "";
  const krFromVal = document.getElementById("kararFrom")?.value  || "";
  const krToVal   = document.getElementById("kararTo")?.value    || "";

  const fAcilisFrom = acFromVal ? new Date(acFromVal).getTime() : null;
  const fAcilisTo   = acToVal   ? new Date(acToVal).getTime()   + 86400000 - 1 : null;
  const fKararFrom  = krFromVal ? new Date(krFromVal).getTime() : null;
  const fKararTo    = krToVal   ? new Date(krToVal).getTime()   + 86400000 - 1 : null;

  filteredRows = rows.filter(r =>
    between(r.dosyaAcilisTarihi, fAcilisFrom, fAcilisTo) &&
    between(r.kararTarihi,       fKararFrom,  fKararTo)
  );

  rebuildStats();
  updateBirimInfo(st[RKEY] || []);
}

// -------------------- Detail -------------------- //
async function openDetailFromData(type, id) {
  if (!type || id == null) return;
  if (isDetailOpening) return;
  isDetailOpening = true;

  try {
    let rows = Array.isArray(filteredRows) ? filteredRows : null;

    if (!rows) {
      const st  = await chrome.storage.local.get(RKEY);
      rows = st[RKEY] || [];
      if (currentUnit) rows = rows.filter(r => String(r.birimAdi || "") === currentUnit);
    }

    let filt = [];
    if (type === "hakim") {
      filt = rows.filter(r =>
        [r.hukumHakimBaskanPId, r.hukumUye1PId, r.hukumUye2PId].some(x => String(x) === id)
      );
    } else if (type === "savci") {
      filt = rows.filter(r => String(r.hukumSavciPId) === id);
    } else if (type === "katip") {
      filt = rows.filter(r => String(r.hukumKatipPId) === id);
    } else if (type === "statu") {
      filt = rows.filter(r => String(getStatusText(r)) === id);
    }

    const detailKeys = filt.map(r => r.dosyaNo || r.esasNo || null);
    const meta = {
      type,
      id,
      unit: currentUnit || "",
      filters: {
        acilisFrom: document.getElementById("acilisFrom")?.value || "",
        acilisTo:   document.getElementById("acilisTo")?.value   || "",
        kararFrom:  document.getElementById("kararFrom")?.value  || "",
        kararTo:    document.getElementById("kararTo")?.value    || ""
      }
    };

    await chrome.storage.local.set({ detailKeys, detailMeta: meta });

    chrome.windows.create(
      { url: chrome.runtime.getURL("details.html"), type: "popup", width: 900, height: 720 },
      () => { isDetailOpening = false; }
    );
  } catch (e) {
    console.warn("[stats] row click error:", e);
    isDetailOpening = false;
  }
}

async function openYearDetail(fieldKey, year) {
  if (!fieldKey || !Number.isFinite(year)) return;
  if (isDetailOpening) return;
  isDetailOpening = true;

  try {
    let rows = Array.isArray(filteredRows) ? filteredRows : null;
    if (!rows) {
      const st = await chrome.storage.local.get(RKEY);
      rows = st[RKEY] || [];
    }

    const filtered = rows.filter(r => {
      let v = r[fieldKey];
      if (fieldKey === "dosyaKapanisTarihi") v = r.dosyaKapanisTarihi || r.kapanisTarihi;
      if (!v) return false;
      const d = new Date(v);
      return d.getFullYear() === year;
    });

    const detailKeys = filtered.map(r => r.dosyaNo || r.esasNo || null);
    const meta = {
      type: "year",
      id: String(year),
      yearField: fieldKey,
      filters: {
        acilisFrom: document.getElementById("acilisFrom")?.value || "",
        acilisTo:   document.getElementById("acilisTo")?.value   || "",
        kararFrom:  document.getElementById("kararFrom")?.value  || "",
        kararTo:    document.getElementById("kararTo")?.value    || ""
      }
    };

    await chrome.storage.local.set({ detailKeys, detailMeta: meta });

    chrome.windows.create(
      { url: chrome.runtime.getURL("details.html"), type: "popup", width: 900, height: 720 },
      () => { isDetailOpening = false; }
    );
  } catch (e) {
    console.warn("[stats] year click error:", e);
    isDetailOpening = false;
  }
}

// -------------------- Export -------------------- //
function downloadBlob(filename, mime, content) {
  const blob = new Blob([content], { type: mime });
  const url  = URL.createObjectURL(blob);
  chrome.downloads.download({ url, filename, saveAs: true }, () => setTimeout(() => URL.revokeObjectURL(url), 5000));
}

async function handleExport(kind) {
  const st = await chrome.storage.local.get(RKEY);
  let rows = st[RKEY] || [];

  if (currentUnit) rows = rows.filter(r => String(r.birimAdi || "") === currentUnit);
  if (Array.isArray(filteredRows)) rows = filteredRows;

  if (!rows.length) { showToast("Dışa aktarılacak kayıt yok", "error"); return; }

  if (kind === "json") {
    const json = JSON.stringify(rows, null, 2);
    downloadBlob("istatistik.json", "application/json", json);
    return;
  }

  const headers = [
    { key: "birimAdi",              title: "Birim" },
    { key: "dosyaNo",               title: "Dosya / Esas" },
    { key: "kararNo",               title: "Karar No" },
    { key: "dosyaAcilisTarihi",     title: "Açılış" },
    { key: "kararTarihi",           title: "Karar" },
    { key: "dosyaKapanisTarihi",    title: "Kapanış" },
    { key: "hukumHakimBaskanPId",   title: "Hakim Başkan" },
    { key: "hukumUye1PId",          title: "Üye 1" },
    { key: "hukumUye2PId",          title: "Üye 2" },
    { key: "hukumSavciPId",         title: "Savcı" },
    { key: "hukumKatipPId",         title: "Kâtip" }
  ];

  const prepared = rows.map(r => ({
    birimAdi: r.birimAdi || "",
    dosyaNo: r.dosyaNo || r.esasNo || "",
    kararNo: r.kararNo || "",
    dosyaAcilisTarihi: fmtDate(r.dosyaAcilisTarihi),
    kararTarihi: fmtDate(r.kararTarihi),
    dosyaKapanisTarihi: fmtDate(r.dosyaKapanisTarihi || r.kapanisTarihi),
    hukumHakimBaskanPId: r.hukumHakimBaskanPId ?? "",
    hukumUye1PId: r.hukumUye1PId ?? "",
    hukumUye2PId: r.hukumUye2PId ?? "",
    hukumSavciPId: r.hukumSavciPId ?? "",
    hukumKatipPId: r.hukumKatipPId ?? ""
  }));

  exportWithButtons(headers, prepared, "istatistik.xlsx", "Istatistik");
}

// -------------------- Reset & Dedup -------------------- //
async function resetAll() {
  if (!confirm("Tüm istatistik ve ham veriyi sıfırlamak istiyor musunuz?")) return;

  await chrome.storage.local.set({
    [KEY]:  [],
    [SKEY]: { hakim: {}, savci: {}, katip: {}, statu: {} },
    [RKEY]: []
  });

  filteredRows = null;
  currentUnit = "";

  await renderList();
  await refreshUnits();
  rebuildStats();
}

async function dedupByEsas() {
  const st   = await chrome.storage.local.get([RKEY]);
  const rows = st[RKEY] || [];

  if (!rows.length) { showToast("Temizlenecek kayıt yok", "error"); return; }

  const seen = new Set();
  const out  = [];

  for (const r of rows) {
    const key = r.dosyaNo || r.esasNo || null;
    if (!key) { out.push(r); continue; }
    if (seen.has(key)) continue;
    seen.add(key);
    out.push(r);
  }

  const ag = buildAggregatesFrom(out);
  await chrome.storage.local.set({ [RKEY]: out, [SKEY]: ag });

  await refreshUnits();
  await applyFilters();

  showToast(`Mükerrer temizleme tamamlandı. Önce: ${rows.length}, Sonra: ${out.length}`);
}

// -------------------- Terfi Window -------------------- //
function openTerfiWindow() {
  chrome.windows.create({
    url:  chrome.runtime.getURL("terfi.html"),
    type: "popup",
    width: 640,
    height: 600
  });
}

// -------------------- Events -------------------- //
document.getElementById("btnReset")?.addEventListener("click", resetAll);
document.getElementById("btnDedup")?.addEventListener("click", dedupByEsas);

document.getElementById("exportCsv")?.addEventListener("click", () => handleExport("excel"));
document.getElementById("exportJson")?.addEventListener("click", () => handleExport("json"));

document.getElementById("refresh")?.addEventListener("click", () => {
  renderList();
  refreshUnits().then(applyFilters);
});

document.getElementById("apply")?.addEventListener("click", applyFilters);

document.getElementById("clearFilters")?.addEventListener("click", () => {
  ["acilisFrom", "acilisTo", "kararFrom", "kararTo"].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.value = "";
  });
  applyFilters();
});

// JSON yükle ve yedekten geri yükleme eventleri
const btnLoadJson = document.getElementById("btnLoadJson");
const loadJsonFileEl = document.getElementById("loadJsonFile");
const btnRestoreBackup = document.getElementById("btnRestoreBackup");

if (btnLoadJson && loadJsonFileEl) {
  btnLoadJson.addEventListener("click", () => loadJsonFileEl.click());
  loadJsonFileEl.addEventListener("change", async e => {
    const f = e.target.files?.[0];
    if (!f) return;
    const txt = await f.text();
    await loadRowsFromText(txt);
    e.target.value = "";
  });
}

if (btnRestoreBackup) {
  btnRestoreBackup.addEventListener("click", async () => {
    if (!confirm("Yedekten geri yüklemek istediğinize emin misiniz? Önceki veriler değişecek.")) return;
    await restoreBackup();
  });
}

// Birim seçimi
const birimSelectEl = document.getElementById("birimSelect");
if (birimSelectEl) {
  birimSelectEl.addEventListener("change", () => {
    currentUnit = birimSelectEl.value || "";
    applyFilters();
  });
}

// Tema toggle
const themeBtn = document.getElementById("themeToggle");
if (themeBtn) {
  themeBtn.addEventListener("click", () => {
    const next = document.documentElement.getAttribute("data-theme") === "light" ? "dark" : "light";
    applyTheme(next);
  });
}

// Uyarılar modal
const btnWarnings = document.getElementById("btnWarnings");
const modalWarnings = document.getElementById("warningsModal");
const btnCloseWarnings = document.getElementById("closeWarnings");
const btnExportWarnings = document.getElementById("btnExportWarnings");

async function showWarnings() {
  await applyFilters();
  const rows = Array.isArray(filteredRows) ? filteredRows : [];
  const warnings = buildWarningsList(rows);
  const table = ensureDataTable("tblWarnings", {
    columns: [
      { title: "#", data: "idx", className: "mono" },
      { title: "Esas No", data: "dosya", className: "mono" },
      { title: "Karar No", data: "kararNo", className: "mono" },
      { title: "Açılış", data: "acilis", className: "mono" },
      { title: "Karar", data: "karar", className: "mono" },
      { title: "Kapanış", data: "kapanis", className: "mono" },
      { title: "Açıklama", data: "aciklama" }
    ],
    paging: true,
    pageLength: 10,
    searching: true,
    info: true,
    lengthChange: true,
    order: [[0, "asc"]]
  });
  table.clear();
  table.rows.add(warnings);
  table.draw();
  if (modalWarnings) modalWarnings.style.display = "flex";
}

if (btnWarnings) btnWarnings.addEventListener("click", showWarnings);
if (btnCloseWarnings) btnCloseWarnings.addEventListener("click", () => {
  if (modalWarnings) modalWarnings.style.display = "none";
});
if (modalWarnings) {
  modalWarnings.addEventListener("click", e => {
    if (e.target === modalWarnings) modalWarnings.style.display = "none";
  });
}
if (btnExportWarnings) {
  btnExportWarnings.addEventListener("click", async () => {
    const rows = Array.isArray(filteredRows) ? filteredRows : [];
    const warnings = buildWarningsList(rows);
    if (!warnings.length) {
      showToast("İndirilecek uyarı yok", "error");
      return;
    }
    const headers = [
      { key: "idx", title: "#" },
      { key: "dosya", title: "Esas No" },
      { key: "kararNo", title: "Karar No" },
      { key: "acilis", title: "Açılış" },
      { key: "karar", title: "Karar" },
      { key: "kapanis", title: "Kapanış" },
      { key: "aciklama", title: "Açıklama" }
    ];
    exportWithButtons(headers, warnings, "uyarilar.xlsx", "Uyarilar");
  });
}

// Terfi butonunu ekle (HTML'de varsa dokunma)
(function attachTerfiButton() {
  if (document.getElementById("btnTerfi")) {
    document.getElementById("btnTerfi").addEventListener("click", openTerfiWindow);
    return;
  }
  const dedupBtn = document.getElementById("btnDedup");
  if (!dedupBtn || !dedupBtn.parentElement) return;
  const btn = document.createElement("button");
  btn.id = "btnTerfi";
  btn.textContent = "Terfi Tablosu";
  btn.className = "ghost";
  dedupBtn.parentElement.insertBefore(btn, dedupBtn.nextSibling);
  btn.addEventListener("click", openTerfiWindow);
})();

// İlk yükleme
(async function init() {
  applyTheme(localStorage.getItem(THEME_KEY) || document.documentElement.getAttribute("data-theme") || "dark");
  await renderList();
  await refreshUnits();
  await applyFilters();
  await ensureInitialBackup();
})();
