// Popup = the freemium control surface.
//  - Descriptive (free): Authority, Topicality, DYNAMICS-WEB character (computed on-device).
//  - Diagnosis (free): "does this page fit reader X?" -> coarse verdict + direction only.
//  - Cure (premium): specific levers + a rewrite of the page text for that reader.
// The mapping M lives server side; the popup only ever sees verdicts, directions, and
// (for premium) the finished rewrite — never the audience target profiles or lever maths.
const AXES = ["rigour", "depth", "originality", "candour", "affect", "commercial_drive", "stance", "register"];
const $ = id => document.getElementById(id);
let TAB = null, TIER = "free", PAGE_TEXT = "";

function bars(web, into) {
  into.innerHTML = "";
  for (const ax of AXES) {
    const v = web[ax] ?? 0;
    const row = document.createElement("div"); row.className = "row";
    row.innerHTML = `<div class="ax">${ax.replace("_", " ")}</div>` +
      `<div class="bar"><div class="fill" style="width:${Math.round(v * 100)}%"></div></div>` +
      `<div class="val">${v.toFixed(2)}</div>`;
    into.appendChild(row);
  }
}

function renderFit(res) {
  const v = $("verdict"), badge = $("vbadge"), rate = $("vrate"), dir = $("vdir"), btn = $("curebtn");
  $("cureout").innerHTML = ""; $("curenote").textContent = "";
  if (!res || res.status === 429) { v.style.display = "none"; dir.textContent = res && res.status === 429 ? "Easy there — try again shortly." : ""; btn.style.display = "none"; return; }
  const b = res.body || {};
  if (res.status === 402) {  // premium audience on a free key
    v.style.display = "flex"; badge.className = "badge unk"; badge.textContent = "Premium"; rate.textContent = "audience";
    dir.innerHTML = "This reader is part of the premium set."; btn.style.display = "none"; return;
  }
  if (b.verdict == null) { v.style.display = "flex"; badge.className = "badge unk"; badge.textContent = "—"; rate.textContent = b.reason || "not scored yet"; dir.textContent = ""; btn.style.display = "none"; return; }
  v.style.display = "flex";
  badge.className = "badge " + (b.verdict === "pass" ? "pass" : "fail");
  badge.textContent = b.verdict === "pass" ? "Good fit" : "Poor fit";
  rate.textContent = b.rating ? `(${b.rating})` : "";
  dir.innerHTML = (b.direction && b.direction.length)
    ? "To fit better: " + b.direction.map(d => `<b>${d}</b>`).join(", ")
    : "Well aligned on the dimensions this reader rewards.";
  btn.style.display = "block";
  btn.textContent = TIER === "premium" ? "Fix this page for the reader" : "Fix this page (Premium)";
}

function renderCure(res, audience) {
  const out = $("cureout"), note = $("curenote");
  out.innerHTML = ""; note.textContent = "";
  if (res && res.status === 402) {  // free user — show the locked value + upsell
    out.innerHTML = `<div class="upsell"><b>Premium unlocks the cure.</b> You can see the page misses for this reader and the direction to move. Premium gives the exact changes and a ready rewrite.</div>` +
      `<div class="rewrite blur">Your rewritten passage, tuned for this reader, appears here with Premium. It keeps every fact, shifts the character, and is ready to paste.</div>`;
    return;
  }
  const b = (res && res.body) || {};
  if (b.suggestions && b.suggestions.length) {
    out.innerHTML = `<ul class="cure">${b.suggestions.map(s => `<li>${s}</li>`).join("")}</ul>`;
  }
  if (b.rewrite) {
    const div = document.createElement("div"); div.className = "rewrite"; div.textContent = b.rewrite;
    out.appendChild(div);
    note.textContent = "Rewrite keeps your facts; signed + watermarked to your account.";
  } else if (b.note) {
    note.textContent = b.note;
  } else if (!b.suggestions) {
    out.innerHTML = `<span class="pagetag">${(b && b.error) || "no rewrite available"}</span>`;
  }
}

async function runFit() {
  const audience = $("aud").value;
  $("cureout").innerHTML = ""; $("curenote").textContent = "";
  if (!audience) { $("verdict").style.display = "none"; $("vdir").textContent = ""; $("curebtn").style.display = "none"; return; }
  $("vdir").textContent = "Checking…";
  const res = await chrome.runtime.sendMessage({ type: "kxFit", url: TAB.url, audience });
  renderFit(res);
}

async function runCure() {
  const audience = $("aud").value; if (!audience) return;
  const btn = $("curebtn"); btn.disabled = true; const old = btn.textContent; btn.textContent = "Working…";
  const res = await chrome.runtime.sendMessage({ type: "kxCure", url: TAB.url, audience, text: PAGE_TEXT });
  renderCure(res, audience);
  btn.disabled = false; btn.textContent = old;
}

chrome.tabs.query({ active: true, currentWindow: true }, async tabs => {
  TAB = tabs[0];
  // descriptive readout
  chrome.runtime.sendMessage({ type: "getScore", tabId: TAB.id }, s => {
    const dom = $("dom");
    if (!s) { dom.textContent = "No data for this page"; }
    else {
      dom.textContent = s.domain || pld(TAB.url);
      $("auth").textContent = (s.authority_score != null ? `Authority ${s.authority_score}/10` : "Authority n/a") +
        (s.pr_rank != null ? ` · rank #${s.pr_rank.toLocaleString()}` : "");
      $("ttf").innerHTML = (s.ttf && s.ttf.length && s.ttf_confident)
        ? (s.ttf_score != null ? `<b>${s.ttf_score}/10</b> ` : "") + s.ttf.map(t => `<span class="chip">${t.topic}</span>`).join("")
        : "<span class='pagetag'>no clear topic</span>";
      const web = s.page_dynamics_web || s.dynamics_web;
      $("scope").textContent = s.page_in_corpus ? "(this page)" : "(domain)";
      if (web) bars(web, $("axes")); else $("axes").innerHTML = "<span class='pagetag'>not yet scored</span>";
    }
  });
  // grab the page text for the cure (best effort)
  try {
    const [r] = await chrome.scripting.executeScript({ target: { tabId: TAB.id }, func: () => (document.body && document.body.innerText || "").replace(/\s+/g, " ").trim().slice(0, 2000) });
    PAGE_TEXT = (r && r.result) || "";
  } catch (e) {}
  // audiences + tier
  const st = await chrome.runtime.sendMessage({ type: "kxState" });
  TIER = (st && st.tier) || "free";
  $("tier").textContent = TIER; $("tier").className = "tier" + (TIER === "premium" ? " premium" : "");
  const sel = $("aud");
  ((st && st.audiences) || []).forEach(a => {
    const o = document.createElement("option"); o.value = a.key;
    o.textContent = a.label + (a.tier === "premium" ? " ★" : "");
    sel.appendChild(o);
  });
  sel.addEventListener("change", runFit);
  $("curebtn").addEventListener("click", runCure);

  // ---- Premium activation ----
  function renderAct(tier) {
    const state = $("actstate"), inp = $("actkey"), btn = $("actbtn");
    if (tier === "premium") { state.textContent = "Premium is active on this device."; inp.style.display = "none"; btn.style.display = "none"; }
    else { state.textContent = "Have a premium key? Paste it to unlock the cure — the specific changes and a ready rewrite."; inp.style.display = ""; btn.style.display = ""; }
  }
  function fillAudiences(list) {
    const s = $("aud"); s.length = 1;
    (list || []).forEach(a => { const o = document.createElement("option"); o.value = a.key; o.textContent = a.label + (a.tier === "premium" ? " ★" : ""); s.appendChild(o); });
  }
  renderAct(TIER);
  $("actbtn").addEventListener("click", async () => {
    const k = $("actkey").value.trim();
    if (!k.startsWith("kx_")) { $("actmsg").textContent = "That does not look like a key."; return; }
    await chrome.storage.local.set({ kxKey: k });
    const st2 = await chrome.runtime.sendMessage({ type: "kxState" });
    TIER = (st2 && st2.tier) || "free";
    if (TIER === "premium") {
      $("actmsg").textContent = "Activated. Premium unlocked.";
      $("tier").textContent = "premium"; $("tier").className = "tier premium";
      renderAct("premium"); fillAudiences(st2.audiences);
    } else { $("actmsg").textContent = "That key is not premium, or it was revoked."; }
  });
});

function pld(u) { try { return new URL(u).hostname.replace(/^www\./, ""); } catch (e) { return ""; } }

// ---- the user's own character profile (DYNAMICS-8 from their browsing) ----
(async () => {
  const D8 = ["Discipline", "Yielding", "Novelty", "Acuity", "Mercuriality", "Impulsivity", "Candour", "Sociability"];
  const id = x => document.getElementById(x);
  function render(p) {
    const st = id("profstate"), box = id("profd8"); box.innerHTML = "";
    if (!p || !p.built) {
      st.textContent = (p && p.n_scored) ? `Seen ${p.n_scored} of your pages so far — keep browsing, or build now.`
        : "Not built yet. Browse a little with the toolbar on, or build from your history below.";
      return;
    }
    st.textContent = `Read from ${p.n_scored} of the pages you actually visit.`;
    const d8 = p.d8_indicative || {};
    D8.forEach(a => {
      const v = d8[a]; const row = document.createElement("div"); row.className = "row";
      if (v == null) {
        row.innerHTML = `<div class="ax">${a}</div><div class="bar"></div><div class="val" style="font-size:9px;color:#b6bac2">n/a</div>`;
        row.title = `${a} is a person-only trait and cannot be read from the content you consume.`;
      } else {
        row.innerHTML = `<div class="ax">${a}</div><div class="bar"><div class="fill" style="width:${Math.round(v * 100)}%"></div></div><div class="val">${v.toFixed(2)}</div>`;
      }
      box.appendChild(row);
    });
  }
  render(await chrome.runtime.sendMessage({ type: "kxProfile" }));
  const run = async (mode, btn) => {
    const old = btn.textContent; btn.disabled = true;
    btn.textContent = mode === "local" ? "Scoring on device…" : "Building…";
    id("profstate").textContent = mode === "local" ? "Reading your pages on this device, this can take a minute…" : "Building your profile…";
    await chrome.runtime.sendMessage({ type: "kxBuildHistory", mode });
    setTimeout(async () => { render(await chrome.runtime.sendMessage({ type: "kxProfile" })); btn.disabled = false; btn.textContent = old; }, mode === "local" ? 3000 : 4500);
  };
  id("buildlocal").addEventListener("click", e => run("local", e.target));
  id("buildserver").addEventListener("click", e => run("server", e.target));
})();

// ---- language: UK English only today; collect demand for what to build next ----
(() => {
  const id = x => document.getElementById(x);
  const btn = id("langbtn"), inp = id("langinput"), msg = id("langmsg");
  if (!btn) return;
  btn.addEventListener("click", async () => {
    const lang = (inp.value || "").trim();
    if (!lang) { inp.focus(); return; }
    btn.disabled = true;
    const r = await chrome.runtime.sendMessage({ type: "kxLangRequest", lang });
    msg.textContent = r ? "Thank you — your request for " + lang + " is logged. We build by demand." : "Could not send, try again.";
    inp.value = ""; btn.disabled = false;
  });
})();
