// JourneyGuide — the "How This Works" guide.
// Three variants (blessings practice / about the book / why this way),
// paginated, with a "Don't show again" on the last page. Auto-opens once
// per variant on first visit; a small opener button is always available.

const JG_PAGES = {
  blessings: [
    { body: "The Twelve Blessings are meant to become part of your daily rhythm. As you move forward in your journey, begin speaking the blessings each day and keeping count as you go. You may choose to follow them in the order of the book, moving through each blessing as designed, or you may speak all twelve in one sitting. The goal is not perfection, but steady practice — returning daily to the truths of God, letting them shape your thoughts, your heart, and your walk of faith." },
    { body: "After reciting the blessings, spend time reflecting on what God may be showing you. The inspiration prompts throughout the site are there to help guide your thoughts, deepen your contemplation, and draw you into prayerful reflection. From there, use the journal to record what is stirring in your heart — type directly, or speak and transcribe. This gives you the freedom to reflect in the way that feels most natural and meaningful to you." },
    { body: "As your journey grows, you may also choose to share your reflections with others in the Tribe through the Community. There, you can post insights from your journal, receive encouragement and perspective from others, and take part in a shared walk of spiritual growth. The journey is personal, but it is not meant to be walked alone." },
    { body: "You will also find a Daily Reading section designed to help you move through Scripture at a pace that fits your life. Whether you want to move slowly and reflect deeply or follow a more structured pace through the Bible, this section encourages steady reading, reflection, and growth in God's Word alongside your daily recitation of the blessings." },
  ],
  book: [
    { title: "This Book Is About Becoming", body: "The Twelve Blessings is a story and a practice about ordinary people facing real loss, hardship, frustration, fear, and uncertainty — and learning to move through it with God. It shows lives being reshaped not by escape from trouble, but by continual commitment to Him. Through that commitment, the soul is slowly strengthened in stability, release, service, praise, wisdom, joy, adversity, gratitude, rest, generosity, forgiveness, and courage." },
    { title: "It Turns the Heart From Asking to Offering", body: "Too often, we ask for things without giving. The same can be true in how we come before God. But that is not Christ's path. Christ teaches the way of offering, service, sacrifice, and love. This book turns the heart away from a faith centered only on receiving, and back toward a faith that asks what can be given to God through the way we live. The blessings become repeated acts of surrender — daily words that train the heart to say, not only \u201chelp me,\u201d but also \u201cshape me, use me, send me.\u201d" },
    { title: "Repetition Is How the Truth Takes Root", body: "The book's rhythm is deliberate: speak each blessing aloud twelve times each day, reflect on it, journal it, and live with it until it begins to work its way into the mind, the will, and the heart. Over time, repetition stops being mere recitation and becomes formation. Stability steadies the shaken life. Release loosens anger and bitterness. Service turns outward. Praise lifts perspective. Wisdom clarifies. Joy breathes again." },
    { title: "It Calls You to More Than Passive Faith", body: "This book is not meant to create passive followers who only admire holy things from a distance. It is meant to help form people of depth, endurance, compassion, and holy resolve. The characters move through their troubles by continually returning themselves to God, and the reader is invited to do the same. The call is not merely to believe, but to be changed — to become someone who can endure, serve, love, forgive, stand, and carry light into the lives of others." },
  ],
  why: [
    { body: "Too often, we ask for things without giving in return. We seek blessing, help, comfort, provision, and direction, yet offer little of ourselves back. The same can be true in our relationship with God. We come with requests, needs, and burdens, but Christ shows us a different path. His way is not centered on taking, but on offering. Not on being ministered to, but on ministering." },
    { body: "The Twelve Blessings help turn the heart back in that direction. They are not merely words to be repeated, but declarations of love, loyalty, and willingness. They train the soul to approach God not only with open hands, but with an open life — to say, \u201cUse me. Shape me. Teach me. Send me.\u201d" },
    { body: "Jesus Himself taught this pattern and lived it fully. He came not to be served, but to serve. His life was poured out in obedience, sacrifice, strength, and love. To follow Him is not simply to admire Him, but to let His life become the model for our own — to become people who are willing to give, to serve, to endure, and to be formed according to the will of God." },
    { body: "This is where repetition becomes powerful. What we return to daily begins to shape us. What we speak consistently with sincerity begins to work its way into the mind, the heart, and the will. Repetition is not empty when it is filled with meaning. It is one of the ways the soul is trained." },
    { body: "There is a psychological and spiritual beauty in this process. Repeated truth slowly becomes inward structure. The words we speak challenge our instincts, soften pride, strengthen resolve, and help align us with God's intentions. What begins as deliberate practice can become transformation. In this way, the blessings are not only remembered — they begin to live within us." },
    { body: "The goal is not passive belief. The goal is formation. Christ does not call people merely to stand near Him in name while remaining unchanged. He calls them into courage, discipline, sacrifice, love, and action. He calls souls willing to be refined into instruments of His purpose." },
    { body: "The Twelve Blessings are a daily act of remembrance and re-commitment. They help train the heart to love God more fully, the mind to dwell on higher things, and the will to answer His call with greater strength. They become more than a ritual; they become a path — a path by which a person is slowly shaped into someone more faithful, more steadfast, more purposeful, and more alive to the work of God." },
  ],
};

const JG_TITLES = { blessings: "How the practice works", book: "About the Book", why: "Why this way?" };

function JourneyGuideModal({ variant = "blessings", onClose }) {
  const [v, setV] = useState(variant);
  const [page, setPage] = useState(0);
  const [prevV, setPrevV] = useState(null);
  const [dismiss, setDismiss] = useState(false);
  const pages = JG_PAGES[v] || [];
  const last = page >= pages.length - 1;
  const cur = pages[page] || {};

  const close = () => {
    if (dismiss) { try { localStorage.setItem(`tt:journeyGuideDismissed:${variant}`, "1"); } catch {} }
    onClose();
  };

  return (
    <div onClick={close} style={{ position: "fixed", inset: 0, zIndex: 95, background: "rgba(10,9,7,0.82)", backdropFilter: "blur(8px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ position: "relative", width: "min(640px, 100%)", maxHeight: "88vh", overflowY: "auto", background: T.bgRise, border: `1px solid ${T.gold}44`, padding: "36px 36px 28px" }}>
        <button onClick={close} aria-label="Close" style={{ position: "absolute", top: 16, right: 16, width: 36, height: 36, background: "transparent", border: `1px solid ${T.gold}33`, color: T.gold, cursor: "pointer" }}>✕</button>
        <SmallCaps color={T.gold} letterSpacing="0.32em">{JG_TITLES[v]}</SmallCaps>
        {cur.title && (
          <h2 style={{ fontFamily: "'Cinzel', serif", fontSize: 26, fontWeight: 500, margin: "16px 0 0", color: T.paper, letterSpacing: "0.02em" }}>{cur.title}</h2>
        )}
        <p style={{ marginTop: 16, fontFamily: "'Cormorant Garamond', serif", fontSize: 19, lineHeight: 1.7, color: T.paper }}>{cur.body}</p>

        {/* Page dots */}
        <div style={{ marginTop: 20, display: "flex", gap: 6, justifyContent: "center" }}>
          {pages.map((_, i) => (
            <div key={i} onClick={() => setPage(i)} style={{ width: 8, height: 8, borderRadius: "50%", background: i === page ? T.gold : T.ash, cursor: "pointer" }} />
          ))}
        </div>

        {/* Don't show again on last page */}
        {last && (
          <label style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 8, justifyContent: "center", cursor: "pointer" }}>
            <input type="checkbox" checked={dismiss} onChange={(e) => setDismiss(e.target.checked)} />
            <span style={{ fontSize: 13, color: T.paperDim, fontFamily: "'Cormorant Garamond', serif", fontStyle: "italic" }}>Don't show this again</span>
          </label>
        )}

        {/* Controls */}
        <div style={{ marginTop: 22, display: "flex", gap: 10, justifyContent: "space-between", flexWrap: "wrap" }}>
          <button onClick={() => {
              if (prevV) { setV(prevV); setPrevV(null); setPage(0); }
              else if (page > 0) setPage(page - 1);
            }}
            style={{ padding: "11px 18px", background: "transparent", color: T.paperDim, border: `1px solid ${T.gold}33`, cursor: (prevV || page > 0) ? "pointer" : "default", opacity: (prevV || page > 0) ? 1 : 0.4, fontFamily: "'Cinzel', serif", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase" }}>
            ← Back
          </button>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {/* Cross-variant links on the blessings/book guides */}
            {v !== "why" && last && (
              <button onClick={() => { setPrevV(v); setV("why"); setPage(0); }}
                style={{ padding: "11px 18px", background: "transparent", color: T.gold, border: `1px solid ${T.gold}55`, cursor: "pointer", fontFamily: "'Cinzel', serif", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase" }}>
                Why This Way?
              </button>
            )}
            {!last ? (
              <button onClick={() => setPage(page + 1)}
                style={{ padding: "11px 22px", background: T.gold, color: T.ink, border: "none", cursor: "pointer", fontFamily: "'Cinzel', serif", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", fontWeight: 600 }}>
                Next →
              </button>
            ) : (
              <button onClick={close}
                style={{ padding: "11px 22px", background: T.gold, color: T.ink, border: "none", cursor: "pointer", fontFamily: "'Cinzel', serif", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", fontWeight: 600 }}>
                Let's Get Started
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Small opener button + auto-open-once logic. Drop <JourneyGuide variant="blessings" />
// at the top of a page; it shows a "How does this work?" pill and auto-opens once.
function JourneyGuide({ variant = "blessings" }) {
  const [open, setOpen] = useState(false);
  useEffect(() => {
    let dismissed = false;
    try { dismissed = localStorage.getItem(`tt:journeyGuideDismissed:${variant}`) === "1"; } catch {}
    if (!dismissed) setOpen(true);
  }, [variant]);
  return (
    <>
      <button onClick={() => setOpen(true)} style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 14px", background: "transparent", color: T.gold, border: `1px solid ${T.gold}44`, cursor: "pointer", fontFamily: "'Cinzel', serif", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase" }}>
        ⓘ How does this work?
      </button>
      {open && <JourneyGuideModal variant={variant} onClose={() => setOpen(false)} />}
    </>
  );
}

Object.assign(window, { JourneyGuideModal, JourneyGuide });
