/* eslint-disable */
/* =============================================================
   GatesPage (جيناتك) — fully data-driven, pixel-built to ref
   -----
   Sources (all from the Spade HD knowledge DB):
     GATE_DB[g]   → name_ar, theme_ar, gift_ar (في اتزانك),
                    shadow_ar (خارج اتزانك), siddhi_ar, center, circuit, desc_ar
     LINE_DB[l]   → name_ar, desc_ar  (معنى الخط)
     PLANET_DB    → planet meaning; CHART_* → which planet/line activates the gate
     CENTER_DB    → center name for the badge
   "في اتزانك / خارج اتزانك" prose + reflection questions are COMPOSED
   from those real fields (gift/shadow/theme/line/side) in Arabic.
   ============================================================= */
(function () {
  const { useState, useMemo } = React;

  /* Resolve a possibly-toned field ({ simple, masri, pro }) to a string.
     REFLECTION_DB questions and GATE_DB.desc carry registers now; passing
     one of those objects straight into JSX throws React error #31 and
     blanks the whole page — it has happened repeatedly in this project. */
  const tp = (f) =>
    typeof f === "string" ? f
      : !f ? ""
      : (window.SpadeTone ? SpadeTone.pick(f) : (f.simple || f.pro || ""));

  const SIDE = { personality: { ar: "وعي", en: "Conscious", color: "#62DDFF" }, design: { ar: "لاوعي", en: "Design", color: "#C084FF" } };
  const centerIdFromName = (n) => {
    if (!n) return "g";
    const s = n.toLowerCase();
    if (s.includes("head")) return "head"; if (s.includes("ajna")) return "ajna";
    if (s.includes("throat")) return "throat"; if (s.includes("solar")) return "solar_plexus";
    if (s.includes("sacral")) return "sacral"; if (s.includes("spleen")) return "spleen";
    if (s.includes("root")) return "root"; if (s.includes("heart") || s.includes("ego") || s.includes("will")) return "ego";
    return "g";
  };

  /* Fill {placeholders} in an already tone-resolved template. The copy
     lives in content.js as STRINGS — resolveTone passes functions through
     unresolved, which silently pins one register for every reader. */
  const fmt = (tplStr, vars) =>
    String(tplStr == null ? "" : tplStr).replace(/\{(\w+)\}/g, (_, k) => (vars[k] != null ? vars[k] : ""));

  /* Keyword terms (gift/shadow/theme) stay constant across registers —
     they are product terminology, not phrasing (§1.1). Only the prose
     around them shifts. */
  const gsv = (db, ar) => ({
    gift: ar ? db.gift_ar : db.gift,
    shadow: ar ? db.shadow_ar : db.shadow,
    theme: ar ? db.theme_ar : db.theme,
  });

  // ── composed prose from DB keywords — works in both AR and EN ──
  function inBalanceText(db, ar, C) {
    const v = gsv(db, ar);
    return { body: fmt(C.in_body, v), example: fmt(C.in_example, v) };
  }
  function outBalanceText(db, ar, C) {
    const v = gsv(db, ar);
    return { body: fmt(C.off_body, v), example: fmt(C.off_example, v) };
  }
  function reflectionQuestions(db, line, side, ar, gateNum, C) {
    // Prefer authored, per-gate reflections from content-db; fall back
    // to the composed version for gates not yet authored.
    const RD = (window.REFLECTION_DB && window.REFLECTION_DB.gates) || {};
    const authored = RD[gateNum];
    if (authored) {
      const qs = ar ? authored.questions_ar : authored.questions_en;
      if (qs && qs.length) return qs;
    }
    const ln = (window.LINE_DB && LINE_DB[line]) || {};
    const lineName = ar ? ln.name_ar : ln.name;
    const v = Object.assign(gsv(db, ar), {
      line: line,
      lineName: lineName,
      side: side === "personality" ? C.q_side_p : C.q_side_d,
    });
    return [
      fmt(C.q1, v),
      fmt(C.q2, v),
      lineName ? fmt(C.q3, v) : fmt(C.q3_alt, v),
    ];
  }
  // how this line specifically colours THIS gate
  function lineMeaning(db, line, ar, C) {
    const ln = (window.LINE_DB && LINE_DB[line]) || {};
    const lineName = ar ? ln.name_ar : ln.name;
    if (!lineName) return "";
    const gateName = ar ? db.name_ar : db.name;
    return fmt(C.line_note, Object.assign(gsv(db, ar), {
      line: line,
      lineName: lineName,
      lineDesc: tp(ar ? ln.desc_ar : ln.desc_en) || "",
      gateName: gateName ? `«${gateName}»` : "",
    }));
  }

  window.GatesPage = function GatesPage({ lang, onRoute }) {
    const L = I18N[lang].gates;
    const ar = lang === "ar";
    const [filter, setFilter] = useState("all");
    const [search, setSearch] = useState("");
    const [showAll, setShowAll] = useState(false);

    // one entry per planetary activation (gate + line + planet + side)
    const activations = useMemo(() => {
      const arr = [];
      (window.CHART_PERSONALITY || []).forEach((r) => arr.push({ g: r.g, l: r.l, planet: r, side: "personality" }));
      (window.CHART_DESIGN || []).forEach((r) => arr.push({ g: r.g, l: r.l, planet: r, side: "design" }));
      return arr;
    }, []);

    const [sel, setSel] = useState(() => activations[0] || { g: 9, l: 5, side: "personality", planet: { ar: "الشمس", glyph: "☉" } });

    const filtered = activations.filter((it) => {
      if (filter === "p" && it.side !== "personality") return false;
      if (filter === "d" && it.side !== "design") return false;
      if (search) {
        const db = (window.GATE_DB && GATE_DB[it.g]) || {};
        const hay = `${it.g}.${it.l} ${db.name_ar || ""} ${it.planet.ar || ""}`.toLowerCase();
        if (!hay.includes(search.toLowerCase())) return false;
      }
      return true;
    });
    const shown = showAll ? filtered : filtered.slice(0, 12);

    const db = (window.GATE_DB && GATE_DB[sel.g]) || {};
    const cid = centerIdFromName(db.center);
    const centerName = ((ar ? CENTER_DB : CENTER_DB)[cid] || {})[ar ? "name_ar" : "name"] || "";
    const sideMeta = SIDE[sel.side];
    const lineDb = (window.LINE_DB && LINE_DB[sel.l]) || {};
    const C = L.composed || {};
    const inB = inBalanceText(db, ar, C); const outB = outBalanceText(db, ar, C);
    const refs = reflectionQuestions(db, sel.l, sel.side, ar, sel.g, C);

    return (
      <div className="page page-gates">
        <PageHeader title={L.title} sub={L.sub} lang={lang} />

        <div className="gates-toolbar" data-galaxy-ui>
          <div className="gates-filters">
            <button className={`tab-pill cyan ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>{ar ? "الكل" : "All"}</button>
            <button className={`tab-pill cyan ${filter === "p" ? "active" : ""}`} onClick={() => setFilter("p")}>{ar ? "الوعي" : "Conscious"}</button>
            <button className={`tab-pill violet ${filter === "d" ? "active" : ""}`} onClick={() => setFilter("d")}>{ar ? "اللاوعي" : "Design"}</button>
          </div>
          <div className="gates-count-pill">{filtered.length} {ar ? "تفعيل" : "activations"}</div>
          <HelpButton lang={lang} route="gates_def" label={ar ? "ما البوابة؟" : "What is a gate?"} />
        </div>

        <div className="gates-grid">
          {/* ── list ── */}
          <div className="gates-list-card" data-galaxy-ui>
            <div className="gates-search">
              <Icon.search size={14} />
              <input type="text" placeholder={ar ? "ابحث عن بوابة أو كوكب…" : "Search gate or planet…"} value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <div className="gates-tiles">
              {shown.map((it, i) => {
                const gdb = (window.GATE_DB && GATE_DB[it.g]) || {};
                const active = sel.g === it.g && sel.l === it.l && sel.side === it.side;
                const col = SIDE[it.side].color;
                return (
                  <button key={i} className={`gate-tile ${active ? "is-active" : ""}`} onClick={() => setSel(it)} style={{ "--gt-color": col }} data-galaxy-ui>
                    <span className="gt-side" style={{ color: col, borderColor: col + "55", background: col + "12" }}>{SIDE[it.side][ar ? "ar" : "en"]}</span>
                    <span className="gt-num">{it.g}.{it.l}</span>
                    <span className="gt-planet"><span style={{ color: col }}>{it.planet.glyph}</span> {ar ? it.planet.ar : it.planet.en}</span>
                    <span className="gt-kw">{ar ? gdb.name_ar : gdb.name}</span>
                  </button>
                );
              })}
            </div>
            {!showAll && filtered.length > 12 && (
              <button className="see-more" onClick={() => setShowAll(true)}>{ar ? "عرض المزيد" : "Show more"} ({filtered.length - 12})</button>
            )}
          </div>

          {/* ── detail ── */}
          <div className="gate-detail" data-galaxy-ui>
            <div className="gd-header">
              <span className="gd-side" style={{ color: sideMeta.color, borderColor: sideMeta.color + "66", background: sideMeta.color + "14" }}>{sideMeta[ar ? "ar" : "en"]}</span>
              <span className="gd-center"><Icon.centers size={12} /> {centerName}</span>
              <button className="gd-fulllink" onClick={() => onRoute && onRoute(`gate/${sel.g}`)}>{ar ? "صفحة البوابة الكاملة" : "Full gate page"} <span>{ar ? "←" : "→"}</span></button>
            </div>
            <div className="gd-title-row">
              <div className="gd-titleblock">
                <h2 className="gd-title">{ar ? "البوابة" : "Gate"} <b>{sel.g}.{sel.l}</b></h2>
                <p className="gd-sub">{ar ? db.name_ar : db.name}</p>
                <div className="gd-meta">
                  <span className="gd-line-chip">{ar ? "الخط" : "Line"} {sel.l} — {ar ? lineDb.name_ar : lineDb.name}</span>
                  <span className="gd-planet-chip"><span style={{ color: sideMeta.color }}>{sel.planet.glyph}</span> {ar ? sel.planet.ar : sel.planet.en}</span>
                </div>
              </div>
              <div className="gd-figure">
                <DnaMark size={64} active={true} />
              </div>
            </div>

            <p className="gd-body">{tp(ar ? db.desc_ar : db.desc_en)}</p>

            <div className="gd-balance">
              <div className="gd-bal-card green">
                <div className="gbc-h"><Icon.leaf size={14} /> {ar ? "في اتزانك" : "In balance"} — <b>{ar ? db.gift_ar : db.gift}</b></div>
                <p>{inB.body}</p>
                <p className="ex"><strong>{ar ? "مثال:" : "Example:"}</strong> {inB.example}</p>
              </div>
              <div className="gd-bal-card red">
                <div className="gbc-h"><Icon.flash size={14} /> {ar ? "خارج اتزانك" : "Out of balance"} — <b>{ar ? db.shadow_ar : db.shadow}</b></div>
                <p>{outB.body}</p>
                <p className="ex"><strong>{ar ? "مثال:" : "Example:"}</strong> {outB.example}</p>
              </div>
            </div>

            <div className="gd-line gd-line-purple gd-line-full">
              <div className="gbc-h" style={{ color: "#C084FF" }}><Icon.starOutline size={15} /> {ar ? `معنى الخط ${sel.l} مع هذه البوابة` : `Line ${sel.l} in this gate`}</div>
              <p>{lineMeaning(db, sel.l, ar, C)}</p>
            </div>

            <div className="gd-line gd-line-cyan gd-line-full">
              <div className="gbc-h" style={{ color: "#62DDFF" }}><Icon.help size={15} /> {ar ? "أسئلة للتأمل" : "Reflection"}</div>
              <ul className="gd-reflect">
                {refs.map((q, i) => <li key={i}>{tp(q)}</li>)}
              </ul>
            </div>

            <div className="gd-tags">
              <span className="gtg-label">{ar ? "وسوم مرتبطة:" : "Tags:"}</span>
              {(ar ? [db.theme_ar, db.gift_ar, db.shadow_ar, db.siddhi_ar] : [db.theme, db.gift, db.shadow, db.siddhi]).filter(Boolean).map((tg, i) => <span key={i} className="tag-chip">{tg}</span>)}
            </div>
          </div>
        </div>
      </div>
    );
  };
})();
