/* eslint-disable */
/* =============================================================
   Interactive Bodygraph — faithful HD layout, our colours
   -----
   Geometry ported 1:1 from src/lib/bodygraph/bodygraph-geometry.ts.
   Render approach mirrors src/components/bodygraph/BodyGraphRenderer.tsx:
     • centers: gradient fill by tone when defined; dim dashed when not
     • channels: grey track + coloured active channel
     • gates: numbered nodes, coloured by activation
   Brand twist (our "features"):
     • personality / conscious = cyan  (#62DDFF)
     • design / unconscious   = violet (#C084FF)
     • both/mixed             = cyan→violet gradient
   Click an ACTIVE gate or channel → a small popup with real info
   (GATE_NAMES / GATE_THEMES / CENTER_INFO from bodygraph-knowledge.js).

   Props: lang, width, height, showGateNumbers, selectable, popups
   ============================================================= */

const { useState: useStateBG, useRef: useRefBG } = React;

const BG_COL = {
  personality: "#62DDFF",
  design: "#C084FF",
  white: "#FFFFFF",
};

// Scale factor: render constants (stroke widths, radii, fonts) were authored
// for a 360-wide viewBox; the geometry now lives in a ~1000-wide reference
// space. Multiply visual dimensions by BG_K so they look identical at any scale.
const BG_K = (() => {
  const parts = (window.BG_VIEWBOX || "0 0 360 530").trim().split(/\s+/);
  const w = parseFloat(parts[2]) || 360;
  return w / 360;
})();
const bgk = (n) => +(n * BG_K).toFixed(2);

// center tone → gradient id (matches source palette)
const BG_TONE = {
  head: "gold", ajna: "green", throat: "bronze", g: "yellow",
  ego: "rose", spleen: "brown", solar_plexus: "brown", sacral: "rose", root: "violet",
};
// solid tone colours (for MiniBodygraph, which has no shared gradient defs)
const BG_TONE_SOLID = {
  gold: "#f4da55", green: "#259552", bronze: "#8a6649", yellow: "#e7c642",
  rose: "#d3354c", brown: "#996437", violet: "#8a4be8",
};

function bgShapePoints(c) {
  const { shape, x, y, w, h } = c;
  if (shape === "poly") return c.pts.map((p) => `${p[0]},${p[1]}`).join(" ");
  if (shape === "tri-up") return `${x + w / 2},${y} ${x + w},${y + h} ${x},${y + h}`;
  if (shape === "tri-down") return `${x},${y} ${x + w},${y} ${x + w / 2},${y + h}`;
  if (shape === "tri-right") return `${x},${y} ${x + w},${y + h * 0.5} ${x},${y + h}`;
  if (shape === "tri-left") return `${x + w},${y} ${x + w},${y + h} ${x},${y + h * 0.5}`;
  if (shape === "diamond") return `${x + w / 2},${y} ${x + w},${y + h / 2} ${x + w / 2},${y + h} ${x},${y + h / 2}`;
  return null;
}

// channel render state from active map (personality / design / mixed / both / inactive)
function bgChannelState(a, b, src) {
  const G = src || ACTIVE_GATES;
  const ga = G[a], gb = G[b];
  if (!ga || !gb) return "inactive";
  const aOn = ga.p || ga.d, bOn = gb.p || gb.d;
  if (!aOn || !bOn) return "inactive";
  if (ga.p && ga.d && gb.p && gb.d) return "both";
  if (ga.p && gb.p && !(ga.d && gb.d)) return "personality";
  if (ga.d && gb.d && !(ga.p && gb.p)) return "design";
  return "mixed";
}

function bgChannelStroke(state) {
  if (state === "personality") return BG_COL.personality;
  if (state === "design") return BG_COL.design;
  if (state === "mixed" || state === "both") return "url(#bg-mixed-stroke)";
  return null;
}

// ─── Main component ──────────────────────────────────────────
window.InteractiveBodygraph = function InteractiveBodygraph(props) {
  const {
    lang = "ar",
    width = 360,
    height = 568,
    showGateNumbers = true,
    popups = true,
    selectable = true,
    educational = false,
    annotated = false,
    onCenterHover,
    onSelect,
    selection = null,
  } = props;

  const [hover, setHover] = useStateBG(null);     // {kind,id}
  const [popup, setPopup] = useStateBG(null);      // {kind,id,px,py}
  const sel = popup ? { kind: popup.kind, id: popup.id } : (selection || hover);
  const ar = lang === "ar";
  const sampleGates = { 64: { p: true }, 47: { p: true }, 61: { d: true }, 5: { d: true }, 15: { d: true } };
  const sampleCenters = new Set(["head", "ajna", "sacral", "g"]);

  const isGateHi = (g) => {
    if (!sel) return false;
    if (sel.kind === "gate") return sel.id === g;
    if (sel.kind === "channel") { const c = BG_CHANNELS.find((x) => `${x[0]}-${x[1]}` === sel.id); return c && (c[0] === g || c[1] === g); }
    if (sel.kind === "center") return BG_GATE_CENTER[g] === sel.id;
    return false;
  };
  const isCenterHi = (cid) => BG_GATES.some((g) => g.c === cid && isGateHi(g.g));
  const hoverPart = (kind, id) => {
    setHover(kind ? { kind, id } : null);
    onCenterHover?.(kind === "center" ? id : kind === "gate" ? BG_GATE_CENTER[id] : null);
  };

  function openPopup(kind, id, e) {
    if (educational) return;
    if (!popups) { onSelect && onSelect({ kind, id }); return; }
    // place popup at click point, in viewBox coordinate %
    const svg = e.currentTarget.ownerSVGElement || e.currentTarget.closest("svg");
    const r = svg.getBoundingClientRect();
    const px = ((e.clientX - r.left) / r.width) * 100;
    const py = ((e.clientY - r.top) / r.height) * 100;
    setPopup({ kind, id, px, py });
    onSelect && onSelect({ kind, id });
  }

  // navigate to a full detail page (used by popup CTAs)
  function goDetail(path) { window.location.hash = `#/${path}`; setPopup(null); }

  // build popup content
  let popupNode = null;
  if (popup) {
    const onLeft = popup.px > 52;
    const vAlign = popup.py > 62 ? "bottom" : "top";
    const style = {
      [onLeft ? "right" : "left"]: `${onLeft ? 100 - popup.px : popup.px}%`,
      [vAlign]: `${vAlign === "bottom" ? 100 - popup.py : popup.py}%`,
    };
    if (popup.kind === "gate") {
      const g = popup.id;
      const cid = BG_GATE_CENTER[g];
      const cinfo = (ar ? CENTER_INFO : CENTER_INFO_EN)[cid] || {};
      const db = (window.GATE_DB && GATE_DB[g]) || {};
      const name = ar ? (db.name_ar || GATE_NAMES[g]) : (db.name || GATE_NAMES_EN[g] || "");
      const theme = ar ? (db.theme_ar || GATE_THEMES[g] || "") : (db.theme || "");
      const a = ACTIVE_GATES[g] || {};
      const isOn = a.p || a.d;
      popupNode = (
        <div className={`bg-pop ${vAlign}`} style={style} onClick={(e) => e.stopPropagation()}>
          <div className="bg-pop-head">
            <span className={`bg-pop-num${isOn ? "" : " off"}`}>{g}</span>
            <div className="bg-pop-titles">
              <strong>{ar ? "البوابة" : "Gate"} {g} · {name}</strong>
              <span>{cinfo.name}{db.circuit ? ` · ${window.circuitLabel(db.circuit, ar ? "ar" : "en").split(" / ")[0]}` : ""}</span>
            </div>
            <div className="bg-pop-tones">
              {a.p && <i className="tone-p" title={ar ? "وعي" : "Personality"} />}
              {a.d && <i className="tone-d" title={ar ? "لاوعي" : "Design"} />}
              {!isOn && <span className="bg-pop-open">{ar ? "غير مفعّلة" : "Open"}</span>}
            </div>
          </div>
          {theme && <p className="bg-pop-body">{theme}</p>}
          {ar && (db.shadow_ar || db.gift_ar) && (
            <div className="bg-pop-keys">
              {db.shadow_ar && <span className="bg-key shadow"><i></i>{db.shadow_ar}</span>}
              {db.gift_ar && <span className="bg-key gift"><i></i>{db.gift_ar}</span>}
              {db.siddhi_ar && <span className="bg-key siddhi"><i></i>{db.siddhi_ar}</span>}
            </div>
          )}
          <button className="bg-pop-cta" onClick={() => goDetail(`gate/${g}`)}>{ar ? "عرض التفاصيل الكاملة" : "View full details"} <span>{ar ? "←" : "→"}</span></button>
          <button className="bg-pop-close" onClick={() => setPopup(null)} aria-label="close">×</button>
        </div>
      );
    } else if (popup.kind === "channel") {
      const ch = BG_CHANNELS.find((x) => `${x[0]}-${x[1]}` === popup.id);
      const [a, b, , label] = ch;
      const ca = (ar ? CENTER_INFO : CENTER_INFO_EN)[BG_GATE_CENTER[a]] || {};
      const cb = (ar ? CENTER_INFO : CENTER_INFO_EN)[BG_GATE_CENTER[b]] || {};
      // channel DB is keyed by ascending "min-max"
      const key1 = `${a}-${b}`, key2 = `${b}-${a}`;
      const cdb = (window.CHANNEL_DB && (CHANNEL_DB[key1] || CHANNEL_DB[key2])) || {};
      const cname = ar ? (cdb.name_ar || `قناة ${label}`) : (cdb.name || `Channel ${a}-${b}`);
      const st = bgChannelState(a, b);
      const stLabel = ar
        ? ({ personality: "وعي", design: "لاوعي", mixed: "مختلط", both: "وعي + لاوعي", inactive: "غير معرّفة" }[st] || "")
        : ({ personality: "Conscious", design: "Unconscious", mixed: "Mixed", both: "Both", inactive: "Open" }[st] || "");
      popupNode = (
        <div className={`bg-pop ${vAlign}`} style={style} onClick={(e) => e.stopPropagation()}>
          <div className="bg-pop-head">
            <span className="bg-pop-num chan">{a}-{b}</span>
            <div className="bg-pop-titles">
              <strong>{cname}</strong>
              <span>{ca.name} ↔ {cb.name}{cdb.circuit ? ` · ${window.circuitLabel(cdb.circuit, ar ? "ar" : "en").split(" / ")[0]}` : ""}</span>
            </div>
          </div>
          <p className="bg-pop-body">
            {ar ? (cdb.desc_ar || "قناة معرّفة تربط بين المركزين وتجعل طاقتهما ثابتة.") : (cdb.desc_en || "A defined channel linking both centers.")}
          </p>
          {stLabel && <div className="bg-pop-keys"><span className={`bg-key side${st === "inactive" ? " open" : ""}`}>{stLabel}</span></div>}
          <button className="bg-pop-cta" onClick={() => goDetail(`channel/${a}-${b}`)}>{ar ? "عرض التفاصيل الكاملة" : "View full details"} <span>{ar ? "←" : "→"}</span></button>
          <button className="bg-pop-close" onClick={() => setPopup(null)} aria-label="close">×</button>
        </div>
      );
    } else if (popup.kind === "center") {
      const cid = popup.id;
      const cinfo = (ar ? CENTER_INFO : CENTER_INFO_EN)[cid] || {};
      const defined = DEFINED_CENTERS.has(cid);
      const gatesIn = BG_GATES.filter((x) => x.c === cid).map((x) => x.g);
      const tone = BG_TONE_SOLID[BG_TONE[cid]] || "#888";
      popupNode = (
        <div className={`bg-pop ${vAlign}`} style={style} onClick={(e) => e.stopPropagation()}>
          <div className="bg-pop-head">
            <span className="bg-pop-num center" style={{ background: tone, color: "#0b0e1c", boxShadow: `0 0 14px ${tone}66` }}>◈</span>
            <div className="bg-pop-titles">
              <strong>{cinfo.name}</strong>
              <span>{defined ? (ar ? "مركز مُعرّف" : "Defined") : (ar ? "مركز مفتوح" : "Open")} · {gatesIn.length} {ar ? "بوابات" : "gates"}</span>
            </div>
            <div className="bg-pop-tones">
              {defined
                ? <i style={{ background: tone, boxShadow: `0 0 7px ${tone}` }} title={ar ? "مُعرّف" : "Defined"} />
                : <span className="bg-pop-open">{ar ? "مفتوح" : "Open"}</span>}
            </div>
          </div>
          {cinfo.summary && <p className="bg-pop-body">{cinfo.summary}</p>}
          {gatesIn.length > 0 && (
            <div className="bg-pop-keys bg-pop-gatekeys">
              {gatesIn.map((gnum) => {
                const on = (ACTIVE_GATES[gnum] || {}).p || (ACTIVE_GATES[gnum] || {}).d;
                return (
                  <button key={gnum} className={`bg-gatechip${on ? " on" : ""}`}
                          onClick={(ev) => { ev.stopPropagation(); setPopup((p) => ({ ...p, kind: "gate", id: gnum })); }}>
                    {gnum}
                  </button>
                );
              })}
            </div>
          )}
          <button className="bg-pop-cta" onClick={() => goDetail(`center/${cid}`)}>{ar ? "عرض تفاصيل المركز" : "View center details"} <span>{ar ? "←" : "→"}</span></button>
          <button className="bg-pop-close" onClick={() => setPopup(null)} aria-label="close">×</button>
        </div>
      );
    }
  }

  return (
    <div className="bg-wrap" onClick={educational ? undefined : () => { setPopup(null); onSelect && onSelect(null); }}>
      <svg
        viewBox={BG_VIEWBOX}
        className="bg-svg"
        preserveAspectRatio="xMidYMid meet"
        role="img"
        aria-label={educational ? (ar ? "مثال تعليمي لخريطة الهيومان ديزاين" : "Sample Human Design bodygraph") : "Human Design bodygraph"}
      >
        <defs>
          <linearGradient id="bg-mixed-stroke" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor={BG_COL.personality} />
            <stop offset="100%" stopColor={BG_COL.design} />
          </linearGradient>
          <linearGradient id="bg-gate-mixed" x1="0" y1="0" x2="1" y2="0">
            <stop offset="50%" stopColor={BG_COL.personality} />
            <stop offset="50%" stopColor={BG_COL.design} />
          </linearGradient>
          <radialGradient id="bg-aura" cx="50%" cy="44%" r="56%">
            <stop offset="0%" stopColor="rgba(133,155,255,0.30)" />
            <stop offset="48%" stopColor="rgba(77,118,255,0.10)" />
            <stop offset="100%" stopColor="rgba(4,8,24,0)" />
          </radialGradient>
          {/* center tone gradients (HD-style) */}
          <linearGradient id="bgc-gold" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#fff9a8"/><stop offset="52%" stopColor="#f4da55"/><stop offset="100%" stopColor="#9b6f25"/></linearGradient>
          <linearGradient id="bgc-green" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#7bf0a1"/><stop offset="52%" stopColor="#259552"/><stop offset="100%" stopColor="#12442c"/></linearGradient>
          <linearGradient id="bgc-bronze" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#d3a56f"/><stop offset="54%" stopColor="#8a6649"/><stop offset="100%" stopColor="#3b2a22"/></linearGradient>
          <linearGradient id="bgc-yellow" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#fff7a8"/><stop offset="55%" stopColor="#e7c642"/><stop offset="100%" stopColor="#865f24"/></linearGradient>
          <linearGradient id="bgc-rose" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#ff8c96"/><stop offset="50%" stopColor="#d3354c"/><stop offset="100%" stopColor="#681b2f"/></linearGradient>
          <linearGradient id="bgc-brown" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#c88d4a"/><stop offset="54%" stopColor="#996437"/><stop offset="100%" stopColor="#4b2d1c"/></linearGradient>
          <linearGradient id="bgc-violet" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#c39aff"/><stop offset="52%" stopColor="#8a4be8"/><stop offset="100%" stopColor="#42205f"/></linearGradient>
          <filter id="bg-glow" x="-60%" y="-60%" width="220%" height="220%">
            <feGaussianBlur stdDeviation="2.4" result="b" /><feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
        </defs>

        <ellipse cx={500} cy={650} rx={430} ry={620} fill="url(#bg-aura)" />
        {annotated && <path d={BG_SILHOUETTE_PATH} fill="rgba(152,114,255,.07)" stroke="rgba(152,114,255,.24)" strokeWidth="2" />}

        {/* ── channels (under centers) ── */}
        <g>
          {BG_CHANNELS.map((ch) => {
            const [a, b, d, label] = ch;
            const id = `${a}-${b}`;
            const state = bgChannelState(a, b, educational ? sampleGates : undefined);
            const active = state !== "inactive";
            const hi = sel && sel.kind === "channel" && sel.id === id;
            const dim = sel && !hi && !(sel.kind === "gate" && (sel.id === a || sel.id === b)) && active && (sel.kind === "channel");
            const stroke = bgChannelStroke(state);
            return (
              <g key={id} style={{ cursor: educational ? "default" : "pointer" }}
                 onClick={educational ? undefined : (e) => { e.stopPropagation(); openPopup("channel", id, e); }}
                 onMouseEnter={() => setHover({ kind: "channel", id })}
                 onMouseLeave={() => setHover(null)}>
                {/* base track (brightens on hover when inactive) */}
                <path d={d} fill="none" stroke={hi && !active ? "rgba(185,200,245,0.5)" : "rgba(175,190,235,0.2)"} strokeWidth={active ? bgk(8) : (hi ? bgk(4.4) : bgk(2.6))} strokeLinecap="round" style={{ transition: "stroke-width .15s, stroke .15s" }} />
                {active && (
                  <>
                    <path d={d} fill="none" stroke={stroke} strokeWidth={hi ? bgk(7.5) : bgk(5.4)} strokeLinecap="round"
                          opacity={dim ? 0.3 : 0.96}
                          style={{ filter: hi ? "drop-shadow(0 0 7px rgba(98,221,255,0.7))" : "drop-shadow(0 0 4px rgba(120,90,255,0.4))", transition: "stroke-width .18s" }} />
                    {/* animated flow dashes */}
                    <path d={d} fill="none" stroke={stroke} strokeWidth={bgk(2)} strokeLinecap="round"
                          opacity="0.9" strokeDasharray={`${bgk(3)} ${bgk(9)}`} className="bg-flow" />
                  </>
                )}
              </g>
            );
          })}
        </g>

        {/* ── centers ── */}
        <g>
          {BG_CENTERS.map((c) => {
            const defined = (educational ? sampleCenters : DEFINED_CENTERS).has(c.id);
            const hi = isCenterHi(c.id);
            const tone = BG_TONE[c.id];
            const fill = annotated ? c.tone + (hi ? "BB" : "55") : defined ? `url(#bgc-${tone})` : "rgba(20,26,48,0.5)";
            const stroke = annotated ? c.tone : hi ? "rgba(98,221,255,0.95)" : defined ? "rgba(255,255,255,0.6)" : "rgba(165,180,230,0.5)";
            const common = {
              fill, stroke,
              strokeWidth: hi ? bgk(2) : defined ? bgk(1.4) : bgk(1.2),
              strokeDasharray: annotated || defined ? undefined : `${bgk(5)} ${bgk(3)}`,
              opacity: defined ? 0.98 : 0.92,
              onClick: educational ? undefined : (e) => { e.stopPropagation(); openPopup("center", c.id, e); },
              onMouseEnter: () => hoverPart("center", c.id),
              onMouseLeave: () => hoverPart(null),
              style: { cursor: educational ? "default" : "pointer", filter: hi ? "drop-shadow(0 0 6px rgba(98,221,255,0.55))" : defined ? "drop-shadow(0 0 5px rgba(255,255,255,0.12))" : "none", transition: "opacity .2s, stroke-width .2s" },
            };
            return c.shape === "square"
              ? <rect key={c.id} x={c.x} y={c.y} width={c.w} height={c.h} rx={bgk(9)} {...common} />
              : <polygon key={c.id} points={bgShapePoints(c)} {...common} />;
          })}
        </g>

        {/* ── gates ── */}
        <g>
          {BG_GATES.map((gg) => {
            const side = educational ? (sampleGates[gg.g]?.p ? "personality" : sampleGates[gg.g]?.d ? "design" : "off") : gateSide(gg.g);
            const active = side !== "off";
            const hi = isGateHi(gg.g);
            const fill = !active ? "rgba(18,22,40,0.9)"
              : side === "personality" ? BG_COL.personality
              : side === "design" ? BG_COL.design
              : "url(#bg-gate-mixed)";
            const r = hi ? bgk(8.4) : active ? bgk(7.2) : bgk(5.2);
            const txtFill = active ? "#06121f" : "rgba(220,224,245,0.5)";
            return (
              <g key={gg.g} style={{ cursor: educational ? "default" : "pointer" }}
                 onClick={educational ? undefined : (e) => { e.stopPropagation(); openPopup("gate", gg.g, e); }}
                 onMouseEnter={() => hoverPart("gate", gg.g)}
                 onMouseLeave={() => hoverPart(null)}>
                {active && <circle cx={gg.x} cy={gg.y} r={r + bgk(3.5)} fill={side === "design" ? BG_COL.design : BG_COL.personality} opacity={hi ? 0.5 : 0.3} style={{ filter: "blur(2.5px)" }} />}
                <circle cx={gg.x} cy={gg.y} r={r} fill={fill}
                        stroke={active ? "rgba(255,255,255,0.85)" : "rgba(150,160,210,0.34)"} strokeWidth={active ? bgk(0.8) : bgk(0.7)} />
                {showGateNumbers && (
                  <text x={gg.x} y={gg.y} textAnchor="middle" dominantBaseline="central"
                        fontSize={active ? bgk(7.6) : bgk(6.6)} fontWeight="800" fontFamily="Space Grotesk, monospace"
                        fill={txtFill} style={{ pointerEvents: "none", userSelect: "none" }}>{gg.g}</text>
                )}
              </g>
            );
          })}
        </g>
      </svg>
      {popupNode}
    </div>
  );
};

// ─── A small static decorative bodygraph for cards ──────────
// Reads the live active chart by default; pass `gates` (an ACTIVE_GATES-shaped
// map) and `defined` (a Set of center ids) to render a specific chart instead.
window.MiniBodygraph = function MiniBodygraph({ width = 92, height = 132, gates = null, defined = null }) {
  const G = gates || ACTIVE_GATES;
  const D = defined || DEFINED_CENTERS;
  return (
    <svg viewBox={BG_VIEWBOX} width={width} height={height} preserveAspectRatio="xMidYMid meet">
      {BG_CHANNELS.map(([a, b, d]) => {
        const st = bgChannelState(a, b, G);
        const on = st !== "inactive";
        return <path key={`${a}-${b}`} d={d}
          stroke={on ? (st === "design" ? BG_COL.design : st === "personality" ? BG_COL.personality : "#9D8BFF") : "rgba(255,255,255,0.06)"}
          strokeWidth={on ? bgk(2.8) : bgk(0.8)} strokeLinecap="round" fill="none" opacity={on ? 0.9 : 0.5} />;
      })}
      {BG_CENTERS.map((c) => {
        const def = D.has(c.id);
        const fill = def ? BG_TONE_SOLID[BG_TONE[c.id]] : "rgba(255,255,255,0.05)";
        const stroke = def ? "rgba(255,255,255,0.5)" : "rgba(255,255,255,0.15)";
        return c.shape === "square"
          ? <rect key={c.id} x={c.x} y={c.y} width={c.w} height={c.h} rx={bgk(4)} fill={fill} stroke={stroke} strokeWidth={bgk(1)} opacity={def ? 0.9 : 0.55} />
          : <polygon key={c.id} points={bgShapePoints(c)} fill={fill} stroke={stroke} strokeWidth="1" opacity={def ? 0.9 : 0.55} />;
      })}
    </svg>
  );
};
