// Vertical milestone timeline — the centerpiece

const { useRef: useRefTL, useState: useStateTL, useEffect: useEffectTL } = React;

function MilestoneCard({ m, idx, status, raised }) {
  const isLeft = idx % 2 === 0;
  const rowRef = useRefTL(null);
  const [shown, setShown] = useStateTL(false);
  useEffectTL(() => {
    if (!rowRef.current) return;
    const el = rowRef.current;
    const check = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight * 0.9) { setShown(true); return true; }
      return false;
    };
    if (check()) return;
    const obs = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting) { setShown(true); obs.disconnect(); } });
    }, { threshold: 0.05, rootMargin: "0px 0px -10% 0px" });
    obs.observe(el);
    // Fallback: show after 200ms regardless
    const t = setTimeout(() => setShown(true), 400);
    return () => { obs.disconnect(); clearTimeout(t); };
  }, []);
  const animStyle = {
    opacity: shown ? 1 : 0,
    transform: shown ? "translateY(0)" : "translateY(24px)",
    transition: "opacity 800ms cubic-bezier(.2,.7,.2,1), transform 800ms cubic-bezier(.2,.7,.2,1)",
  };
  const statusLabel = {
    complete: { text: "Completed", color: "var(--moss-600)", dot: "var(--moss-500)" },
    progress: { text: "In Progress", color: "var(--gold-500)", dot: "var(--gold-500)" },
    locked:   { text: "Upcoming",   color: "rgba(47,51,29,0.5)", dot: "rgba(47,51,29,0.3)" },
  }[status];

  // compute progress within this phase
  let phasePct = 0;
  if (m.cumulative != null) {
    const prev = MILESTONES[idx - 1];
    const prevCum = prev ? prev.cumulative : 0;
    phasePct = Math.max(0, Math.min(1, (raised - prevCum) / (m.cumulative - prevCum)));
  }

  return (
    <div ref={rowRef} className="milestone-row" style={{
      display: "grid",
      gridTemplateColumns: "1fr 64px 1fr",
      alignItems: "start",
      gap: 0,
      marginBottom: 72,
      position: "relative",
    }}>
      {/* Left cell */}
      <div style={{ gridColumn: isLeft ? "1" : "3", gridRow: 1, paddingRight: isLeft ? 48 : 0, paddingLeft: isLeft ? 0 : 48, ...animStyle }} className={isLeft ? "align-right" : "align-left"}>
        <div className="milestone-card" style={{ padding: "32px 34px", position: "relative" }}>
          {/* corner phase number */}
          <div style={{ position: "absolute", top: 24, right: 28, fontFamily: "var(--serif)", fontSize: 56, lineHeight: 1, color: "rgba(181,168,107,0.25)", fontStyle: "italic" }}>
            {m.n}
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
            <div style={{ width: 44, height: 44, borderRadius: 2, border: "1px solid rgba(181,168,107,0.4)", display: "grid", placeItems: "center", color: "var(--gold-500)" }}>
              <Glyph name={m.icon} size={24} />
            </div>
            <span className="pill" style={{ color: statusLabel.color, background: status === "progress" ? "rgba(181,168,107,0.08)" : "transparent" }}>
              <span className="dot" style={{ background: statusLabel.dot }} />
              {statusLabel.text}
            </span>
          </div>

          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.25em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)" }}>
            Phase {m.n}
          </div>
          <h3 style={{ fontSize: 32, marginTop: 6, marginBottom: 10, color: "var(--navy-900)" }}>
            {m.title}
          </h3>

          <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 14 }}>
            <span style={{ fontFamily: "var(--serif)", fontSize: 26, color: "var(--navy-800)" }}>
              {m.goalLabel || formatMoney(m.goal, { compact: true })}
            </span>
            <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)" }}>
              {m.cumulative != null ? `to ${formatMoney(m.cumulative, { compact: true })} total` : "naming partnership"}
            </span>
          </div>

          <p style={{ fontSize: 14.5, lineHeight: 1.65, color: "rgba(47,51,29,0.75)", margin: 0 }}>
            {m.blurb}
          </p>

          <ul style={{ listStyle: "none", padding: 0, margin: "18px 0 0", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "6px 16px" }}>
            {m.bullets.map((b, i) => (
              <li key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "rgba(47,51,29,0.7)" }}>
                <span style={{ width: 4, height: 4, background: status === "complete" ? "var(--moss-500)" : "var(--gold-500)", borderRadius: "50%", flexShrink: 0 }} />
                {b}
              </li>
            ))}
          </ul>

          {/* within-phase progress */}
          {m.cumulative != null && (
            <div style={{ marginTop: 20, paddingTop: 18, borderTop: "1px dashed rgba(47,51,29,0.12)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)" }}>
                <span>Phase progress</span>
                <span>{(phasePct * 100).toFixed(0)}%</span>
              </div>
              <div style={{ height: 3, background: "rgba(47,51,29,0.08)", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ height: "100%", width: (phasePct * 100) + "%", background: status === "complete" ? "var(--moss-500)" : "linear-gradient(90deg, var(--gold-500), var(--gold-300))", transition: "width 900ms" }} />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Center node */}
      <div style={{ gridColumn: "2", gridRow: 1, position: "relative", minHeight: 80 }}>
        <div className={"spine-node " + status} style={{ top: 40 }} />
      </div>

      {/* Opposite-side meta */}
      <div style={{ gridColumn: isLeft ? "3" : "1", gridRow: 1, paddingLeft: isLeft ? 48 : 0, paddingRight: isLeft ? 0 : 48, paddingTop: 48, ...animStyle }} className={isLeft ? "align-left" : "align-right"}>
        <div style={{ textAlign: isLeft ? "left" : "right" }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.25em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)" }}>
            Chapter {String(idx + 1).padStart(2, "0")}
          </div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 110, lineHeight: 0.9, fontStyle: "italic", color: "rgba(47,51,29,0.08)", marginTop: 4 }}>
            {m.n}
          </div>
          {status === "progress" && (
            <div style={{ marginTop: 8, fontFamily: "var(--serif)", fontSize: 20, fontStyle: "italic", color: "var(--gold-500)" }}>
              We are here.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Timeline({ raised }) {
  const ref = useRefTL(null);
  const [fillPct, setFillPct] = useStateTL(0);

  // Spine fill tracks how many milestones have progress-or-complete based on raised
  useEffectTL(() => {
    const reached = MILESTONES.reduce((acc, m, i) => {
      const s = statusFor(m, raised);
      if (s === "complete") return i + 1;
      if (s === "progress") {
        const prev = MILESTONES[i - 1];
        const prevCum = prev ? prev.cumulative : 0;
        const p = m.cumulative ? (raised - prevCum) / (m.cumulative - prevCum) : 0;
        return i + Math.max(0, Math.min(1, p));
      }
      return acc;
    }, 0);
    setFillPct(Math.max(0, Math.min(1, reached / MILESTONES.length)) * 100);
  }, [raised]);

  return (
    <section id="journey" className="paper" style={{ padding: "140px 0 100px", position: "relative" }}>
      <div className="container">
        <div style={{ textAlign: "center", marginBottom: 80 }}>
          <div className="rule" style={{ justifyContent: "center", maxWidth: 320, margin: "0 auto 28px" }}>The Journey · Eight Phases</div>
          <h2 style={{ fontSize: "clamp(42px, 5vw, 68px)", letterSpacing: "-0.015em" }}>
            From a single seed<br/>
            <em style={{ fontWeight: 400, color: "var(--moss-600)" }}>to a full academy.</em>
          </h2>
          <p style={{ marginTop: 22, fontSize: 16, maxWidth: 560, margin: "22px auto 0", lineHeight: 1.65, color: "rgba(47,51,29,0.68)" }}>
            Each chapter of New Eden unlocks when the community gives together. Follow the line — see where we are, and where we're going.
          </p>
        </div>

        <div ref={ref} style={{ position: "relative", maxWidth: 1160, margin: "0 auto" }}>
          {/* spine */}
          <div className="spine">
            <div className="spine-fill" style={{ height: fillPct + "%" }} />
          </div>

          {/* Starting node */}
          <div style={{ position: "relative", textAlign: "center", marginBottom: 48 }}>
            <div style={{ marginBottom: 32, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.28em", textTransform: "uppercase", color: "var(--gold-500)" }}>Today · {formatMoney(raised, { compact: true })} raised</div>
            <div className="spine-node complete" style={{ position: "relative", margin: "0 auto" }} />
          </div>

          {MILESTONES.map((m, i) => (
            <MilestoneCard key={m.n} m={m} idx={i} status={statusFor(m, raised)} raised={raised} />
          ))}

          {/* End node */}
          <div style={{ position: "relative", textAlign: "center", marginTop: 24 }}>
            <div className="spine-node" style={{ position: "relative", margin: "0 auto", borderColor: "var(--gold-500)", background: "var(--cream-50)" }}>
              <span style={{ position: "absolute", inset: 3, borderRadius: "50%", background: "var(--gold-500)", display: "block" }} />
            </div>
            <div style={{ marginTop: 18, fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 24, color: "var(--navy-800)" }}>
              The vision, complete.
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 860px) {
          .milestone-row {
            grid-template-columns: 56px 1fr !important;
          }
          .milestone-row > div:first-child, .milestone-row > div:last-child {
            grid-column: 2 !important;
            grid-row: auto !important;
            padding: 0 0 0 24px !important;
            text-align: left !important;
          }
          .milestone-row > div:nth-child(2) { grid-column: 1 !important; }
          .milestone-row > div:last-child { padding-top: 8px !important; display: none; }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { Timeline });
