// Two side-by-side calendar wheels for the Calendar page.
//
// Left:  12 Gregorian months drawn at their TRUE proportional widths
//        (Jan=31, Feb=28, Mar=31, ...) — the asymmetry is the point.
// Right: 13 lunar moons, each exactly 28 days, plus one "day out of time."
//
// Pure SVG, rendered once on mount. Re-renders on langchange so month
// abbreviations follow the current language.

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

  const MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // 365

  function t(key, fallback) {
    return (window.i18n && window.i18n.t) ? window.i18n.t(key, fallback) : fallback;
  }

  // ----- Geometry helpers -------------------------------------------------
  const SIZE = 300, CX = SIZE / 2, CY = SIZE / 2;
  const R_OUTER = 130, R_INNER = 64;
  // Where labels sit (between inner and outer radius).
  const R_LABEL = (R_OUTER + R_INNER) / 2;

  function polar(angleDeg, r) {
    const rad = (angleDeg - 90) * Math.PI / 180;
    return { x: CX + r * Math.cos(rad), y: CY + r * Math.sin(rad) };
  }

  function donutArc(startDeg, endDeg) {
    // Note: SVG arcs draw clockwise from the start point. We build the
    // outer arc going clockwise, then jump inward and return counter-clockwise.
    const sOuter = polar(startDeg, R_OUTER);
    const eOuter = polar(endDeg,   R_OUTER);
    const sInner = polar(endDeg,   R_INNER);
    const eInner = polar(startDeg, R_INNER);
    const sweep = endDeg - startDeg;
    const large = sweep > 180 ? 1 : 0;
    return [
      "M", sOuter.x, sOuter.y,
      "A", R_OUTER, R_OUTER, 0, large, 1, eOuter.x, eOuter.y,
      "L", sInner.x, sInner.y,
      "A", R_INNER, R_INNER, 0, large, 0, eInner.x, eInner.y,
      "Z"
    ].join(" ");
  }

  // ----- Wheel builders ---------------------------------------------------
  function buildMonthWheel() {
    const months = [
      t("page.calendar.mon_jan", "Jan"),
      t("page.calendar.mon_feb", "Feb"),
      t("page.calendar.mon_mar", "Mar"),
      t("page.calendar.mon_apr", "Apr"),
      t("page.calendar.mon_may", "May"),
      t("page.calendar.mon_jun", "Jun"),
      t("page.calendar.mon_jul", "Jul"),
      t("page.calendar.mon_aug", "Aug"),
      t("page.calendar.mon_sep", "Sep"),
      t("page.calendar.mon_oct", "Oct"),
      t("page.calendar.mon_nov", "Nov"),
      t("page.calendar.mon_dec", "Dec"),
    ];
    let cursor = 0;
    const slices = [];
    for (let i = 0; i < 12; i++) {
      const days = MONTH_DAYS[i];
      const sweep = (days / 365) * 360;
      const startDeg = cursor;
      const endDeg = cursor + sweep;
      const midDeg = (startDeg + endDeg) / 2;
      const labelPos = polar(midDeg, R_LABEL);
      slices.push({
        path: donutArc(startDeg, endDeg),
        labelX: labelPos.x,
        labelY: labelPos.y,
        name: months[i],
        days,
      });
      cursor = endDeg;
    }
    return slices;
  }

  function buildMoonWheel() {
    const sweep = 360 / 13;
    const slices = [];
    for (let i = 0; i < 13; i++) {
      const startDeg = i * sweep;
      const endDeg = startDeg + sweep;
      const midDeg = (startDeg + endDeg) / 2;
      const labelPos = polar(midDeg, R_LABEL);
      slices.push({
        path: donutArc(startDeg, endDeg),
        labelX: labelPos.x,
        labelY: labelPos.y,
        // Roman numeral I-XIII — universal across languages.
        name: toRoman(i + 1),
        days: 28,
      });
    }
    return slices;
  }

  function toRoman(n) {
    const map = [
      [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]
    ];
    let out = "";
    for (const [v, s] of map) {
      while (n >= v) { out += s; n -= v; }
    }
    return out;
  }

  // ----- Renderers --------------------------------------------------------
  function svgFor(slices, theme, centerTopText, centerBotText) {
    const slicesHtml = slices.map((s, i) => `
      <g class="wheel-slice ${theme}-slice" data-i="${i}">
        <path d="${s.path}"></path>
        <text class="wheel-label" x="${s.labelX.toFixed(2)}" y="${s.labelY.toFixed(2)}" text-anchor="middle" dominant-baseline="middle">${s.name}</text>
        <text class="wheel-days"  x="${s.labelX.toFixed(2)}" y="${(s.labelY + 13).toFixed(2)}" text-anchor="middle" dominant-baseline="middle">${s.days}</text>
      </g>
    `).join("");
    return `
      <svg class="wheel wheel-${theme}" viewBox="0 0 ${SIZE} ${SIZE}" role="img" aria-hidden="true">
        ${slicesHtml}
        <text class="wheel-center-top" x="${CX}" y="${CY - 8}" text-anchor="middle">${centerTopText}</text>
        <text class="wheel-center-bot" x="${CX}" y="${CY + 14}" text-anchor="middle">${centerBotText}</text>
      </svg>
    `;
  }

  function render() {
    const monthSlices = buildMonthWheel();
    const moonSlices  = buildMoonWheel();

    const monthSvg = svgFor(
      monthSlices, "month",
      "12",
      t("page.calendar.wheel_uneven", "uneven")
    );
    const moonSvg = svgFor(
      moonSlices, "moon",
      "13",
      t("page.calendar.wheel_equal", "× 28")
    );

    root.innerHTML = `
      <div class="moonwheels-grid">
        <figure class="wheel-cell">
          ${monthSvg}
          <figcaption>
            <strong>${t("page.calendar.wheel_month_title", "12 Months")}</strong>
            <span>${t("page.calendar.wheel_month_sub", "365 days — unequal, decreed")}</span>
          </figcaption>
        </figure>
        <figure class="wheel-cell">
          ${moonSvg}
          <figcaption>
            <strong>${t("page.calendar.wheel_moon_title", "13 Moons")}</strong>
            <span>${t("page.calendar.wheel_moon_sub", "364 + 1 days — equal, natural")}</span>
          </figcaption>
        </figure>
      </div>
      <p class="moonwheels-caption">${t("page.calendar.wheel_caption", "The body knows 13. The state imposed 12.")}</p>
    `;
  }

  render();
  window.addEventListener("langchange", render);
})();
