// The Boundaries page — personal Boundary Map.
//
// Four concentric circles: Intimate / Close / Social / Public, with
// Strangers as the field outside. Type a name, pick the ring, place
// the person. Click any chip to remove or move. Saves to localStorage.
// The shape that emerges is your boundary architecture — and the gap
// between where people sit and where you wish they sat is the work.

(function () {
  const root = document.getElementById("boundarymap");
  if (!root) return;

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

  const STORAGE_KEY = "wuys-boundary-map";

  const RINGS = [
    { id: "intimate", color: "#ef4444", r: 60  },
    { id: "close",    color: "#f59e0b", r: 110 },
    { id: "social",   color: "#10b981", r: 160 },
    { id: "public",   color: "#3b82f6", r: 210 }
  ];

  // Restore people from localStorage.
  let people = {};
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
    if (saved && typeof saved === "object") people = saved;
  } catch (_) {}

  const svg       = root.querySelector(".bm-svg");
  const inputEl   = root.querySelector(".bm-input");
  const ringBtnsEl= root.querySelector(".bm-ring-btns");
  const addBtn    = root.querySelector(".bm-add");
  const listEl    = root.querySelector(".bm-list");
  const emptyEl   = root.querySelector(".bm-empty");
  const SVG_NS    = "http://www.w3.org/2000/svg";

  let selectedRing = "social";

  // Build ring buttons.
  RINGS.forEach((R) => {
    const btn = document.createElement("button");
    btn.type = "button";
    btn.className = "bm-ring-btn" + (R.id === selectedRing ? " active" : "");
    btn.dataset.ring = R.id;
    btn.style.setProperty("--c", R.color);
    btn.setAttribute("data-i18n", "page.boundaries.bm_ring_" + R.id);
    btn.textContent = R.id;
    ringBtnsEl.appendChild(btn);
  });
  ringBtnsEl.addEventListener("click", (e) => {
    const btn = e.target.closest(".bm-ring-btn");
    if (!btn) return;
    selectedRing = btn.dataset.ring;
    ringBtnsEl.querySelectorAll(".bm-ring-btn").forEach((b) =>
      b.classList.toggle("active", b === btn));
  });

  // Build the SVG rings.
  const CX = 250, CY = 250;
  RINGS.slice().reverse().forEach((R) => {
    const c = document.createElementNS(SVG_NS, "circle");
    c.setAttribute("cx", CX); c.setAttribute("cy", CY);
    c.setAttribute("r", R.r);
    c.setAttribute("class", "bm-ring bm-ring-" + R.id);
    c.setAttribute("fill", R.color);
    c.setAttribute("fill-opacity", "0.08");
    c.setAttribute("stroke", R.color);
    c.setAttribute("stroke-opacity", "0.4");
    c.setAttribute("stroke-width", "1");
    svg.appendChild(c);
    // Ring label.
    const lbl = document.createElementNS(SVG_NS, "text");
    lbl.setAttribute("x", CX);
    lbl.setAttribute("y", CY - R.r + 14);
    lbl.setAttribute("text-anchor", "middle");
    lbl.setAttribute("class", "bm-ring-label");
    lbl.setAttribute("fill", R.color);
    lbl.setAttribute("data-i18n", "page.boundaries.bm_ring_" + R.id);
    lbl.textContent = R.id;
    svg.appendChild(lbl);
  });
  // Center dot ("you").
  const me = document.createElementNS(SVG_NS, "circle");
  me.setAttribute("cx", CX); me.setAttribute("cy", CY);
  me.setAttribute("r", 8);
  me.setAttribute("class", "bm-me");
  svg.appendChild(me);

  function save() {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(people)); } catch (_) {}
  }
  function uid() { return Math.random().toString(36).slice(2, 9); }

  function placePeople() {
    // Remove old chips from SVG.
    svg.querySelectorAll(".bm-chip").forEach((c) => c.remove());
    // Group by ring.
    const grouped = { intimate: [], close: [], social: [], public: [] };
    Object.keys(people).forEach((id) => {
      const p = people[id];
      if (grouped[p.ring]) grouped[p.ring].push({ id, name: p.name });
    });
    // Place each group around its ring.
    RINGS.forEach((R) => {
      const list = grouped[R.id] || [];
      const n = list.length;
      if (!n) return;
      list.forEach((person, i) => {
        const ang = (i / n) * Math.PI * 2 - Math.PI / 2;
        const r = R.id === "intimate" ? R.r * 0.55
                : R.r - 28;
        const x = CX + r * Math.cos(ang);
        const y = CY + r * Math.sin(ang);
        const g = document.createElementNS(SVG_NS, "g");
        g.setAttribute("class", "bm-chip");
        g.dataset.id = person.id;
        g.setAttribute("transform", "translate(" + x.toFixed(1) + "," + y.toFixed(1) + ")");
        const text = document.createElementNS(SVG_NS, "text");
        text.setAttribute("text-anchor", "middle");
        text.setAttribute("dominant-baseline", "middle");
        text.setAttribute("class", "bm-chip-text");
        text.setAttribute("fill", R.color);
        text.textContent = person.name;
        // Background bg behind text (rect computed after measurement isn't trivial in SVG;
        // use a fill via a 'rect' sized to a fixed padding).
        const padX = 7, padY = 4;
        const charW = Math.max(person.name.length * 6.2, 28);
        const bg = document.createElementNS(SVG_NS, "rect");
        bg.setAttribute("x", -(charW / 2 + padX));
        bg.setAttribute("y", -8 - padY);
        bg.setAttribute("width", charW + padX * 2);
        bg.setAttribute("height", 16 + padY * 2);
        bg.setAttribute("rx", 9);
        bg.setAttribute("fill", "rgba(10, 8, 18, 0.92)");
        bg.setAttribute("stroke", R.color);
        bg.setAttribute("stroke-width", "1");
        g.appendChild(bg);
        g.appendChild(text);
        svg.appendChild(g);
      });
    });
  }
  function renderList() {
    const keys = Object.keys(people);
    if (keys.length === 0) {
      emptyEl.style.display = "";
      listEl.style.display = "none";
      return;
    }
    emptyEl.style.display = "none";
    listEl.style.display = "";
    listEl.innerHTML = "";
    keys.forEach((id) => {
      const p = people[id];
      const R = RINGS.find((x) => x.id === p.ring);
      const row = document.createElement("div");
      row.className = "bm-list-row";
      row.style.setProperty("--c", R ? R.color : "#888");
      row.innerHTML =
        '<span class="bm-list-name">' + escapeHtml(p.name) + '</span>' +
        '<span class="bm-list-ring">' + t("page.boundaries.bm_ring_" + p.ring, p.ring) + '</span>' +
        '<button class="bm-list-del" type="button" data-id="' + id + '" aria-label="remove">×</button>';
      listEl.appendChild(row);
    });
  }
  function escapeHtml(s) {
    return s.replace(/[<>&"]/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;" }[c]));
  }
  function render() {
    placePeople();
    renderList();
  }

  function addPerson() {
    const name = inputEl.value.trim().slice(0, 22);
    if (!name) return;
    const id = uid();
    people[id] = { name, ring: selectedRing };
    inputEl.value = "";
    save();
    render();
  }
  addBtn.addEventListener("click", addPerson);
  inputEl.addEventListener("keydown", (e) => {
    if (e.key === "Enter") { e.preventDefault(); addPerson(); }
  });
  listEl.addEventListener("click", (e) => {
    const btn = e.target.closest(".bm-list-del");
    if (!btn) return;
    delete people[btn.dataset.id];
    save();
    render();
  });
  window.addEventListener("langchange", render);

  render();
})();
