// Sacred-geometry visualizer for the Magic page.
//
// Three forms, each generated as SVG, each cycling on a timer:
//   1) Seed of Life     — 7 circles, the foundational form
//   2) Flower of Life   — 19 circles, the bloom
//   3) Metatron's Cube  — 13 dots + every line between them; contains the
//                          5 Platonic solids hidden in the lattice.
//
// Forms fade in over a few seconds (circles + lines stroke-draw via
// stroke-dashoffset), hold, then fade to the next.

(function () {
  const wrap = document.getElementById("magicgeo");
  if (!wrap) return;
  const svg = wrap.querySelector("svg");
  const labelEl = wrap.querySelector(".mg-label");
  const dotsEl  = wrap.querySelector(".mg-dots");
  if (!svg || !labelEl || !dotsEl) return;

  const SIZE = 420, CX = SIZE / 2, CY = SIZE / 2;
  const R = 38;                       // circle radius (also the seed spacing)
  const SQRT3 = Math.sqrt(3);

  function t(key, fallback) {
    return (window.i18n && window.i18n.t) ? window.i18n.t(key, fallback) : fallback;
  }
  function pt(dist, angleDeg) {
    const rad = (angleDeg - 90) * Math.PI / 180;
    return [CX + dist * Math.cos(rad), CY + dist * Math.sin(rad)];
  }

  // ----- Centers ----------------------------------------------------------
  const seedCenters = [[CX, CY]];
  for (let i = 0; i < 6; i++) seedCenters.push(pt(R, i * 60));

  const flowerCenters = seedCenters.slice();
  // Outer ring of 12: 6 at distance R*√3 (offset 30°) and 6 at distance 2R.
  for (let i = 0; i < 6; i++) flowerCenters.push(pt(R * SQRT3, 30 + i * 60));
  for (let i = 0; i < 6; i++) flowerCenters.push(pt(R * 2,    i * 60));

  // Metatron / Fruit-of-Life centers (13 dots): center + first hex ring
  // at distance R*√3, second hex ring at distance 2R*√3.
  const metaCenters = [[CX, CY]];
  for (let i = 0; i < 6; i++) metaCenters.push(pt(R * SQRT3,     i * 60));
  for (let i = 0; i < 6; i++) metaCenters.push(pt(R * 2 * SQRT3, i * 60));

  // ----- SVG builders -----------------------------------------------------
  function ns(name) { return document.createElementNS("http://www.w3.org/2000/svg", name); }

  function makeForm(name, centers, withLines) {
    const g = ns("g");
    g.classList.add("mg-form", "mg-" + name);
    // Circles.
    centers.forEach((c, i) => {
      const circ = ns("circle");
      circ.setAttribute("cx", c[0]);
      circ.setAttribute("cy", c[1]);
      circ.setAttribute("r",  R);
      circ.classList.add("mg-circle");
      circ.style.animationDelay = (i * 0.06).toFixed(2) + "s";
      g.appendChild(circ);
    });
    // Connecting lines (Metatron — every center to every other).
    if (withLines) {
      const lines = [];
      for (let i = 0; i < centers.length; i++) {
        for (let j = i + 1; j < centers.length; j++) {
          lines.push([centers[i], centers[j]]);
        }
      }
      lines.forEach((ln, i) => {
        const line = ns("line");
        line.setAttribute("x1", ln[0][0]);
        line.setAttribute("y1", ln[0][1]);
        line.setAttribute("x2", ln[1][0]);
        line.setAttribute("y2", ln[1][1]);
        line.classList.add("mg-line");
        line.style.animationDelay = (1.0 + i * 0.012).toFixed(2) + "s";
        g.appendChild(line);
      });
    }
    return g;
  }

  // Build all three groups (hidden by default — JS toggles .visible).
  const forms = [
    { id: "seed",    label: "page.magic.mg_seed",    fallback: "Seed of Life",
      el: makeForm("seed",   seedCenters,   false) },
    { id: "flower",  label: "page.magic.mg_flower",  fallback: "Flower of Life",
      el: makeForm("flower", flowerCenters, false) },
    { id: "metatron", label: "page.magic.mg_metatron", fallback: "Metatron's Cube",
      el: makeForm("metatron", metaCenters, true) },
  ];
  forms.forEach((f) => svg.appendChild(f.el));

  // Indicator dots — one per form.
  dotsEl.innerHTML = forms.map((_, i) =>
    '<span class="mg-dot" data-i="' + i + '"></span>'
  ).join("");
  const dotEls = dotsEl.querySelectorAll(".mg-dot");

  // ----- Cycle ------------------------------------------------------------
  const HOLD_MS  = 6500;
  const FADE_MS  = 900;
  let idx = 0;
  let timer = null;

  function show(i) {
    idx = i;
    forms.forEach((f, j) => f.el.classList.toggle("visible", j === i));
    dotEls.forEach((d, j) => d.classList.toggle("active", j === i));
    labelEl.textContent = t(forms[i].label, forms[i].fallback);
  }

  function tick() {
    show((idx + 1) % forms.length);
  }

  function start() {
    if (timer) return;
    show(idx);
    timer = setInterval(tick, HOLD_MS + FADE_MS);
  }
  function stop() {
    if (timer) clearInterval(timer);
    timer = null;
  }

  // Wire dots — let the visitor jump.
  dotEls.forEach((d) => d.addEventListener("click", () => {
    show(parseInt(d.dataset.i, 10));
    if (timer) { clearInterval(timer); timer = setInterval(tick, HOLD_MS + FADE_MS); }
  }));

  // Pause when the Magic view isn't on screen.
  const magicView = document.querySelector('.view[data-view="magic"]');
  function isActive() { return magicView && magicView.classList.contains("active"); }
  if (magicView && "MutationObserver" in window) {
    new MutationObserver(() => { if (isActive()) start(); else stop(); })
      .observe(magicView, { attributes: true, attributeFilter: ["class"] });
    if (isActive()) start();
  } else {
    start();
  }
  document.addEventListener("visibilitychange", () => {
    if (document.hidden) stop();
    else if (isActive()) start();
  });

  window.addEventListener("langchange", () => labelEl.textContent = t(forms[idx].label, forms[idx].fallback));
})();
