/* =============================================================
   CompassPage.jsx — "بوصلة اليوم" / Daily Compass
   -----
   Personal daily guidance from the active chart + LIVE planetary
   transit (computed by HDEngine for the current moment).
   Mirrors reference page-mockup "بوصلة اليوم".
   Browser build: classic <script type="text/babel">; window.CompassPage
   ============================================================= */
(function () {
  const { useState, useMemo } = React;

  // ── type-keyed daily copy (calm, brand voice) ──
  const BY_TYPE = {
    Projector: {
      ar: { signal_t: "ثق بإشارتك الأولى، والطاقة تستجيب.",
        signal_b: "يدعوك يومك إلى الهدوء والمراقبة، انتظر الاعتراف والدعوة المناسبة، واصغِ لإحساسك الجسدي الأول، فهو مرشدك الأصدق اليوم.",
        signal_hint: "إحساس جسدي مفاجئ أو تنبيه داخلي سريع",
        inb: ["تراقب قبل أن تتدخل.", "تنتظر الاعتراف أو الدعوة المناسبة.", "تثق بإشارتك الجسدية الأولى.", "تحافظ على طاقتك وتختار بوعي أين توجّهها."],
        outb: ["تحاول إثبات قيمتك أو السعي للاعتراف.", "تقدّم نصيحة غير مطلوبة.", "تتجاهل إحساسك الأول.", "تُفرغ طاقتك للآخرين وتستنزف نفسك."] },
      en: { signal_t: "Trust your first signal — the energy responds.",
        signal_b: "Today invites stillness and watching. Wait for recognition and the right invitation, and listen to your first bodily sense — it is your truest guide today.",
        signal_hint: "A sudden bodily sense or quick inner cue",
        inb: ["You observe before stepping in.", "You wait for recognition or the right invitation.", "You trust your first bodily signal.", "You guard your energy and choose where to aim it."],
        outb: ["You try to prove your worth or chase recognition.", "You give unrequested advice.", "You ignore your first sense.", "You pour energy into others and drain yourself."] },
    },
    Generator: {
      ar: { signal_t: "استجب لما يضيء طاقتك، ودَع الباقي يمر.",
        signal_b: "اليوم يطلب منك أن تنتظر ما يستحق استجابتك. عندما يستجيب جسدك بحماس، اتبعه؛ وعندما يخمد، توقّف. رضاك هو بوصلتك.",
        signal_hint: "حماس جسدي صادق أو انجذاب فوري",
        inb: ["تنتظر ما يستدعي استجابتك.", "تتبع ما يضيء طاقتك بحماس.", "تنهي ما بدأته بإتقان.", "تستمع لصوت جسدك قبل عقلك."],
        outb: ["تبدأ أشياء بلا استجابة حقيقية.", "تقول نعم من باب المجاملة.", "تتجاهل إشارات الإرهاق.", "تندفع لمجرّد الحركة."] },
      en: { signal_t: "Respond to what lights your energy; let the rest pass.",
        signal_b: "Today asks you to wait for what deserves your response. When your body lights up, follow it; when it dims, pause. Satisfaction is your compass.",
        signal_hint: "Honest bodily enthusiasm or instant pull",
        inb: ["You wait for what calls a response.", "You follow what lights you up.", "You finish what you start, well.", "You listen to your body before your mind."],
        outb: ["You start things with no real response.", "You say yes out of courtesy.", "You ignore signs of burnout.", "You rush just to be in motion."] },
    },
    "Manifesting Generator": {
      ar: { signal_t: "استجب، ثم تحرّك بسرعتك الخاصة.",
        signal_b: "طاقتك سريعة ومتعددة المسارات. انتظر الاستجابة، وأعلِم من حولك بخطوتك التالية، ولا تخف من تخطّي الخطوات التي لا تخدمك.",
        signal_hint: "حماس فوري متبوع بوضوح الاتجاه",
        inb: ["تستجيب أولاً ثم تتحرك.", "تُعلِم من يتأثر بخطوتك.", "تتبع شغفك المتعدد بلا ذنب.", "تتخطّى ما لا يخدم اتجاهك."],
        outb: ["تقفز دون استجابة.", "تنسى إعلام المحيط.", "تجبر نفسك على مسار واحد.", "تترك أشياء ناقصة باستمرار."] },
      en: { signal_t: "Respond, then move at your own speed.",
        signal_b: "Your energy is fast and multi-track. Wait for the response, inform those around you of your next step, and don't fear skipping what doesn't serve you.",
        signal_hint: "Instant enthusiasm followed by clear direction",
        inb: ["You respond first, then move.", "You inform whoever your step affects.", "You follow your many passions, guilt-free.", "You skip what doesn't serve your direction."],
        outb: ["You leap without a response.", "You forget to inform others.", "You force a single track.", "You constantly leave things unfinished."] },
    },
    Manifestor: {
      ar: { signal_t: "بادر بما يدفعك من الداخل، وأعلِم قبل أن تتحرّك.",
        signal_b: "اليوم لطاقتك المبادِرة. اتبع دفعتك الداخلية، وأعلِم من سيتأثر بقرارك قبل الفعل، لتجد سلامك وحريّتك في آنٍ معًا.",
        signal_hint: "دفعة داخلية واضحة للبدء",
        inb: ["تتبع دفعتك الداخلية للبدء.", "تُعلِم من يتأثر قبل أن تتحرك.", "تحمي استقلاليتك بهدوء.", "تبادر دون انتظار إذن."],
        outb: ["تنتظر إذنًا لا تحتاجه.", "تتحرك دون إعلام فتثير المقاومة.", "تكبت دفعتك للبدء.", "تتفاعل بغضب بدل المبادرة."] },
      en: { signal_t: "Initiate what moves you within — inform before you act.",
        signal_b: "Today is for your initiating energy. Follow your inner urge, inform those your decision affects before acting, and find peace and freedom at once.",
        signal_hint: "A clear inner urge to begin",
        inb: ["You follow your urge to begin.", "You inform those affected before moving.", "You quietly protect your autonomy.", "You initiate without waiting for permission."],
        outb: ["You wait for permission you don't need.", "You move without informing and stir resistance.", "You suppress your urge to start.", "You react with anger instead of initiating."] },
    },
    Reflector: {
      ar: { signal_t: "امنح نفسك وقتًا — وضوحك يأتي مع القمر.",
        signal_b: "أنت مرآة لمحيطك. لا تتعجّل القرارات الكبيرة اليوم؛ راقب كيف تتغيّر طاقتك مع الأماكن والناس، ودع الوضوح ينضج عبر دورة قمرية كاملة.",
        signal_hint: "تغيّر ملحوظ في إحساسك مع المكان",
        inb: ["تمنح القرارات الكبيرة وقتها.", "تنتبه لأثر المكان والناس عليك.", "تتحدث مع من تثق بهم قبل الحسم.", "تحتفي بدهشتك مما تعكسه."],
        outb: ["تتسرّع في قرار مصيري.", "تتماهى مع طاقة لا تخصّك.", "تحكم على يومك بمعيار ثابت.", "تتجاهل حاجتك لبيئة سليمة."] },
      en: { signal_t: "Give yourself time — clarity arrives with the moon.",
        signal_b: "You mirror your surroundings. Don't rush big decisions today; notice how your energy shifts with places and people, and let clarity ripen over a full lunar cycle.",
        signal_hint: "A noticeable shift in how a place feels",
        inb: ["You give big decisions their time.", "You notice how places and people affect you.", "You talk to trusted people before deciding.", "You delight in the surprise of what you reflect."],
        outb: ["You rush a fateful decision.", "You merge with energy that isn't yours.", "You judge your day by a fixed standard.", "You ignore your need for a healthy environment."] },
    },
  };

  function typeKey() {
    const en = (window.CHART_SUMMARY && CHART_SUMMARY.type_en) || "Projector";
    return BY_TYPE[en] ? en : "Projector";
  }

  // deterministic 0..100 "harmony" from date + type (stable within a day)
  function harmonyFor(d, salt) {
    const s = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${salt}`;
    let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
    return 72 + (h % 27); // 72–98
  }

  // daily streak via localStorage
  function streakInfo() {
    try {
      const today = new Date(); today.setHours(0, 0, 0, 0);
      const raw = JSON.parse(localStorage.getItem("sle.compass") || "{}");
      const last = raw.last ? new Date(raw.last) : null;
      let streak = raw.streak || 0;
      if (!last) streak = 1;
      else {
        const diff = Math.round((today - last) / 86400000);
        if (diff === 0) streak = streak || 1;
        else if (diff === 1) streak += 1;
        else streak = 1;
      }
      localStorage.setItem("sle.compass", JSON.stringify({ last: today.toISOString(), streak }));
      return streak;
    } catch (e) { return 1; }
  }

  const MSG = {
    ar: ["أين أحاول أن أرى دون أن أكون مدعوًا؟ وما الإشارة التي أتجاهلها اليوم؟",
      "ما الذي يضيء طاقتي حقًا حين أصغي لجسدي لا لعقلي؟",
      "متى كانت آخر مرة وثقت فيها بإحساسي الأول دون تبرير؟"],
    en: ["Where am I trying to see without being invited? And which signal am I ignoring today?",
      "What truly lights my energy when I listen to my body, not my mind?",
      "When did I last trust my first sense without justifying it?"],
  };

  const HANDLE = (ar) => ([
    { ic: "compass", t: ar ? "في العمل" : "At work", b: ar ? "ركّز على التحليل والرؤية، لا تبدأ شيئًا جديدًا دون وضوح أو دعوة." : "Focus on insight, not starting anything new without clarity or an invitation." },
    { ic: "heart", t: ar ? "في العلاقات" : "In relationships", b: ar ? "اسمح للعلاقة أن تأتي إليك، لا تطارد، ولا تفسّر، فقط لاحظ." : "Let connection come to you. Don't chase or over-explain — just notice." },
    { ic: "sun", t: ar ? "في طاقتك" : "Your energy", b: ar ? "خذ فترات راحة قصيرة، احمِ طاقتك من الضوضاء والمهام الزائدة." : "Take short breaks; protect your energy from noise and extra tasks." },
    { ic: "eye", t: ar ? "في وضوحك" : "Your clarity", b: ar ? "اسأل جسدك قبل القرار، أول إحساس غالبًا يكون الأصدق." : "Ask your body before deciding — the first sense is usually truest." },
  ]);

  const DEEP = (ar) => ([
    ar ? "أفضل أوقات اتخاذ القرار" : "Best decision windows",
    ar ? "نقطة الانتباه اليوم" : "Today's focus point",
    ar ? "نافذة الانسجام" : "Harmony window",
    ar ? "نافذة الضغط" : "Pressure window",
    ar ? "طاقة التفاعل" : "Interaction energy",
  ]);

  window.CompassPage = function CompassPage({ lang, onRoute }) {
    const ar = lang === "ar";
    const tk = typeKey();
    const C = BY_TYPE[tk][lang] || BY_TYPE[tk].ar;
    const S = window.CHART_SUMMARY || {};
    const now = new Date();

    const harmony = harmonyFor(now, tk);
    const streak = useMemo(() => streakInfo(), []);
    const msg = MSG[lang][(now.getDate()) % MSG[lang].length];

    const transit = useMemo(() => {
      if (window.HDEngine && HDEngine.ready()) return HDEngine.transit(now, ["sun", "moon", "mercury"]);
      return [];
    }, []);
    const sunT = transit.find((t) => t.p === "sun") || {};
    const TDB = (window.TRANSIT_DB || {})[sunT.g] || {};
    const tp = (f) => (window.SpadeTone ? window.SpadeTone.pick(f) : (typeof f === "string" ? f : (f && (f.simple || f.pro)) || ""));
    const transitText = tp(ar ? (TDB.transit_ar || TDB.transit_theme_ar) : (TDB.transit_en || TDB.transit_theme_en));
    const transitDesc = {
      sun: transitText || (ar ? "وضوح مفاجئ يساعدك على رؤية ما يستحق طاقتك." : "A sudden clarity helps you see what deserves your energy."),
      moon: ar ? "حدسك قوي اليوم، انتبه لإشاراتك الجسدية." : "Your intuition is strong today — heed your bodily cues.",
      mercury: ar ? "أفكار وتنظيم أفضل، لكن شاركها فقط عند الدعوة." : "Clearer ideas — but share them only when invited.",
    };

    const dateLabel = now.toLocaleDateString(ar ? "ar-EG" : "en-GB", { weekday: "long", day: "numeric", month: "long" });
    const profileLine = `${ar ? S.type_ar : S.type_en} • ${ar ? S.authority_en : S.authority_en} • ${S.profile || ""}`;

    return (
      <>
        <PageHeader title={ar ? "بوصلة اليوم" : "Daily Compass"} sub={ar ? "إشاراتك الشخصية ليومك بناءً على خريطتك وعبور الكواكب الحالية." : "Your personal signals for today, based on your chart and the current planetary transit."} lang={lang} />
        <div className="cp-wrap">
          {/* date eyebrow */}
          <div className="cp-date"><span className="cp-eyebrow">{ar ? "اليوم" : "Today"}</span><span>— {dateLabel}</span></div>

          {/* row 1: hero + transit */}
          <div className="cp-row cp-row-hero">
            <section className="cp-hero card-glass">
              <div className="cp-hero-badges">
                <span className="cp-badge cp-badge-accent">{ar ? "توجّه اليوم" : "Today's direction"}</span>
                <span className="cp-badge">{`${ar ? S.type_ar : S.type_en} • ${ar ? S.authority_ar : S.authority_en} • ${S.profile}`}</span>
              </div>
              <h2 className="cp-hero-title">{C.signal_t}</h2>
              <p className="cp-hero-body">{C.signal_b}</p>
              {transitText && (
                <div className="cp-guidance">
                  <Icon.sun size={14} />
                  <span><b>{ar ? `عبور البوابة ${sunT.g}` : `Gate ${sunT.g} transit`} — </b>{transitText}</span>
                </div>
              )}
              <div className="cp-hero-stats">
                <div className="cp-stat"><span className="cp-stat-ic"><Icon.heart size={16} /></span><div><strong>{ar ? "إشارتك اليوم" : "Your signal today"}</strong><em>{C.signal_hint}</em></div></div>
                <div className="cp-stat cp-stat-harmony"><span className="cp-stat-ic"><Icon.heart size={16} /></span><div><strong>{ar ? "درجة الانسجام" : "Harmony"}</strong><b className="cp-harmony">{harmony}%</b></div></div>
              </div>
            </section>

            <aside className="cp-transit card-glass">
              <div className="cp-card-head"><h3>{ar ? "عبور اليوم" : "Today's transit"}</h3><span className="cp-head-ic"><Icon.planets size={18} /></span></div>
              <div className="cp-transit-list">
                {transit.map((tr) => (
                  <div className="cp-transit-row" key={tr.p}>
                    <span className="cp-planet-badge">{tr.glyph}</span>
                    <div className="cp-transit-text">
                      <strong>{(ar ? tr.ar : tr.en)} {ar ? "في البوابة" : "in gate"} <b>{tr.g}.{tr.l}</b></strong>
                      <em>{transitDesc[tr.p] || ""}</em>
                    </div>
                  </div>
                ))}
                {transit.length === 0 && <p className="cp-empty">{ar ? "جارٍ حساب العبور…" : "Computing transit…"}</p>}
                {(TDB.collective_mood_ar || TDB.collective_mood_en) && (
                  <p className="cp-collective">{tp(ar ? TDB.collective_mood_ar : TDB.collective_mood_en)}</p>
                )}
              </div>
            </aside>
          </div>

          {/* row 2: balance + handle */}
          <div className="cp-row cp-row-3">
            <section className="cp-balance cp-in card-glass">
              <div className="cp-card-head"><h3>{ar ? "في اتزانك اليوم" : "In balance today"}</h3><span className="cp-head-ic cp-green"><Icon.leaf size={18} /></span></div>
              <ul className="cp-list cp-list-in">{C.inb.map((x, i) => <li key={i}><span className="cp-mark cp-ok"><Icon.check size={12} /></span>{x}</li>)}</ul>
            </section>
            <section className="cp-balance cp-out card-glass">
              <div className="cp-card-head"><h3>{ar ? "خارج اتزانك اليوم" : "Out of balance today"}</h3><span className="cp-head-ic cp-red"><Icon.flash size={18} /></span></div>
              <ul className="cp-list cp-list-out">{C.outb.map((x, i) => <li key={i}><span className="cp-mark cp-no">✕</span>{x}</li>)}</ul>
            </section>
            <section className="cp-handle card-glass">
              <div className="cp-card-head"><h3>{ar ? "كيف تتعامل مع يومك؟" : "How to handle your day"}</h3></div>
              <div className="cp-handle-grid">
                {HANDLE(ar).map((h, i) => {
                  const I = Icon[h.ic] || Icon.compass;
                  return <div className="cp-handle-card" key={i}><span className="cp-handle-ic"><I size={18} /></span><strong>{h.t}</strong><p>{h.b}</p></div>;
                })}
              </div>
            </section>
          </div>

          {/* row 3: streak + message + tomorrow */}
          <div className="cp-row cp-row-3b">
            <section className="cp-streak card-glass">
              <div className="cp-card-head"><h3>{ar ? "سجل حضورك اليومي" : "Daily presence"}</h3><span className="cp-head-ic cp-gold"><Icon.star size={16} /></span></div>
              <div className="cp-streak-body">
                <div className="cp-ring" style={{ "--p": `${Math.min(streak, 7) / 7 * 360}deg` }}><div className="cp-ring-in"><b>{streak}</b><span>{ar ? "أيام متتالية" : "day streak"}</span></div></div>
                <div className="cp-streak-text">
                  <strong>{ar ? "أنت على المسار الصحيح!" : "You're on the right track!"}</strong>
                  <p>{ar ? "استمر في حضورك اليومي لتعميق وعيك وزيادة انسجامك." : "Keep showing up daily to deepen awareness and harmony."}</p>
                  <span className="cp-pill-pt">+1 {ar ? "نقطة اليوم" : "point today"}</span>
                </div>
              </div>
            </section>
            <section className="cp-message card-glass">
              <div className="cp-card-head"><h3>{ar ? "رسالة اليوم" : "Message of the day"}</h3><span className="cp-head-ic"><Icon.help size={16} /></span></div>
              <p className="cp-quote">“{msg}”</p>
            </section>
          </div>

          {/* The locked "tomorrow's compass" card and the paywalled
              "deeper details" section were removed with the paid tier.
              Neither had content behind it — they were teasers for a
              purchase that no longer exists. */}
        </div>
      </>
    );
  };
})();
