/* eslint-disable */
/* =============================================================
   ComparePage — Spade's Life Explained UI Kit
   -----
   Browser build: classic <script type="text/babel">; attaches window.ComparePage.
   Reads globals: I18N, Icon, PageHeader, Btn, MiniBodygraph, CHART_SUMMARY,
   ChartStore, HDEngine, BG_CHANNELS, channelShort (ComparePersonCard is local)
   -----
   "Other" person is chosen via the picker: any saved chart from ChartStore,
   or the built-in sample "Sarah" — computed with the real engine so her
   bodygraph, table values and connection channels are all genuine.
   Next.js port: lift the component into its own module —
     export default function ComparePage({ lang, onRoute }) { … }
   — and replace the window globals above with real imports.
   ============================================================= */
(function () {
  const { useState, useMemo, useEffect } = React;

  // ── Sample "Sarah" — computed once with the real engine ─────
  function sampleRecord() {
    if (window.__SLE_SAMPLE_OTHER !== undefined) return window.__SLE_SAMPLE_OTHER;
    try {
      const chart = HDEngine.computeChart({
        name: "سارة", year: 1990, month: 8, day: 7, hour: 8, minute: 5,
        tzOffsetMinutes: 180, lat: 21.4925, lng: 39.1776,
        placeAr: "جدة، السعودية", placeEn: "Jeddah, Saudi Arabia",
      });
      window.__SLE_SAMPLE_OTHER = { id: "__sample", name: "سارة", chart, sample: true };
    } catch (e) { window.__SLE_SAMPLE_OTHER = null; }
    return window.__SLE_SAMPLE_OTHER;
  }

  function fmtBirth(meta) {
    if (!meta || !meta.birth_iso) return { date: "", time: "" };
    const local = new Date(new Date(meta.birth_iso).getTime() + (meta.tzOffsetMinutes || 0) * 60000);
    const pad = (n) => String(n).padStart(2, "0");
    return {
      date: `${local.getUTCFullYear()}/${pad(local.getUTCMonth() + 1)}/${pad(local.getUTCDate())}`,
      time: meta.unknownTime ? "—" : `${pad(local.getUTCHours())}:${pad(local.getUTCMinutes())}`,
    };
  }

  // chart record → display person (incl. gates/defined for the mini bodygraph)
  function personFromChart(c, lang, fallbackName) {
    const ar = lang === "ar";
    const bt = fmtBirth(c.meta);
    const name = c.meta.name || fallbackName || "—";
    return {
      name, avatar: name.trim().charAt(0),
      date: bt.date, time: bt.time,
      place: ar ? (c.meta.placeAr || c.meta.placeEn) : (c.meta.placeEn || c.meta.placeAr),
      type: ar ? c.type_ar : c.type_en,
      strategy: ar ? c.strategy_ar : c.strategy_en,
      authority: ar ? c.authority_ar : c.authority_en,
      profile: c.profile,
      definition: ar ? c.definition_ar : c.definition_en,
      cross: c.cross_codes || "",
      signature: ar ? c.signature_ar : c.signature_en,
      not_self: ar ? c.not_self_ar : c.not_self_en,
      gates: c.activeGates, defined: new Set(c.definedCenters),
    };
  }

  // ════════════════════════════════════════════════════════════
  //   COMPARE
  // ════════════════════════════════════════════════════════════
  window.ComparePage = function ComparePage({ lang, onRoute }) {
    const L = I18N[lang].compare;
    const ar = lang === "ar";

    // refresh when charts change (create / rename / delete / active switch)
    const [tick, setTick] = useState(0);
    useEffect(() => window.ChartStore.subscribe(() => setTick((t) => t + 1)), []);

    const sample = sampleRecord();
    const saved = useMemo(
      () => window.ChartStore.listCharts().filter((r) => r.id !== window.ChartStore.activeId()),
      [tick]
    );

    const [otherId, setOtherId] = useState("__sample");
    const otherRec = (otherId !== "__sample" && (saved.find((r) => r.id === otherId) || null)) || sample;
    const isSample = !otherRec || otherRec.id === "__sample";

    // "me" — the live active chart (globals are kept in sync by ChartStore)
    const me = useMemo(() => {
      const S = CHART_SUMMARY;
      return {
        name: ar ? S.name_ar : S.name_en,
        avatar: ((ar ? S.name_ar : S.name_en) || S.name_ar || "").trim().charAt(0),
        date: S.birth_date, time: S.birth_time, place: ar ? S.birth_place_ar : S.birth_place_en,
        type: ar ? S.type_ar : S.type_en, strategy: ar ? S.strategy_ar : S.strategy_en,
        authority: ar ? S.authority_ar : S.authority_en, profile: S.profile,
        definition: ar ? S.definition_ar : S.definition_en, cross: S.cross_codes || "(9/16 | 64/63)",
        signature: ar ? S.signature_ar : S.signature_en, not_self: ar ? S.not_self_ar : S.not_self_en,
        gates: window.ACTIVE_GATES, defined: window.DEFINED_CENTERS,
      };
    }, [lang, tick]);

    const other = otherRec ? personFromChart(otherRec.chart, lang, otherRec.name) : null;

    // Curated notes for the sample pairing; neutral computed notes otherwise.
    const sampleNotes = {
      type:       ar ? "تكامل جميل، أنت توجّه وسارة تستجيب." : "Beautiful complementarity — you guide, Sarah responds.",
      strategy:   ar ? "تفاعلكم يساعدكما على الدخول في الاستجابة." : "Your dynamic helps you both enter into response.",
      authority:  ar ? "توازن متين بين حكمة الغريزة والحس العاطفي." : "Solid balance between gut wisdom and emotional sensitivity.",
      profile:    ar ? "أنت تبحث عن الحلول، وسارة تبني العلاقات." : "You search for solutions; Sarah builds relationships.",
      definition: ar ? "تعريفك المنفصل يستفيد من تعريفها الموحد." : "Your split benefits from her unified definition.",
      cross:      ar ? "كلاكما يحمل طاقة التأثير وإرشاد الآخرين." : "Both of you carry the energy to influence and guide others.",
      signature:  ar ? "النجاح والرضا يكملان بعضكما البعض." : "Success and satisfaction complete each other.",
    };
    const noteFor = (k, a, b) => (isSample ? sampleNotes[k] : (a === b ? L.note_same : L.note_diff));

    const aspectRows = other
      ? ["type", "strategy", "authority", "profile", "definition", "cross", "signature"].map((k) => ({
          k, me: me[k], o: other[k], note: noteFor(k, me[k], other[k]),
        }))
      : [];

    // Electromagnetic connection channels: complete across the pair,
    // incomplete within each person alone.
    const connChannels = useMemo(() => {
      if (!other) return [];
      const list = [];
      (window.BG_CHANNELS || []).forEach(([a, b]) => {
        const mA = !!me.gates[a], mB = !!me.gates[b];
        const oA = !!other.gates[a], oB = !!other.gates[b];
        if ((mA || oA) && (mB || oB) && !(mA && mB) && !(oA && oB)) list.push([a, b]);
      });
      return list;
    }, [me, otherRec, lang]);

    // ── content-db: the four connection states + per-channel themes ──
    const STATE_COLORS = { electromagnetic: "#FF78B5", companionship: "#5FD6B5", dominance: "#F8C648", compromise: "#A28DFE" };
    const dyn = useMemo(() => {
      const DB = window.COMPARE_DB;
      if (!other || !DB || !DB.states) return [];
      const out = [];
      (window.BG_CHANNELS || []).forEach(([a, b]) => {
        const mA = !!me.gates[a], mB = !!me.gates[b], oA = !!other.gates[a], oB = !!other.gates[b];
        const meFull = mA && mB, oFull = oA && oB;
        let state = null;
        if (meFull && oFull) state = "companionship";
        else if (meFull && !oA && !oB) state = "dominance";
        else if (oFull && !mA && !mB) state = "dominance";
        else if (meFull || oFull) state = "compromise";
        else if ((mA && oB && !mB && !oA) || (mB && oA && !mA && !oB)) state = "electromagnetic";
        if (!state) return;
        const key = `${a}-${b}`, alt = `${b}-${a}`;
        const ch = DB.channels[key] || DB.channels[alt] || {};
        const cdb = (window.CHANNEL_DB || {})[key] || (window.CHANNEL_DB || {})[alt] || {};
        const st = DB.states[state];
        out.push({
          key, state, color: STATE_COLORS[state],
          stateName: ar ? st.name_ar : st.name_en,
          stateDesc: ar ? st.desc_ar : st.desc_en,
          theme: ar ? ch.relationship_theme_ar : ch.relationship_theme_en,
          chName: (ar ? cdb.name_ar : cdb.name) || key,
        });
      });
      // electromagnetic first (the interesting ones), then by state
      const rank = { electromagnetic: 0, dominance: 1, compromise: 2, companionship: 3 };
      return out.sort((x, y) => rank[x.state] - rank[y.state]);
    }, [me, otherRec, lang]);

    /* القراءة المولَّدة من الخريطتين. حلّت محلّ فقرات «سارة» الثابتة
       التي كانت تُعرَض كما هي أيًّا كان الطرف المختار.

       السجلّ في التبعيّات عمدًا: بنك العبارات مُنبَّر، وبدونه يبقى
       الناتج محفوظًا من السجلّ السابق فلا تتغيّر الفقرات عند تبديل
       النبرة — وهو ما حدث فعلًا قبل إضافته. */
    const [tone, setTone] = useState(window.SpadeTone ? SpadeTone.get() : "simple");
    useEffect(() => {
      const onTone = () => setTone(window.SpadeTone ? SpadeTone.get() : "simple");
      window.addEventListener("hd-tone-change", onTone);
      return () => window.removeEventListener("hd-tone-change", onTone);
    }, []);
    const syn = useMemo(
      () => (window.CompareSynthesis ? CompareSynthesis.build(me, other, lang) : null),
      [me, otherRec, lang, tick, tone]
    );

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

        {/* ── Picker: which chart to compare against ── */}
        <div className="compare-pick" data-galaxy-ui>
          <span className="cpk-label">{L.pick_label}</span>
          <div className="cpk-pills">
            {saved.map((r) => (
              <button key={r.id} className={`cpk-pill ${otherId === r.id ? "is-on" : ""}`} data-galaxy-ui onClick={() => setOtherId(r.id)}>
                {r.name}
              </button>
            ))}
            {sample && (
              <button className={`cpk-pill cpk-sample ${isSample ? "is-on" : ""}`} data-galaxy-ui onClick={() => setOtherId("__sample")}>
                {L.pick_sample}
              </button>
            )}
          </div>
          {saved.length === 0 && <span className="cpk-empty">{L.pick_empty}</span>}
        </div>

        <div className="compare-profiles">
          {other && <ComparePersonCard who={other} role="other" L={L} compared />}
          <ComparePersonCard who={me} role="me" L={L} />
        </div>

        <div className="compare-table" data-galaxy-ui>
          <div className="ct-row ct-head">
            <span>{L.note}</span>
            <span>{L.side_other}</span>
            <span>{L.side_yours}</span>
            <span>{L.aspect}</span>
          </div>
          {aspectRows.map((r, i) => (
            <div key={i} className="ct-row">
              <span className="ct-note"><Icon.check size={14} style={{ color: "#5FD6B5" }} /> {r.note}</span>
              <span data-cl={L.side_other}>{r.o}</span>
              <span data-cl={L.side_yours}>{r.me}</span>
              <span className="ct-asp">{L.labels[r.k] || ""}</span>
            </div>
          ))}
        </div>

        <div className="compare-bottom">
          <div className="cb-card" data-galaxy-ui>
            <h3 className="cb-h">{L.interactions_title}</h3>
            <div className="cb-row3">
              <div className="cb-mini cb-purple">
                <span className="cbm-h"><Icon.bookOpen size={14} /> {L.learning}</span>
                <p>{syn ? syn.learning : ""}</p>
                <em>{L.conflict_cta}</em>
              </div>
              <div className="cb-mini cb-gold">
                <span className="cbm-h"><Icon.flash size={14} /> {L.conflict}</span>
                <p>{syn ? syn.conflict : ""}</p>
                <em>{L.conflict_cta}</em>
              </div>
              <div className="cb-mini cb-green">
                <span className="cbm-h"><Icon.leaf size={14} /> {L.common}</span>
                <p>{syn ? syn.common : ""}</p>
                <em>{L.learning_cta}</em>
              </div>
            </div>
            <div className="cb-channels">
              <strong>{L.channels_title}:</strong>
              {connChannels.length === 0 && <span className="ch-none">{L.channels_none}</span>}
              {connChannels.slice(0, 8).map((c, i) => (
                <span key={i} className="ch-tag">{c[0]} - {c[1]}<em>{window.channelShort(c[0], c[1], lang)}</em></span>
              ))}
            </div>
          </div>
          <div className="cb-card" data-galaxy-ui>
            <h3 className="cb-h">{L.dynamics_title}</h3>
            <div className="cb-dynamic">
              {dyn.length > 0 ? dyn.slice(0, 6).map((d, i) => (
                <div key={d.key} className="cbd-row">
                  <span className="cbd-icon" style={{ color: d.color }}><Icon.flash size={16} /></span>
                  <div className="cbd-text">
                    <strong style={{ color: d.color }}>{d.stateName} · {d.chName} ({d.key})</strong>
                    <span>{d.theme || d.stateDesc}</span>
                  </div>
                </div>
              )) : (
                /* لا حالة قناةٍ واحدة بين الخريطتين. كان هنا ثلاثُ
                   بطاقاتٍ وهمية عن «سارة» تُعرَض بدل الفراغ؛ والفراغ
                   هنا نتيجةٌ صحيحة تُقال لا تُغطّى. */
                <p className="cbd-empty">{L.channels_none}</p>
              )}
            </div>
            <div className="cb-relations">
              {(syn ? syn.relations : []).map((it, i) => (
                <div key={i} className="cbr-row">
                  <span className="cbr-icon" style={{ color: ["#5FD6B5","#F45F5F","#F8C648"][i] }}>{[<Icon.heart size={16} key="r1" />,<Icon.flash size={16} key="r2" />,<Icon.starOutline size={16} key="r3" />][i]}</span>
                  <div className="cbr-text">
                    <strong>{it.t}</strong>
                    <span>{it.body}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="deep-cta deep-compare" data-galaxy-ui>
          <div className="dc-figure"><Icon.crown size={36} /></div>
          <div className="dc-text">
            <h3>{L.deep_title}</h3>
            <p>{L.deep_body}</p>
          </div>
          <div className="dc-actions">
            <Btn kind="outline" onClick={() => onRoute("report")}><Icon.download size={14} /> {L.cta2}</Btn>
          </div>
        </div>
      </div>
    );
  };

  function ComparePersonCard({ who, role, L, compared }) {
    return (
      <div className={`cp-card ${role === "me" ? "cp-me" : "cp-other"}`} data-galaxy-ui>
        <div className="cp-head">
          <h3>{who.name}</h3>
          <div className="cp-avatar"><span>{who.avatar}</span></div>
        </div>
        <div className="cp-body">
          <div className="cp-meta">
            <div><em>{L.birth_date}</em><span>{who.date}</span></div>
            <div><em>{L.birth_time}</em><span>{who.time}</span></div>
            <div><em>{L.birth_place}</em><span>{who.place}</span></div>
          </div>
          <div className="cp-mini-bg">
            <MiniBodygraph width={92} height={132} gates={who.gates} defined={who.defined} />
          </div>
          <div className="cp-summary">
            <span className="cp-tag">{compared ? L.compared : L.yours}</span>
            {[["type","planets"],["strategy","compass"],["authority","heart"],["profile","centers"],["definition","diamond"]].map(([k, ic], i) => {
              const II = Icon[ic];
              return (
                <div key={i} className="cp-srow">
                  <Icon.chevLeft size={12} />
                  <span className="cp-sv">{who[k]}</span>
                  <span className="cp-sl">{L.labels[k] || k}</span>
                  <span className="cp-si"><II size={14} /></span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }
})();
