/* eslint-disable */
/* =============================================================
   dream-bodygraph.jsx — رسم مصفوفة الحلم
   -------------------------------------------------------------
   يقرأ الهندسة من DREAM_GEO (أفقية، خاصّة بالمصفوفة) والحالة من
   نتيجة DreamRave. لا يحسب شيئًا بنفسه.

   ── لماذا هندسة مستقلّة ──────────────────────────────────────
   جُرِّبت إعادة استعمال هندسة البودي-جراف، فأعطت شكلًا رأسيًّا لا
   يشبه المصفوفة: ترتيب المراكز فيها أفقيّ وأشكالها مختلفة. لا
   تُعِد ربطه بـ BG_CENTERS.

   ── الطبقتان ────────────────────────────────────────────────
   سماويّ من الميلاد · بنفسجيّ من لحظة القمر −88° · متدرّج من
   الاثنين. المرجع يستعمل الأسود والأحمر؛ لوننا لغتنا.

   ── تحذير ───────────────────────────────────────────────────
   لا تمرّر كائن نبرة خام إلى React — يُفرِغ الصفحة. كل نصّ هنا
   يمرّ بـ tp(field, lang).
   ============================================================= */
(function () {
  const tp = (f, lang) =>
    typeof f === "string" ? f
      : !f ? ""
      : (window.SpadeTone ? SpadeTone.pick(f[lang === "en" ? "en" : "ar"] || f, lang) : "");

  /* نقاط الشكل — تُحسب مرّة، فالهندسة ثابتة. */
  function shapeOf(c) {
    const { shape, cx, cy } = c;
    if (shape === "circle") return { el: "circle", p: { cx, cy, r: c.rad } };
    if (shape === "rect") {
      return { el: "rect", p: { x: cx - c.w / 2, y: cy - c.h / 2, width: c.w, height: c.h, rx: c.r || 18 } };
    }
    if (shape === "tri-down") {
      const hw = c.w / 2, top = cy - c.h / 2, bot = cy + c.h / 2;
      return { el: "polygon", p: { points: `${cx - hw},${top} ${cx + hw},${top} ${cx},${bot}` } };
    }
    if (shape === "diamond") {
      const hw = c.w / 2, hh = c.h / 2;
      return { el: "polygon", p: { points: `${cx},${cy - hh} ${cx + hw},${cy} ${cx},${cy + hh} ${cx - hw},${cy}` } };
    }
    if (shape === "hex") {
      const r = c.rad;
      const pts = [];
      for (let i = 0; i < 6; i++) {
        const a = (Math.PI / 180) * (60 * i - 30);
        pts.push(`${(cx + r * Math.cos(a)).toFixed(1)},${(cy + r * Math.sin(a)).toFixed(1)}`);
      }
      return { el: "polygon", p: { points: pts.join(" ") } };
    }
    return null;
  }

  window.DreamBodygraph = function DreamBodygraph({ result, lang }) {
    const G = window.DREAM_GEO;
    if (!result || !G) return null;

    const ar = lang !== "en";
    const C = window.DREAM_CONTENT || {};
    const L = (C.graph || {});

    const definedSet = new Set((result.centers || []).map((c) => c.id));
    const gateSet = new Set(result.gates || []);
    const hangSet = new Set(result.hanging || []);
    const liveChan = new Set((result.channels || []).map((c) =>
      c.gates.slice().sort((x, y) => x - y).join("-")));

    /* طبقة كل بوابة: من الميلاد، أو من لحظة القمر، أو منهما. */
    const layerOf = {};
    (result.activations || []).forEach((a) => {
      layerOf[a.gate] = layerOf[a.gate] && layerOf[a.gate] !== a.layer ? "both" : a.layer;
    });

    const FILL = { waking: "#62DDFF", lunar: "#C084FF", both: "url(#dbgBoth)" };
    const cName = (id) => tp(((C.centers || {})[id] || {}).name, lang) || id;

    return (
      <div className="dbg-wrap">
        <svg viewBox={G.viewBox} className="dbg-svg" role="img"
             aria-label={ar ? "رسم مصفوفة الحلم" : "Dream matrix chart"}>
          <defs>
            <linearGradient id="dbgBoth" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="#62DDFF" />
              <stop offset="100%" stopColor="#C084FF" />
            </linearGradient>
          </defs>

          <path d={G.silhouette} className="dbg-sil" />

          {/* خيوط الأطراف الغائبة ثم أشباحها */}
          {Object.keys(G.ghostPaths).map((g) => (
            <path key={"gp" + g} d={G.ghostPaths[g]} className="dbg-ghost-line" />
          ))}
          {Object.keys(G.ghosts).map((g) => {
            const p = G.ghosts[g];
            return (
              <g key={"gh" + g} className="dbg-ghost">
                <circle cx={p[0]} cy={p[1]} r="15" />
                <text x={p[0]} y={p[1]} textAnchor="middle" dominantBaseline="central">{g}</text>
                <title>{tp(L.ghost, lang)}</title>
              </g>
            );
          })}

          {/* القنوات: الخافتة أولًا ثم المكتملة فوقها */}
          {Object.keys(G.paths).map((key) => {
            const on = liveChan.has(key);
            const meta = (C.channels || {})[key] || {};
            return (
              <path key={key} d={G.paths[key]} className={"dbg-chan" + (on ? " on" : "")}>
                <title>{key} · {tp(meta.name, lang)}</title>
              </path>
            );
          })}

          {/* المراكز */}
          {G.centers.map((c) => {
            const on = definedSet.has(c.id);
            const s = shapeOf(c);
            if (!s) return null;
            const El = s.el;
            return (
              <El key={c.id} {...s.p}
                className={"dbg-center" + (on ? " on" : " open")}
                style={on ? { fill: c.tone, stroke: c.tone } : { stroke: c.tone }}>
                <title>{cName(c.id) + " — " + tp(on ? L.defined : L.open, lang)}</title>
              </El>
            );
          })}

          {/* البوابات الخمس عشرة */}
          {Object.keys(G.gates).map((k) => {
            const g = +k, p = G.gates[k];
            const on = gateSet.has(g);
            const layer = layerOf[g];
            const hang = on && hangSet.has(g);
            return (
              <g key={g} className={"dbg-gate" + (on ? " on" : "")}>
                {hang && <circle cx={p[0]} cy={p[1]} r="24" className="dbg-hang-ring" />}
                <circle cx={p[0]} cy={p[1]} r="17"
                  className={"dbg-dot" + (on ? "" : " off")}
                  style={on ? { fill: FILL[layer] || FILL.waking } : undefined} />
                <text x={p[0]} y={p[1]} className={"dbg-num" + (on ? "" : " off")}
                  textAnchor="middle" dominantBaseline="central">{g}</text>
                <title>
                  {g + (on
                    ? " — " + tp(layer === "both" ? L.layerBoth : layer === "lunar" ? L.layerLunar : L.layerWaking, lang)
                        + (hang ? " · " + tp(L.hanging, lang) : "")
                    : " — " + tp(L.inactive, lang))}
                </title>
              </g>
            );
          })}
        </svg>

        <ul className="dbg-legend">
          <li><i className="sw waking" />{tp(L.legendWaking, lang)}</li>
          <li><i className="sw lunar" />{tp(L.legendLunar, lang)}</li>
          <li><i className="sw both" />{tp(L.legendBoth, lang)}</li>
          <li><i className="sw dead" />{tp(L.legendOff, lang)}</li>
          <li><i className="sw ghost" />{tp(L.legendGhost, lang)}</li>
        </ul>
      </div>
    );
  };
})();
