// Legacy — Founders' Stone + Benefactors' Leaderboard
// Threshold: $100+ = engraved in stone. Below = digital Founders' Registry.
// Top 10 gifts (by amount) auto-fill the benefactor buildings — leaderboard style.

const STONE_THRESHOLD = 100;    // min gift to be engraved on physical stone
const FOUNDERS_GOAL = 500000;   // cutoff for founders' phase
const TIERS = [
  { min: 100,    max: 999,     label: "Founder",           note: "Engraved on the Founders' Stone" },
  { min: 1000,   max: 9999,    label: "Patron",            note: "Larger type · dedicated stone section" },
  { min: 10000,  max: 99999,   label: "Pillar",            note: "Stone + plaque inside first building" },
  { min: 100000, max: 249999,  label: "Cornerstone",       note: "Stone + room dedication" },
  { min: 250000, max: Infinity,label: "Benefactors' Circle", note: "Building engraving + portrait" },
];

// Seed leaderboard — used if the live donor DB is sparse. Each donor now
// carries a `preferences` list (location ids). Building assignments are
// computed live by window.NE_resolveAssignments, walking top→bottom.
const SEED_LEADERBOARD = [
  { email: "whitfield@example.com", name: "The Whitfield Family",     amount: 2000000, preferences: ["dining-hall","library","chapel","main-school"] },
  { email: "cordero@example.com",   name: "Marcus & Elena Cordero",   amount: 1500000, preferences: ["library","auditorium","chapel","early-learning"] },
  { email: "anon-1@example.com",    name: "Anonymous",                amount: 1000000, preferences: ["chapel","fountain","gardens"] },
  { email: "bright@example.com",    name: "The Bright Foundation",    amount: 750000,  preferences: ["main-school","library","auditorium"] },
  { email: "hollis@example.com",    name: "Patricia & James Hollis",  amount: 500000,  preferences: ["auditorium","chapel","early-learning","library"] },
  { email: "okafor@example.com",    name: "The Okafor Family",        amount: 250000,  preferences: ["early-learning","library","gardens"] },
  { email: "tan@example.com",       name: "Dr. & Mrs. Tan",           amount: 120000,  preferences: ["outdoor-classroom","gardens","sidewalks"] },
  { email: "chen@example.com",      name: "Grace Chen",               amount: 85000,   preferences: ["girls-dorm","library"] },
  { email: "reyes@example.com",     name: "The Reyes Family",         amount: 50000,   preferences: [] },
  { email: "alder@example.com",     name: "J. & E. Alder",            amount: 25000,   preferences: ["front-gate","fountain","pond"] },
];

function LegacySection({ raised, leaderboard }) {
  const foundersPct = Math.min(100, (raised / FOUNDERS_GOAL) * 100);
  const foundersLeft = Math.max(0, FOUNDERS_GOAL - raised);
  const stoneFull = raised >= FOUNDERS_GOAL;

  // Backend already returns top-N donors with their resolved building assignments.
  const ranked = (Array.isArray(leaderboard) ? leaderboard : []).map(d => ({
    name: d.displayName,
    amount: d.lifetimeCents / 100,
    preferences: d.preferences || [],
    assignedName: d.assignedName,
    assignedFrom: d.assignedFrom,
    assignedId: d.assignedId,
  }));

  return (
    <section id="legacy" className="paper" style={{ padding: "140px 0 120px", position: "relative", overflow: "hidden" }}>
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0, pointerEvents: "none", opacity: 0.5,
        backgroundImage: "radial-gradient(circle at 15% 30%, rgba(74,98,64,0.08), transparent 50%), radial-gradient(circle at 85% 70%, rgba(181,168,107,0.1), transparent 50%)",
      }} />

      <div className="container" style={{ position: "relative" }}>
        <div style={{ textAlign: "center", maxWidth: 780, margin: "0 auto 80px" }}>
          <div className="rule" style={{ justifyContent: "center", marginBottom: 22 }}>Legacy · Names in stone</div>
          <h2 style={{ fontSize: "clamp(40px, 5.5vw, 68px)", lineHeight: 1.08 }}>
            Your name, <em style={{ fontWeight: 400, color: "var(--moss-600)" }}>carved</em> into<br/>
            the <em style={{ fontWeight: 400, color: "var(--gold-600, rgb(138,125,77))" }}>story</em> of this place.
          </h2>
          <p style={{ fontSize: 17, lineHeight: 1.7, color: "rgba(47,51,29,0.7)", marginTop: 26, maxWidth: 620, margin: "26px auto 0" }}>
            The first to plant seeds deserve to be remembered. We honor our earliest and most generous supporters with permanent marks upon the grounds — so that decades from now, students walking to class will know the names of those who believed first.
          </p>
        </div>

        {/* FOUNDERS' STONE */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 60, alignItems: "center", marginBottom: 80 }} className="legacy-grid">
          <div style={{ position: "relative" }}>
            <FoundersStoneSVG pct={foundersPct} />
            <div style={{ position: "absolute", bottom: -18, left: "50%", transform: "translateX(-50%)", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.3em", textTransform: "uppercase", color: "rgba(47,51,29,0.45)", whiteSpace: "nowrap" }}>
              — The Founders' Stone · placed on the west quad —
            </div>
          </div>

          <div>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.26em", textTransform: "uppercase", color: "var(--gold-600, rgb(138,125,77))", marginBottom: 14 }}>
              Phase One · The Founders
            </div>
            <h3 style={{ fontSize: "clamp(28px, 3.5vw, 42px)", lineHeight: 1.15 }}>
              Gifts of <em style={{ fontWeight: 400 }}>$100 or more</em><br/>
              are engraved on the stone.
            </h3>
            <p style={{ fontSize: 15, lineHeight: 1.7, color: "rgba(47,51,29,0.7)", marginTop: 18 }}>
              A single granite marker will be set at the entrance to the campus. Every donor who gives <strong>$100 or more before we reach our first $500,000</strong> is carved permanently into the stone. Every gift below $100 is honored in our <a href="#registry" style={{ color: "var(--moss-600)", textDecoration: "underline" }}>digital Founders' Registry</a> — also permanent, also forever.
            </p>

            <div style={{ marginTop: 32, padding: 24, background: "rgba(181,168,107,0.06)", border: "1px solid rgba(181,168,107,0.25)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--navy-800)" }}>
                  Founders' Stone · Progress
                </div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--navy-900)" }}>
                  {formatMoney(raised, { compact: true })} <span style={{ color: "rgba(47,51,29,0.4)", fontSize: 15 }}>/ $500K</span>
                </div>
              </div>
              <div style={{ height: 6, background: "rgba(47,51,29,0.1)", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ height: "100%", width: foundersPct + "%", background: "linear-gradient(90deg, var(--moss-500), var(--gold-500))", borderRadius: 999, transition: "width 900ms" }} />
              </div>
              <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", fontSize: 12, color: "rgba(47,51,29,0.6)" }}>
                <span>{stoneFull ? "The stone is full." : `${formatMoney(foundersLeft, { compact: true })} until the stone closes`}</span>
                <span style={{ fontFamily: "var(--mono)", letterSpacing: "0.12em", textTransform: "uppercase", fontSize: 10 }}>{stoneFull ? "Closed" : "Open"}</span>
              </div>
            </div>

            <div style={{ marginTop: 24, fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 16, color: "rgba(47,51,29,0.6)" }}>
              "When your children ask in time to come, 'What do these stones mean?'…" <span style={{ fontFamily: "var(--sans)", fontStyle: "normal", fontSize: 12, color: "rgba(47,51,29,0.5)", letterSpacing: "0.1em" }}>— Joshua 4:6</span>
            </div>
          </div>
        </div>

        {/* TIER LADDER */}
        <div style={{ background: "var(--cream-50)", border: "1px solid rgba(47,51,29,0.1)", padding: "36px 40px", marginBottom: 100, boxShadow: "0 20px 40px -30px rgba(47,51,29,0.3)" }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--gold-600, rgb(138,125,77))", marginBottom: 18, textAlign: "center" }}>
            Tiers of Recognition
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 1, background: "rgba(47,51,29,0.08)" }} className="tier-grid">
            {TIERS.map((tier, i) => (
              <div key={i} style={{ padding: "20px 16px", background: "var(--cream-50)", textAlign: "center" }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)" }}>
                  {tier.max === Infinity ? `$${(tier.min/1000).toFixed(0)}K+` : `$${tier.min.toLocaleString()} – $${tier.max.toLocaleString()}`}
                </div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--navy-900)", marginTop: 10, fontStyle: "italic" }}>{tier.label}</div>
                <div style={{ fontSize: 12, color: "rgba(47,51,29,0.65)", marginTop: 8, lineHeight: 1.5 }}>{tier.note}</div>
              </div>
            ))}
          </div>
          <div style={{ textAlign: "center", marginTop: 18, fontSize: 13, color: "rgba(47,51,29,0.6)", fontStyle: "italic" }}>
            Gifts under $100 are honored in the digital <a href="#registry" style={{ color: "var(--moss-600)" }}>Founders' Registry</a> — every name, forever.
          </div>
        </div>

        {/* BENEFACTORS' LEADERBOARD */}
        <div style={{ borderTop: "1px solid rgba(47,51,29,0.12)", paddingTop: 80 }}>
          <div style={{ textAlign: "center", maxWidth: 720, margin: "0 auto 40px" }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.26em", textTransform: "uppercase", color: "var(--gold-600, rgb(138,125,77))", marginBottom: 14 }}>
              The Benefactors' Leaderboard · Live
            </div>
            <h3 style={{ fontSize: "clamp(28px, 3.5vw, 42px)", lineHeight: 1.15 }}>
              The ten largest gifts <em style={{ fontWeight: 400 }}>become buildings.</em>
            </h3>
            <p style={{ fontSize: 16, lineHeight: 1.7, color: "rgba(47,51,29,0.7)", marginTop: 18 }}>
              Rankings update in real time. Whoever holds a top-ten spot when we break ground chooses the building that will carry their family name, their photograph, and their dedication. The $1 gift that becomes the largest gift wins the Dining Hall. This is a promise, not a marketing line.
            </p>
          </div>

          {/* live indicator */}
          <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 8, marginBottom: 24, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)" }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--moss-500)", boxShadow: "0 0 0 4px rgba(95,122,82,0.2)", animation: "pulse 2s ease-in-out infinite" }} />
            Live rankings · updates as gifts arrive
          </div>

          {/* leaderboard */}
          <div style={{ maxWidth: 920, margin: "0 auto", background: "var(--cream-50)", border: "1px solid rgba(47,51,29,0.1)", boxShadow: "0 30px 60px -40px rgba(47,51,29,0.35)" }}>
            <div style={{ padding: "22px 32px", display: "grid", gridTemplateColumns: "50px 1fr 160px 1fr", gap: 16, borderBottom: "2px solid var(--navy-900)", background: "rgba(47,51,29,0.03)" }} className="ledger-row">
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)" }}>Rank</div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)" }}>Benefactor</div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)", textAlign: "right" }}>Pledge</div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "rgba(47,51,29,0.55)" }}>Building Choice</div>
            </div>

            {ranked.length === 0 && (
              <div style={{ padding: "40px 32px", textAlign: "center", color: "rgba(47,51,29,0.5)", fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18, borderBottom: "1px solid rgba(47,51,29,0.06)" }}>
                The leaderboard awaits its first benefactor.
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "rgba(47,51,29,0.4)", marginTop: 10, fontStyle: "normal" }}>
                  Top 10 gifts will appear here as they arrive
                </div>
              </div>
            )}

            {ranked.map((d, i) => {
              const assigned = d.assignedName;
              return (
                <div key={i} style={{ padding: "22px 32px", display: "grid", gridTemplateColumns: "50px 1fr 160px 1fr", gap: 16, borderBottom: "1px solid rgba(47,51,29,0.06)", alignItems: "center", transition: "background 400ms" }} className="ledger-row">
                  <div style={{ fontFamily: "var(--serif)", fontSize: 26, color: "var(--gold-600, rgb(138,125,77))", fontStyle: "italic" }}>
                    {String(i + 1).padStart(2, "0")}
                  </div>
                  <div>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 20, color: "var(--navy-900)" }}>{d.name}</div>
                    <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(47,51,29,0.5)", marginTop: 2 }}>
                      {assigned
                        ? `Choice #${d.assignedFrom} · family name on entry`
                        : (Array.isArray(d.preferences) && d.preferences.length === 0
                          ? "No preferences — decides at groundbreaking"
                          : "All choices taken · Board will consult")}
                    </div>
                  </div>
                  <div style={{ textAlign: "right", fontFamily: "var(--serif)", fontSize: 22, color: "var(--navy-900)" }}>
                    {formatMoney(d.amount, { compact: true })}
                  </div>
                  <div style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 17, color: assigned ? "var(--moss-600)" : "rgba(47,51,29,0.4)" }}>
                    {assigned || "— pending —"}
                  </div>
                </div>
              );
            })}

            <div style={{ padding: "28px 32px", background: "var(--navy-800)", color: "var(--cream-50)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
              <div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--gold-400)" }}>Think you can crack the top 10?</div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 22, marginTop: 4 }}>Speak with the Board privately.</div>
              </div>
              <a href="mailto:benefactors@neweden.academy" className="btn btn-gold benefactors-cta" style={{ padding: "14px 22px" }}>
                benefactors@neweden.academy
              </a>
            </div>
          </div>

          <div style={{ textAlign: "center", marginTop: 22, fontSize: 13, color: "rgba(47,51,29,0.55)", fontStyle: "italic", maxWidth: 640, margin: "22px auto 0" }}>
            Every gift is counted — one-time or the total of all monthly gifts. Anonymous donors are ranked by amount but listed as "Anonymous" on the stone and on this board.
          </div>
        </div>

        {/* DIGITAL FOUNDERS' REGISTRY */}
        <div id="registry" style={{ marginTop: 120, padding: "60px 48px", background: "var(--navy-900)", color: "var(--cream-50)", position: "relative", overflow: "hidden" }}>
          <div aria-hidden="true" style={{ position: "absolute", top: 0, left: 0, right: 0, height: 2, background: "linear-gradient(90deg, transparent, var(--gold-500), transparent)" }} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 60, alignItems: "center" }} className="registry-grid">
            <div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.26em", textTransform: "uppercase", color: "var(--gold-400)", marginBottom: 14 }}>
                Digital Founders' Registry
              </div>
              <h3 style={{ fontSize: "clamp(28px, 3.5vw, 40px)", lineHeight: 1.15, color: "var(--cream-50)" }}>
                Every gift.<br/><em style={{ fontWeight: 400, color: "var(--gold-400)" }}>Every donor.</em><br/>Forever on record.
              </h3>
              <p style={{ fontSize: 15, lineHeight: 1.7, color: "rgba(255,241,212,0.75)", marginTop: 20 }}>
                If your gift is below the $100 stone threshold, your name is still permanently recorded here — on our website, in our archive, and in our annual report. A $5 gift matters. A $5,000 gift matters. We remember both.
              </p>
              <a href="#" style={{ display: "inline-flex", alignItems: "center", gap: 10, marginTop: 24, padding: "12px 22px", border: "1px solid var(--gold-500)", color: "var(--gold-400)", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", textDecoration: "none", transition: "all 180ms" }}>
                Browse the full registry →
              </a>
            </div>

            {/* registry placeholder — names appear here as gifts arrive */}
            <div style={{ display: "grid", placeItems: "center", padding: "40px 24px", border: "1px dashed rgba(255,241,212,0.2)", background: "rgba(255,241,212,0.03)", textAlign: "center" }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--gold-400)" }}>The registry awaits</div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 22, fontStyle: "italic", color: "var(--cream-50)", marginTop: 10, lineHeight: 1.4 }}>The first names will appear here<br/>as the first gifts arrive.</div>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .legacy-grid, .registry-grid { grid-template-columns: 1fr !important; gap: 48px !important; }
          .tier-grid { grid-template-columns: 1fr 1fr !important; }
          .ledger-row { grid-template-columns: 44px 1fr !important; }
          .ledger-row > div:nth-child(3), .ledger-row > div:nth-child(4) {
            grid-column: 2 / -1; text-align: left !important;
          }
        }
        @media (max-width: 640px) {
          .benefactors-cta {
            white-space: normal !important;
            word-break: break-all;
            letter-spacing: 0.06em !important;
            font-size: 12px !important;
            text-transform: none !important;
            padding: 12px 16px !important;
            max-width: 100%;
            text-align: center;
          }
        }
        @keyframes pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.6; transform: scale(0.85); }
        }
      `}</style>
    </section>
  );
}

// ---- The Founders' Stone SVG --------------------------------------------
function FoundersStoneSVG({ pct }) {
  // Stone is intentionally blank at launch — names will appear here as
  // gifts of $100+ arrive and are engraved.
  const names = Array.from({ length: 24 }, () => "");
  const rowsLit = Math.ceil((pct / 100) * (names.length / 3));

  return (
    <svg viewBox="0 0 400 480" style={{ width: "100%", height: "auto", maxWidth: 440, display: "block", margin: "0 auto", filter: "drop-shadow(0 30px 40px rgba(47,51,29,0.25))" }}>
      <defs>
        <linearGradient id="stoneGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#b8b0a1" />
          <stop offset="40%" stopColor="#9c9484" />
          <stop offset="100%" stopColor="#6b6558" />
        </linearGradient>
        <linearGradient id="stoneShine" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="rgba(255,248,230,0.35)" />
          <stop offset="60%" stopColor="transparent" />
        </linearGradient>
      </defs>

      <path
        d="M 60 80 Q 58 70 70 60 L 130 40 Q 200 28 270 42 L 330 58 Q 345 68 342 82 L 348 160 L 344 250 L 346 340 L 340 420 Q 338 450 310 452 L 230 460 Q 150 462 90 450 Q 62 446 60 420 L 56 330 L 60 230 L 58 140 Z"
        fill="url(#stoneGrad)"
        stroke="#4a4638" strokeWidth="1.5"
      />
      <path
        d="M 60 80 Q 58 70 70 60 L 130 40 Q 200 28 270 42 L 330 58 Q 345 68 342 82 L 348 160 L 344 250 L 346 340 L 340 420 Q 338 450 310 452 L 230 460 Q 150 462 90 450 Q 62 446 60 420 L 56 330 L 60 230 L 58 140 Z"
        fill="url(#stoneShine)" opacity="0.35"
      />

      <line x1="100" y1="96" x2="300" y2="96" stroke="#3d3a2f" strokeWidth="0.8" opacity="0.5" />
      <line x1="100" y1="100" x2="300" y2="100" stroke="#d4c9a8" strokeWidth="0.4" opacity="0.4" />

      <text x="200" y="80" textAnchor="middle" fill="#3d3a2f" fontFamily="Cormorant Garamond, serif" fontSize="14" letterSpacing="3" fontStyle="italic">FOUNDERS OF NEW EDEN</text>
      <text x="200" y="122" textAnchor="middle" fill="#3d3a2f" fontFamily="Cormorant Garamond, serif" fontSize="11" letterSpacing="4" style={{ textTransform: "uppercase" }} opacity="0.6">ANNO MMXXVI</text>

      <path d="M 78 120 Q 82 180 76 240 Q 72 300 80 360" stroke="#3d3a2f" strokeWidth="0.6" fill="none" opacity="0.35" />
      <path d="M 320 140 Q 316 220 322 300" stroke="#3d3a2f" strokeWidth="0.5" fill="none" opacity="0.3" />

      <g fontFamily="Cormorant Garamond, serif" fontSize="9.2" fill="#2a2820" style={{ letterSpacing: 0.5 }}>
        {names.map((n, i) => {
          const col = i % 3;
          const row = Math.floor(i / 3);
          const x = 92 + col * 72;
          const y = 160 + row * 32;
          const isLit = row < rowsLit;
          return (
            <g key={i} opacity={isLit ? 0.95 : 0.25}>
              <text x={x} y={y} textAnchor="start">
                {n.length > 16 ? n.slice(0, 14) + "…" : n}
              </text>
              {isLit && <line x1={x} y1={y + 2} x2={x + 56} y2={y + 2} stroke="#2a2820" strokeWidth="0.3" opacity="0.25" />}
            </g>
          );
        })}
      </g>

      <g transform="translate(200, 428)" opacity="0.55">
        <line x1="0" y1="-10" x2="0" y2="6" stroke="#2a2820" strokeWidth="1.2" />
        <line x1="-6" y1="-4" x2="6" y2="-4" stroke="#2a2820" strokeWidth="1.2" />
      </g>
    </svg>
  );
}

Object.assign(window, { LegacySection });
