// AdBlockMaxxer — options / dashboard page.

const TOGGLES = {
  youtubeSkip: "youtubeSkip",
  sponsorblock: "sponsorblock",
  spotifyMute: "spotifyMute",
  twitchPoints: "twitchPoints",
  twitchExtras: "twitchExtras",
  twitchGame: "twitchGame",
  cookieDismiss: "cookieDismiss",
  cosmetic: "cosmetic",
  // easylist handled separately (also flips the DNR ruleset)
};

const SB_CATS = [
  ["sponsor", "Sponsor"],
  ["selfpromo", "Self-promotion"],
  ["interaction", "Interaction reminder (like/sub)"],
  ["intro", "Intro / intermission"],
  ["outro", "Outro / endcards"],
  ["music_offtopic", "Non-music section"],
  ["preview", "Preview / recap"],
  ["filler", "Filler tangent"],
];
const SB_DEFAULT = ["sponsor", "selfpromo", "interaction", "intro", "outro", "music_offtopic"];

const $ = (id) => document.getElementById(id);
const isFirefox = /firefox/i.test(navigator.userAgent);

// ---- feature toggles --------------------------------------------------------
function wireToggles(data) {
  for (const [id, key] of Object.entries(TOGGLES)) {
    const el = $(id);
    if (!el) continue;
    el.checked = data[key] !== false;
    el.onchange = () => chrome.storage.local.set({ [key]: el.checked });
  }
  const ez = $("easylist");
  ez.checked = data.easylistEnabled !== false;
  ez.onchange = () => {
    chrome.storage.local.set({ easylistEnabled: ez.checked });
    chrome.runtime.sendMessage({ type: "setRuleset", id: "easylist", enabled: ez.checked });
  };
}

// ---- performance mode -------------------------------------------------------
function wirePerf(data) {
  const on = $("perfMode");
  on.checked = data.perfMode === true; // defaults OFF
  on.onchange = () => chrome.storage.local.set({ perfMode: on.checked });
  const mins = $("perfSuspendMins");
  mins.value = String(data.perfSuspendMins || 10);
  mins.onchange = () => chrome.storage.local.set({ perfSuspendMins: parseInt(mins.value, 10) || 10 });
  // Twitch fullscreen chat overlay (default OFF)
  const co = $("twitchChatOverlay");
  if (co) {
    co.checked = data.twitchChatOverlay === true;
    co.onchange = () => chrome.storage.local.set({ twitchChatOverlay: co.checked });
  }
  const fq = $("twitchForceQuality");
  if (fq) {
    fq.checked = data.twitchForceQuality === true;
    fq.onchange = () => chrome.storage.local.set({ twitchForceQuality: fq.checked });
  }
}

// ---- sponsorblock categories ------------------------------------------------
function wireSbCats(data) {
  const chosen = new Set(Array.isArray(data.sbCategories) ? data.sbCategories : SB_DEFAULT);
  const box = $("sbCats");
  box.innerHTML = "";
  for (const [key, label] of SB_CATS) {
    const id = "sb-" + key;
    const wrap = document.createElement("label");
    wrap.innerHTML = `<input type="checkbox" id="${id}" ${chosen.has(key) ? "checked" : ""}/> <span>${label}</span>`;
    box.appendChild(wrap);
    wrap.querySelector("input").onchange = (e) => {
      if (e.target.checked) chosen.add(key); else chosen.delete(key);
      chrome.storage.local.set({ sbCategories: [...chosen] });
    };
  }
}

// ---- custom filter lists ----------------------------------------------------
function renderLists(data) {
  const lists = data.customLists || [];
  const status = data.customListStatus || {};
  const host = $("lists");
  host.innerHTML = "";
  if (!lists.length) {
    host.innerHTML = '<p class="muted">No custom lists yet.</p>';
  }
  lists.forEach((l, i) => {
    const st = status[l.url];
    let stHtml = "";
    if (st && st.error) stHtml = `<div class="st err">⚠ ${st.error}</div>`;
    else if (st) stHtml = `<div class="st ok">${st.rules || 0} rules${st.cosmetic ? " · " + st.cosmetic + " cosmetic" : ""}</div>`;
    const item = document.createElement("div");
    item.className = "list-item";
    item.innerHTML = `
      <input type="checkbox" ${l.enabled !== false ? "checked" : ""} title="Enable/disable" />
      <div class="meta">
        <div class="nm">${escapeHtml(l.name || l.url)}</div>
        <div class="url">${escapeHtml(l.url)}</div>
        ${stHtml}
      </div>
      <div class="rm" title="Remove">✕</div>`;
    item.querySelector("input").onchange = (e) => {
      lists[i].enabled = e.target.checked;
      chrome.storage.local.set({ customLists: lists }, () => rebuild());
    };
    item.querySelector(".rm").onclick = () => {
      lists.splice(i, 1);
      chrome.storage.local.set({ customLists: lists }, () => rebuild());
    };
    host.appendChild(item);
  });
  const count = data.customListCount || 0;
  $("listSummary").textContent = count ? count.toLocaleString() + " live network rules" : "";
}

function addList() {
  const url = $("listUrl").value.trim();
  if (!/^https?:\/\//i.test(url)) { flash("backupMsg", "Enter a valid http(s) list URL."); return; }
  const name = $("listName").value.trim();
  chrome.storage.local.get("customLists", (r) => {
    const lists = r.customLists || [];
    if (lists.some((l) => l.url === url)) { flash("listSummary", "Already added."); return; }
    lists.push({ name, url, enabled: true });
    chrome.storage.local.set({ customLists: lists }, () => {
      $("listUrl").value = ""; $("listName").value = "";
      rebuild();
    });
  });
}

function rebuild() {
  $("listSummary").textContent = "Rebuilding…";
  chrome.runtime.sendMessage({ type: "rebuildDynamic" }, () => load());
}

// ---- stats ------------------------------------------------------------------
const CAT_LABEL = {
  youtube: "YouTube ads", spotify: "Spotify ads", sponsorblock: "SponsorBlock skips",
  twitch: "Twitch", network: "Network",
};
function renderStats(data) {
  $("statTotal").textContent = (data.adsSkipped || 0).toLocaleString();
  const stats = data.stats || {};
  const cats = stats.byCategory || {};
  const sites = stats.bySite || {};

  const catUl = $("byCat");
  const catEntries = Object.entries(cats).sort((a, b) => b[1] - a[1]);
  catUl.innerHTML = catEntries.length
    ? catEntries.map(([k, v]) => `<li><span>${CAT_LABEL[k] || k}</span><b>${v.toLocaleString()}</b></li>`).join("")
    : '<li class="muted">No data yet.</li>';

  const siteUl = $("bySite");
  const siteEntries = Object.entries(sites).sort((a, b) => b[1] - a[1]).slice(0, 8);
  siteUl.innerHTML = siteEntries.length
    ? siteEntries.map(([k, v]) => `<li><span>${escapeHtml(k)}</span><b>${v.toLocaleString()}</b></li>`).join("")
    : '<li class="muted">No data yet.</li>';
}

// ---- backup -----------------------------------------------------------------
function exportSettings() {
  chrome.storage.local.get(null, (all) => {
    const blob = new Blob([JSON.stringify(all, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "adblockmaxxer-settings.json";
    a.click();
    setTimeout(() => URL.revokeObjectURL(url), 2000);
    flash("backupMsg", "Exported.");
  });
}
function importSettings(file) {
  const reader = new FileReader();
  reader.onload = () => {
    try {
      const obj = JSON.parse(reader.result);
      if (!obj || typeof obj !== "object") throw new Error("not an object");
      chrome.storage.local.set(obj, () => {
        // re-apply DNR state that lives outside plain storage
        chrome.runtime.sendMessage({ type: "setRuleset", id: "easylist", enabled: obj.easylistEnabled !== false });
        chrome.runtime.sendMessage({ type: "rebuildDynamic" }, () => {
          flash("backupMsg", "Imported. Reloading…");
          setTimeout(() => location.reload(), 700);
        });
      });
    } catch (e) {
      flash("backupMsg", "Import failed: " + e.message);
    }
  };
  reader.readAsText(file);
}

// ---- helpers ----------------------------------------------------------------
function escapeHtml(s) {
  return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
let flashTimer = null;
function flash(id, msg) {
  const el = $(id); if (!el) return;
  el.textContent = msg;
  clearTimeout(flashTimer);
  flashTimer = setTimeout(() => { if (el.id === "backupMsg") el.textContent = ""; }, 3500);
}

// ---- load -------------------------------------------------------------------
function load() {
  chrome.storage.local.get(null, (data) => {
    wireToggles(data);
    wirePerf(data);
    wireSbCats(data);
    renderLists(data);
    renderStats(data);
  });
}

document.addEventListener("DOMContentLoaded", () => {
  $("shortcutsUrl").textContent = isFirefox ? "about:addons → ⚙ → Manage Extension Shortcuts" : "chrome://extensions/shortcuts";
  $("addList").onclick = addList;
  $("listUrl").addEventListener("keydown", (e) => { if (e.key === "Enter") addList(); });
  $("refreshLists").onclick = rebuild;
  $("resetStats").onclick = () => chrome.storage.local.set({ adsSkipped: 0, stats: { byCategory: {}, bySite: {} } }, load);
  $("exportBtn").onclick = exportSettings;
  $("importBtn").onclick = () => $("importFile").click();
  $("importFile").addEventListener("change", (e) => { if (e.target.files[0]) importSettings(e.target.files[0]); });
  load();
});

chrome.storage.onChanged.addListener((c) => {
  // keep stats + list status live without a full re-wire of inputs
  if (c.adsSkipped || c.stats) chrome.storage.local.get(null, renderStats);
  if (c.customListStatus || c.customListCount) chrome.storage.local.get(null, renderLists);
});
