const KEY = "json_stats";
const THEME_KEY = "uyap_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" ? "☀️" : "🌙";
}

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

async function render() {
  try {
    const obj  = await chrome.storage.local.get(KEY);
    const list = obj[KEY] || [];
    const el   = document.getElementById("list");
    if (!list.length) {
      el.textContent = "Henüz veri yok.";
      return;
    }
    el.innerHTML = list
      .slice()
      .reverse()
      .slice(0, 300)
      .map(itemHtml)
      .join("");
  } catch (e) {
    console.warn(e);
  }
}

document.getElementById("refresh")?.addEventListener("click", render);
document.getElementById("clear")?.addEventListener("click", async () => {
  await chrome.storage.local.set({ [KEY]: [] });
  render();
});
document.getElementById("openStats")?.addEventListener("click", () =>
  chrome.windows.create({ url: chrome.runtime.getURL("stats.html"), type: "popup", width: 980, height: 760 })
);
document.getElementById("themeToggle")?.addEventListener("click", () => {
  const cur = document.documentElement.getAttribute("data-theme") === "light" ? "dark" : "light";
  applyTheme(cur);
});

document.addEventListener("DOMContentLoaded", () => {
  applyTheme(localStorage.getItem(THEME_KEY) || "dark");
  render();
});
