// The Sovereignty page — personal autonomy radar.
//
// 8 axes of sovereignty. Each scored 0–10 by the user. The polygon
// of your current shape is drawn on the radar; surface area becomes
// a single "Sovereignty Score" (0–100). Values persist to localStorage
// so the shape survives reloads.
//
// The point is not to score perfect — it is to see the shape of your
// life. The places where the polygon caves inward are where the world
// owns a piece of you that you can decide to reclaim.

(function () {
  const root = document.getElementById("radar");
  if (!root) return;
  const view = document.querySelector('.view[data-view="sovereignty"]');
  if (!view) return;

  const t = (k, fb) => (window.i18n && window.i18n.t) ? window.i18n.t(k, fb) : fb;

  const AXES = [
    { id: "body",   color: "#fbbf24", angle: -90 },
    { id: "money",  color: "#10b981", angle: -45 },
    { id: "time",   color: "#06b6d4", angle: 0   },
    { id: "voice",  color: "#3b82f6", angle: 45  },
    { id: "mind",   color: "#a855f7", angle: 90  },
    { id: "skills", color: "#ec4899", angle: 135 },
    { id: "bonds",  color: "#ef4444", angle: 180 },
    { id: "spirit", color: "#f59e0b", angle: 225 }
  ];

  const STORAGE_KEY = "wuys-sovereignty-radar";
  const DEFAULT_VAL = 5;

  // Load saved values from localStorage; fall back to default.
  let values = {};
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
    AXES.forEach((a) => { values[a.id] = saved[a.id] != null ? saved[a.id] : DEFAULT_VAL; });
  } catch (_) {
    AXES.forEach((a) => { values[a.id] = DEFAULT_VAL; });
  }
  function save() {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(values)); } catch (_) {}
  }

  const svg       = root.querySelector(".rd-svg");
  const polyEl    = root.querySelector(".rd-poly");
  const dotsEl    = root.querySelector(".rd-dots");
  const labelsEl  = root.querySelector(".rd-labels");
  const ringsEl   = root.querySelector(".rd-rings");
  const slidersEl = root.querySelector(".rd-sliders");
  const scoreEl   = root.querySelector(".rd-score");
  const verdictEl = root.querySelector(".rd-verdict");
  const resetBtn  = root.querySelector(".rd-reset");
  const exportBtn = root.querySelector(".rd-export");
  const infoEl    = root.querySelector(".rd-info");
  const SVG_NS    = "http://www.w3.org/2000/svg";

  // Radar geometry — center (200,200), max radius 160.
  const CX = 200, CY = 200, R = 160;

  function deg2rad(d) { return (d * Math.PI) / 180; }

  // Build the concentric rings (octagon at each integer level 2..10).
  function ringPoints(level) {
    const r = (level / 10) * R;
    return AXES.map((a) => {
      const rad = deg2rad(a.angle);
      return (CX + Math.cos(rad) * r).toFixed(1) + "," + (CY + Math.sin(rad) * r).toFixed(1);
    }).join(" ");
  }
  [2, 4, 6, 8, 10].forEach((lvl) => {
    const ring = document.createElementNS(SVG_NS, "polygon");
    ring.setAttribute("points", ringPoints(lvl));
    ring.setAttribute("class", "rd-ring");
    ring.setAttribute("data-level", String(lvl));
    ringsEl.appendChild(ring);
  });

  // Axis spokes + labels.
  AXES.forEach((a) => {
    const rad = deg2rad(a.angle);
    // Spoke
    const line = document.createElementNS(SVG_NS, "line");
    line.setAttribute("x1", CX);
    line.setAttribute("y1", CY);
    line.setAttribute("x2", (CX + Math.cos(rad) * R).toFixed(1));
    line.setAttribute("y2", (CY + Math.sin(rad) * R).toFixed(1));
    line.setAttribute("class", "rd-spoke");
    ringsEl.appendChild(line);
    // Label
    const lblR = R + 20;
    const text = document.createElementNS(SVG_NS, "text");
    text.setAttribute("x", (CX + Math.cos(rad) * lblR).toFixed(1));
    text.setAttribute("y", (CY + Math.sin(rad) * lblR).toFixed(1));
    text.setAttribute("class", "rd-label");
    text.setAttribute("data-axis", a.id);
    text.setAttribute("fill", a.color);
    text.setAttribute("text-anchor", "middle");
    text.setAttribute("dominant-baseline", "middle");
    text.setAttribute("data-i18n", "page.sovereignty.rd_axis_" + a.id);
    text.textContent = a.id;
    labelsEl.appendChild(text);
  });

  // Build sliders.
  AXES.forEach((a) => {
    const row = document.createElement("div");
    row.className = "rd-slider-row";
    row.style.setProperty("--c", a.color);
    row.innerHTML =
      '<label class="rd-slider-label" data-i18n="page.sovereignty.rd_axis_' + a.id + '">' + a.id + '</label>' +
      '<input class="rd-slider" type="range" min="0" max="10" step="1" value="' + values[a.id] + '" data-axis="' + a.id + '" />' +
      '<span class="rd-slider-val">' + values[a.id] + '</span>';
    slidersEl.appendChild(row);
  });

  // Build the polygon + value dots.
  function pointForAxis(a) {
    const v = values[a.id];
    const r = (v / 10) * R;
    const rad = deg2rad(a.angle);
    return [CX + Math.cos(rad) * r, CY + Math.sin(rad) * r];
  }
  function render() {
    const pts = AXES.map(pointForAxis);
    polyEl.setAttribute("points", pts.map(p => p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" "));
    // Dots at each vertex
    while (dotsEl.firstChild) dotsEl.removeChild(dotsEl.firstChild);
    AXES.forEach((a, i) => {
      const [x, y] = pts[i];
      const c = document.createElementNS(SVG_NS, "circle");
      c.setAttribute("cx", x.toFixed(1));
      c.setAttribute("cy", y.toFixed(1));
      c.setAttribute("r", 4);
      c.setAttribute("fill", a.color);
      c.setAttribute("class", "rd-dot");
      dotsEl.appendChild(c);
    });
    // Score = average × 10 → 0..100
    const sum = AXES.reduce((s, a) => s + values[a.id], 0);
    const score = Math.round((sum / AXES.length) * 10);
    scoreEl.textContent = score;
    verdictEl.textContent = t(verdictKey(score), verdictFallback(score));
  }
  function verdictKey(score) {
    if (score >= 85) return "page.sovereignty.rd_v_5";
    if (score >= 65) return "page.sovereignty.rd_v_4";
    if (score >= 45) return "page.sovereignty.rd_v_3";
    if (score >= 25) return "page.sovereignty.rd_v_2";
    return "page.sovereignty.rd_v_1";
  }
  function verdictFallback(score) {
    if (score >= 85) return "Sovereign";
    if (score >= 65) return "Mostly your own";
    if (score >= 45) return "Half free";
    if (score >= 25) return "Mostly owned";
    return "Captured";
  }

  // Slider wiring.
  slidersEl.addEventListener("input", (e) => {
    const s = e.target.closest(".rd-slider");
    if (!s) return;
    const id = s.dataset.axis;
    values[id] = parseInt(s.value, 10);
    s.parentElement.querySelector(".rd-slider-val").textContent = values[id];
    render();
    save();
  });

  // ---- Axis info panel: hover preview + click to pin ------------------
  let pinned = null;
  function showInfo(id) {
    const a = AXES.find(x => x.id === id);
    if (!a) return;
    const title = infoEl.querySelector(".rd-info-title");
    const body  = infoEl.querySelector(".rd-info-body");
    title.textContent = t("page.sovereignty.rd_axis_" + id, id);
    title.style.color = a.color;
    body.textContent  = t("page.sovereignty.rd_desc_" + id, "");
    infoEl.style.setProperty("--c", a.color);
    infoEl.classList.add("active");
    infoEl.dataset.axis = id;
  }
  function hideInfo() {
    infoEl.classList.remove("active");
    infoEl.removeAttribute("data-axis");
  }
  function bindAxisInfo(el, id) {
    el.addEventListener("click", (e) => {
      e.stopPropagation();
      if (pinned === id) { pinned = null; hideInfo(); return; }
      pinned = id;
      showInfo(id);
    });
    el.addEventListener("mouseenter", () => {
      if (pinned) return;
      showInfo(id);
    });
    el.addEventListener("mouseleave", () => {
      if (pinned) return;
      hideInfo();
    });
  }
  // Bind to each slider label + each SVG axis label.
  AXES.forEach((a) => {
    const sliderLabel = slidersEl.querySelector('.rd-slider-label[data-i18n="page.sovereignty.rd_axis_' + a.id + '"]');
    if (sliderLabel) bindAxisInfo(sliderLabel, a.id);
    const svgLabel = labelsEl.querySelector('text[data-axis="' + a.id + '"]');
    if (svgLabel) bindAxisInfo(svgLabel, a.id);
  });
  // Click anywhere else dismisses a pinned panel.
  document.addEventListener("click", (e) => {
    if (!pinned) return;
    if (e.target.closest(".rd-slider-label, text[data-axis], .rd-info")) return;
    pinned = null;
    hideInfo();
  });

  resetBtn.addEventListener("click", () => {
    AXES.forEach((a) => { values[a.id] = DEFAULT_VAL; });
    slidersEl.querySelectorAll(".rd-slider").forEach((s) => {
      s.value = DEFAULT_VAL;
      s.parentElement.querySelector(".rd-slider-val").textContent = DEFAULT_VAL;
    });
    render();
    save();
  });

  // ---- Export to PNG ---------------------------------------------------
  function todayISO() {
    const d = new Date();
    const pad = (n) => String(n).padStart(2, "0");
    return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate());
  }
  function exportPNG() {
    const W = 900, H = 1000;
    const cv = document.createElement("canvas");
    cv.width = W; cv.height = H;
    const c = cv.getContext("2d");
    // Background
    const bg = c.createLinearGradient(0, 0, 0, H);
    bg.addColorStop(0, "#15102a");
    bg.addColorStop(1, "#0a0612");
    c.fillStyle = bg;
    c.fillRect(0, 0, W, H);

    // Title
    c.fillStyle = "#f5f3ef";
    c.textAlign = "center";
    c.font = "italic 38px 'Cormorant Garamond', Georgia, serif";
    c.fillText(t("page.sovereignty.rd_title", "The Sovereignty Radar"), W / 2, 70);

    const dateStr = todayISO();
    c.font = "16px 'Courier New', monospace";
    c.fillStyle = "rgba(245, 243, 239, 0.55)";
    c.fillText(dateStr, W / 2, 100);

    // Radar geometry
    const RCX = W / 2, RCY = 480, RR = 260;
    // Rings
    function octPts(rr) {
      return AXES.map((a) => {
        const rad = deg2rad(a.angle);
        return [RCX + Math.cos(rad) * rr, RCY + Math.sin(rad) * rr];
      });
    }
    [2, 4, 6, 8, 10].forEach((lvl) => {
      const pts = octPts((lvl / 10) * RR);
      c.strokeStyle = lvl === 10 ? "rgba(255,255,255,0.22)" : "rgba(255,255,255,0.07)";
      c.lineWidth = 1;
      c.beginPath();
      pts.forEach((p, i) => i === 0 ? c.moveTo(p[0], p[1]) : c.lineTo(p[0], p[1]));
      c.closePath();
      c.stroke();
    });
    // Spokes
    c.strokeStyle = "rgba(255,255,255,0.08)";
    AXES.forEach((a) => {
      const rad = deg2rad(a.angle);
      c.beginPath();
      c.moveTo(RCX, RCY);
      c.lineTo(RCX + Math.cos(rad) * RR, RCY + Math.sin(rad) * RR);
      c.stroke();
    });
    // Polygon
    const polyPts = AXES.map((a) => {
      const v = values[a.id];
      const r = (v / 10) * RR;
      const rad = deg2rad(a.angle);
      return [RCX + Math.cos(rad) * r, RCY + Math.sin(rad) * r];
    });
    c.beginPath();
    polyPts.forEach((p, i) => i === 0 ? c.moveTo(p[0], p[1]) : c.lineTo(p[0], p[1]));
    c.closePath();
    c.fillStyle = "rgba(167, 139, 250, 0.25)";
    c.fill();
    c.strokeStyle = "rgba(167, 139, 250, 0.95)";
    c.lineWidth = 2;
    c.stroke();
    // Dots
    AXES.forEach((a, i) => {
      const [x, y] = polyPts[i];
      c.fillStyle = a.color;
      c.beginPath();
      c.arc(x, y, 6, 0, 2 * Math.PI);
      c.fill();
    });
    // Axis labels (name + value)
    c.font = "bold 16px 'Cormorant Garamond', Georgia, serif";
    AXES.forEach((a) => {
      const rad = deg2rad(a.angle);
      const lr = RR + 36;
      const x = RCX + Math.cos(rad) * lr;
      const y = RCY + Math.sin(rad) * lr;
      c.fillStyle = a.color;
      c.textAlign = "center";
      c.textBaseline = "middle";
      const name = t("page.sovereignty.rd_axis_" + a.id, a.id).toUpperCase();
      c.fillText(name, x, y - 9);
      c.font = "20px 'Courier New', monospace";
      c.fillText(String(values[a.id]), x, y + 12);
      c.font = "bold 16px 'Cormorant Garamond', Georgia, serif";
    });

    // Score
    const sum = AXES.reduce((s, a) => s + values[a.id], 0);
    const score = Math.round((sum / AXES.length) * 10);
    c.fillStyle = "rgba(167, 139, 250, 1)";
    c.font = "72px 'Courier New', monospace";
    c.textAlign = "center";
    c.fillText(String(score), W / 2, 880);
    c.fillStyle = "rgba(245, 243, 239, 0.55)";
    c.font = "20px 'Courier New', monospace";
    c.fillText("/ 100", W / 2 + 90, 880);

    // Verdict
    c.fillStyle = "rgba(245, 243, 239, 0.85)";
    c.font = "italic 22px 'Cormorant Garamond', Georgia, serif";
    c.fillText(t(verdictKey(score), verdictFallback(score)), W / 2, 920);

    // Footer
    c.fillStyle = "rgba(245, 243, 239, 0.35)";
    c.font = "12px 'Courier New', monospace";
    c.fillText("wakeupyoursoul.com · " + t("page.sovereignty.rd_footer_tag", "your sovereignty is yours"), W / 2, 970);

    // Download
    cv.toBlob((blob) => {
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "sovereignty-radar-" + dateStr + ".png";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      setTimeout(() => URL.revokeObjectURL(url), 5000);
    }, "image/png");
  }
  exportBtn.addEventListener("click", exportPNG);

  window.addEventListener("langchange", () => {
    render();
    if (infoEl.dataset.axis) showInfo(infoEl.dataset.axis);
  });

  render();
})();
