// Main app — wired to the live backend via window.NE_API.

const { useState: useStateM, useEffect: useEffectM, useRef: useRefM } = React;

function Nav({ onGive }) {
  const loggedIn = NE_API.isLoggedIn();
  const [menuOpen, setMenuOpen] = useStateM(false);
  const close = () => setMenuOpen(false);
  return (
    <nav className={"top" + (menuOpen ? " menu-open" : "")}>
      <a href="/" className="brand" style={{ textDecoration: "none" }}>
        <div className="brand-mark">
          <img src="assets/logo.png" alt="New Eden Academy" />
        </div>
        <div>
          <div className="brand-name">NEW EDEN</div>
          <div className="brand-tag">FAITH · LEARNING · PURPOSE</div>
        </div>
      </a>

      <div className="links">
        <a href="/" className="active" onClick={close}>Home</a>
        <a href="story.html" onClick={close}>Story</a>
        <a href="gallery.html" onClick={close}>Gallery</a>
        <a href="events.html" onClick={close}>Events</a>
        <a href="pledge.html" onClick={close}>Pledge</a>
        <a href="ways-to-give.html" onClick={close}>Ways to Give</a>
        <a href="updates.html" onClick={close}>Updates</a>
        <a href="faq.html" onClick={close}>FAQ</a>
        <a href="account.html" className="account" onClick={close}>{loggedIn ? "Account" : "Sign In"}</a>
      </div>

      <div className="cta">
        <button type="button" className="hamburger" aria-label="Toggle menu" aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}>
          <span></span>
        </button>
        <button onClick={() => { close(); onGive(); }} className="btn-give">Give Now</button>
      </div>
    </nav>
  );
}

function StickyGive({ visible, raised, goal, onGive }) {
  const pct = Math.max(0.5, Math.min(100, goal > 0 ? (raised / goal) * 100 : 0)).toFixed(2);
  return (
    <div className={"sticky-give " + (visible ? "show" : "")}>
      <div className="sticky-give-inner">
        <div className="sticky-give-stats">
          <div className="sticky-give-label">New Eden · Live Total</div>
          <div className="sticky-give-amount">{formatMoney(raised)}</div>
        </div>
        <div className="sticky-give-bar">
          <div className="hbar-track" style={{ height: 4 }}>
            <div className="hbar-fill" style={{ width: pct + "%" }} />
          </div>
        </div>
        <button className="btn btn-gold sticky-give-btn" onClick={onGive}>Give</button>
      </div>
    </div>
  );
}

const PRAYED_KEY = "ne_prayed";
const PRAYER_COUNT_CACHE_KEY = "ne_prayer_count_cache";

function readPrayerCountCache() {
  try {
    var v = parseInt(localStorage.getItem(PRAYER_COUNT_CACHE_KEY) || "0", 10);
    return isNaN(v) || v < 0 ? 0 : v;
  } catch { return 0; }
}
function writePrayerCountCache(n) {
  try { localStorage.setItem(PRAYER_COUNT_CACHE_KEY, String(n)); } catch {}
}

function App() {
  const [raised, setRaised] = useStateM(0);
  const [goal, setGoal] = useStateM(120000000);
  const [prayerCount, setPrayerCountRaw] = useStateM(readPrayerCountCache);
  const setPrayerCount = (next) => {
    setPrayerCountRaw((prev) => {
      var resolved = typeof next === "function" ? next(prev) : next;
      writePrayerCountCache(resolved);
      return resolved;
    });
  };
  const [hasPrayed, setHasPrayed] = useStateM(false);
  const [showSticky, setShowSticky] = useStateM(false);
  const [messages, setMessages] = useStateM([]);
  const [leaderboard, setLeaderboard] = useStateM([]);
  const [monthlySeries, setMonthlySeries] = useStateM([]);
  const [phaseInfo, setPhaseInfo] = useStateM({ phase: "Phase I", phaseNote: "Plant the Seed" });
  const [toast, setToast] = useStateM(null);

  // Bootstrap from backend
  useEffectM(() => {
    refreshAll();
    try { if (localStorage.getItem(PRAYED_KEY) === "1") setHasPrayed(true); } catch {}
  }, []);

  const refreshAll = async () => {
    try {
      const [stats, wall, board] = await Promise.all([
        NE_API.stats(),
        NE_API.encouragements(),
        NE_API.namingAssignments(),
      ]);
      if (stats) {
        setRaised(stats.totalRaisedCents / 100);
        setPrayerCount(stats.prayerCount);
        if (stats.campaign) {
          setGoal(stats.campaign.goalCents / 100);
          setPhaseInfo({ phase: stats.campaign.phase, phaseNote: stats.campaign.phaseNote });
        }
        if (Array.isArray(stats.monthlySeries)) {
          setMonthlySeries(stats.monthlySeries);
        }
      }
      if (Array.isArray(wall)) {
        setMessages(wall.map(m => ({
          name: m.name || "Anonymous",
          text: m.message,
          when: relativeTime(m.createdAt),
        })));
      }
      if (board && Array.isArray(board.entries)) {
        setLeaderboard(board.entries);
      }
    } catch (e) {
      console.error("Failed to load backend stats", e);
    }
  };

  useEffectM(() => {
    const onScroll = () => {
      const passedHero = window.scrollY > window.innerHeight * 0.6;
      const beforeFooter = window.scrollY + window.innerHeight < document.body.scrollHeight - 400;
      setShowSticky(passedHero && beforeFooter);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const flashToast = (text) => {
    setToast(text);
    setTimeout(() => setToast(null), 3000);
  };

  const pray = async () => {
    if (hasPrayed) {
      flashToast("Already praying with us · thank you.");
      return;
    }
    setHasPrayed(true);
    setPrayerCount(c => c + 1);
    try { localStorage.setItem(PRAYED_KEY, "1"); } catch {}
    flashToast("Thank you. You are part of this vision.");
    try {
      const r = await NE_API.recordPrayer();
      if (r && typeof r.total === "number") setPrayerCount(r.total);
    } catch (e) { console.warn("prayer record failed", e); }
  };

  const scrollToGive = () => {
    document.getElementById("give")?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  // give.jsx now owns the donation API call (and optional register/sign-in).
  // This callback only fires after the gift has been recorded — we just confirm + refresh.
  const handleGive = (amount) => {
    flashToast(`Thank you · ${formatMoney(amount)} gift recorded · awaits Stripe confirmation`);
    setTimeout(refreshAll, 500);
  };

  const handleEncouragement = async (m) => {
    setMessages(prev => [{ ...m, pending: true }, ...prev]);
    flashToast("Your encouragement is in review · thank you.");
    try {
      await NE_API.submitEncouragement(m.name === "Anonymous" ? null : m.name, m.text);
    } catch (e) {
      flashToast("Submission failed · " + (e.message || "see console"));
      console.error(e);
    }
  };

  return (
    <>
      <Nav onGive={scrollToGive} />

      <Hero
        raised={raised} goal={goal}
        prayerCount={prayerCount}
        hasPrayed={hasPrayed}
        onPray={pray}
        onGive={scrollToGive}
        monthlySeries={monthlySeries}
      />

      <Timeline raised={raised} />

      <GiveSection raised={raised} onGive={handleGive} />

      <LegacySection raised={raised} leaderboard={leaderboard} />

      <Newsletter />

      <EncouragementWall messages={messages} onSubmit={handleEncouragement} />

      <OtherWaysToHelp />

      <FinalCTA onGive={scrollToGive} onPray={pray} />

      <Footer />

      <StickyGive visible={showSticky} raised={raised} goal={goal} onGive={scrollToGive} />

      <div style={{
        position: "fixed", bottom: showSticky ? 96 : 32, left: "50%", transform: "translateX(-50%)",
        background: "var(--navy-900)", color: "var(--cream-50)",
        padding: "14px 22px", borderRadius: 2,
        border: "1px solid var(--gold-500)",
        fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
        boxShadow: "0 20px 40px rgba(0,0,0,0.35)",
        opacity: toast ? 1 : 0,
        transition: "opacity 280ms, bottom 280ms",
        pointerEvents: "none",
        zIndex: 60,
        maxWidth: "90vw", textAlign: "center",
      }}>
        {toast}
      </div>
    </>
  );
}

function relativeTime(iso) {
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return "just now";
  if (diff < 3600) return Math.round(diff / 60) + " min ago";
  if (diff < 86400) return Math.round(diff / 3600) + " hours ago";
  if (diff < 172800) return "yesterday";
  if (diff < 604800) return Math.round(diff / 86400) + " days ago";
  return Math.round(diff / 604800) + " weeks ago";
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
