/* P.E.S.T — content sections: Manifesto, Structure, Members + Modal, Partners, Footer */
const { useState: useS, useEffect: useE } = React;

function useReveal() {
  useE(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && e.target.classList.add("in")),
      { threshold: 0.12 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ---------- Manifesto ---------- */
function Manifesto() {
  const pts = [
    { n: "01", h: "Hivemind", p: "We think together. Knowledge flows freely between nodes — what one learns, the hive learns." },
    { n: "02", h: "Trust", p: "Core members share the highest level of trust. It is the foundation everything else is built on." },
    { n: "03", h: "Open Door", p: "Anyone who wants to join is welcome as a Member. A seat at the core, however, is earned." },
    { n: "04", h: "Global, DE-rooted", p: "Members span the globe, but our roots and working language are German. English is our shared front door." },
  ];
  return (
    <section className="manifesto sec-pad" id="manifesto">
      <div className="wrap">
        <div className="manifesto-grid reveal">
          <div>
            <div className="eyebrow">Manifesto</div>
            <p className="manifesto-statement" style={{ marginTop: 18 }}>
              P.E.S.T is a <em className="grad-text">single mind running on many people</em> —
              a collective that turns shared web3 knowledge into an edge no one holds alone.
            </p>
          </div>
          <div className="manifesto-cols">
            {pts.map((x) => (
              <div className="pt" key={x.n}>
                <h4><span className="num">{x.n}</span> {x.h}</h4>
                <p>{x.p}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Structure ---------- */
function Structure() {
  const all = window.PEST_DATA.members;
  const coCount = all.filter((m) => m.role === "co-leader").length;
  const coreCount = all.length;
  const tiers = [
    { rank: "01", name: "Leader", count: "1", desc: "Sets direction and holds the hive together.", t1: true },
    { rank: "02", name: "Co-Leader", count: String(coCount), desc: "Right hands to the Leader — operations and steering." },
    { rank: "03", name: "Core-Member", count: String(coreCount), desc: "The trusted inner circle. Earned, never given." },
    { rank: "04", name: "Member", count: "∞", desc: "The wider hive. Open to everyone who wants in." },
  ];
  return (
    <section className="structure sec-pad" id="structure">
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="eyebrow">Structure</div>
          <h2 className="h-sec">Four tiers, <span className="grad-text">one organism</span></h2>
        </div>
        <div className="tiers">
          {tiers.map((t, i) => (
            <div className={"tier reveal" + (t.t1 ? " tier-1" : "")} key={t.rank} style={{ transitionDelay: i * 60 + "ms" }}>
              <span className="rank">{t.rank}</span>
              <div>
                <div className="t-name">{t.name}</div>
                <div className="t-desc">{t.desc}</div>
              </div>
              <span className="t-count">{t.count}</span>
            </div>
          ))}
        </div>
        <div className="struct-note reveal">
          <span className="ic"><window.Icon.link /></span>
          <span>
            New Core-Members are elected by the existing Core — an <b style={{ color: "var(--tx)" }}>absolute majority</b> is
            required. There is no fixed cap on the core; trust sets the pace.
          </span>
        </div>

        <div className="special-roles reveal">
          <div className="eyebrow" style={{ marginBottom: 18 }}>Special designations</div>
          <p className="lead" style={{ marginBottom: 26 }}>
            Held <b style={{ color: "var(--tx)" }}>in addition</b> to a Core-Member's seat — earned for what they bring to the hive.
          </p>
          <div className="special-grid">
            <div className="special-card oracle">
              <span className="m-badge oracle">Oracle</span>
              <p>Members who consistently stand out — sharp calls, signal, and insight that lifts the whole hive.</p>
            </div>
            <div className="special-card gcoder">
              <span className="m-badge gcoder">Genetic Coder</span>
              <p>Keepers of the machine — responsible for P.E.S.T's IT infrastructure, tooling and the tech that runs underneath.</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Members ---------- */
// Sort order: Leader -> Co-Leader -> Genetic Coder -> Oracle -> rest (stable within group)
function sortPriority(m) {
  if (m.role === "leader") return 0;
  if (m.role === "co-leader") return 1;
  if ((m.tags || []).includes("genetic-coder")) return 2;
  if ((m.tags || []).includes("oracle")) return 3;
  return 4;
}
function sortMembers(list) {
  return list
    .map((m, i) => [m, i])
    .sort((a, b) => sortPriority(a[0]) - sortPriority(b[0]) || window.badgePriority(a[0]) - window.badgePriority(b[0]) || a[1] - b[1])
    .map((x) => x[0]);
}
const BADGE_META = {
  leader: { full: "Leader", short: "Leader", cls: "lead" },
  "co-leader": { full: "Co-Leader", short: "Co-Lead", cls: "co" },
  oracle: { full: "Oracle", short: "Oracle", cls: "oracle" },
  "genetic-coder": { full: "Genetic Coder", short: "Coder", cls: "gcoder" },
};

function memberBadges(m) {
  const b = [];
  if (m.role === "leader") b.push("leader");
  if (m.role === "co-leader") b.push("co-leader");
  (m.tags || []).forEach((t) => BADGE_META[t] && b.push(t));
  return b;
}
function roleLabel(m) {
  if (m.role === "leader") return "Leader";
  if (m.role === "co-leader") return "Co-Leader";
  if ((m.tags || []).includes("oracle")) return "Oracle";
  if ((m.tags || []).includes("genetic-coder")) return "Genetic Coder";
  return "Core-Member";
}

function HMedals({ m, big }) {
  const hb = window.honoraryBadges ? window.honoraryBadges(m) : [];
  if (!hb.length) return null;
  return (
    <div className={"hb-medals" + (big ? " big" : "")}>
      {hb.map((k) => {
        const B = window.HBADGE[k]; const I = B.icon;
        return <span className={"hb-medal " + B.cls} key={k} title={B.tip}><I /></span>;
      })}
    </div>
  );
}

function Avatar({ m, pfp, big }) {
  const initials = m.nick.slice(0, 2);
  const img = pfp && pfp.img;
  return (
    <div className={big ? "modal-av" : "m-avatar"}>
      {img ? <img src={img} alt={m.nick} /> : <span className="ph">{initials}</span>}
      <HMedals m={m} big={big} />
    </div>
  );
}

function MemberCard({ m, onOpen }) {
  const badges = memberBadges(m);
  return (
    <div className="m-card" onClick={() => onOpen(m)}>
      {badges.length > 0 && (
        <div className="m-badges">
          {badges.map((b) => (
            <span className={"m-badge " + BADGE_META[b].cls} key={b}>{BADGE_META[b].short}</span>
          ))}
        </div>
      )}
      {m.pfps.length > 1 && <span className="m-multi">{m.pfps.length}×</span>}
      <Avatar m={m} pfp={m.pfps[0]} />
      <div className="m-nick">{m.nick}</div>
      <div className="m-role">{roleLabel(m)}</div>
    </div>
  );
}

function DiscordPill({ user }) {
  const [copied, setCopied] = useS(false);
  const copy = () => {
    navigator.clipboard && navigator.clipboard.writeText(user);
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  };
  return (
    <button className="social-pill discord-pill" onClick={copy} title="Copy Discord username">
      <window.Icon.discord /> {copied ? "Copied ✓" : user}
    </button>
  );
}

function scrollToPartner(abbr) {
  const p = (window.PEST_DATA.partners || []).find((x) => x.abbr === abbr);
  if (!p) return;
  const el = document.getElementById("partner-" + p.id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 90;
  window.scrollTo({ top, behavior: "smooth" });
  el.classList.add("p-flash");
  setTimeout(() => el.classList.remove("p-flash"), 1600);
}

function MemberModal({ m, onClose, onGoPartner }) {
  const [idx, setIdx] = useS(0);
  useE(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  useE(() => setIdx(0), [m]);
  if (!m) return null;
  const socials = Object.keys(m.socials || {});
  const badges = memberBadges(m);
  const pfp = m.pfps[idx] || m.pfps[0];
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close"><window.Icon.close /></button>
        <div className="modal-top">
          <Avatar m={m} pfp={pfp} big />
          <div className="modal-id">
            <div className="modal-role">{roleLabel(m)}</div>
            <div className="modal-nick glitch grad-text" data-text={m.nick}>{m.nick}</div>
            <div className="modal-pfp">
              PFP · <b>{pfp.name}</b>
              {pfp.partner && (
                <button className="pfp-partner-pill" onClick={() => onGoPartner(pfp.partner)} title={"Partner community: " + pfp.partner}>
                  {pfp.partner} <span className="arr">↗</span>
                </button>
              )}
            </div>
            {badges.length > 0 && (
              <div className="modal-badges">
                {badges.map((b) => (
                  <span className={"m-badge " + BADGE_META[b].cls} key={b}>{BADGE_META[b].full}</span>
                ))}
              </div>
            )}
            {window.honoraryBadges(m).length > 0 && (
              <div className="modal-badges hbadges">
                {window.honoraryBadges(m).map((k) => {
                  const B = window.HBADGE[k]; const I = B.icon;
                  return <span className={"hb-chip " + B.cls} key={k} title={B.tip}><I /> {B.label}</span>;
                })}
              </div>
            )}
          </div>
        </div>
        <div className="modal-body">
          {m.pfps.length > 1 && (
            <div className="pfp-strip">
              <span className="pfp-strip-label">PFP Collection</span>
              <div className="pfp-thumbs">
                {m.pfps.map((p, i) => (
                  <button
                    key={i}
                    className={"pfp-thumb" + (i === idx ? " active" : "")}
                    onClick={() => setIdx(i)}
                    title={p.name}
                  >
                    {p.img ? <img src={p.img} alt={p.name} /> : <span>{m.nick.slice(0, 2)}</span>}
                  </button>
                ))}
              </div>
            </div>
          )}
          {m.desc ? <p className="modal-desc">{m.desc}</p> : <p className="modal-desc faint">No bio yet.</p>}
          {(socials.length > 0 || m.discord) && (
            <div className="modal-socials">
              {socials.map((s) => {
                const meta = window.SOCIAL_META[s];
                const I = meta.icon;
                return (
                  <a className="social-pill" key={s} href={m.socials[s]} target="_blank" rel="noreferrer">
                    <I /> {meta.label}
                  </a>
                );
              })}
              {m.discord && <DiscordPill user={m.discord} />}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Members() {
  const [open, setOpen] = useS(null);
  const data = sortMembers(window.PEST_DATA.members);
  return (
    <section className="members sec-pad" id="members">
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="eyebrow">Core Members</div>
          <h2 className="h-sec">The <span className="grad-text">inner circle</span></h2>
          <p className="lead" style={{ marginTop: 14 }}>
            Thirty nodes of trust. Tap any member to see their dossier and personal channels.
          </p>
        </div>
        <div className="member-grid reveal">
          {data.map((m, i) => <MemberCard key={i} m={m} onOpen={setOpen} />)}
        </div>
      </div>
      {open && <MemberModal m={open} onClose={() => setOpen(null)} onGoPartner={(abbr) => { setOpen(null); setTimeout(() => scrollToPartner(abbr), 80); }} />}
    </section>
  );
}

/* ---------- Partners ---------- */
function Partners() {
  const data = window.PEST_DATA.partners;
  return (
    <section className="partners sec-pad" id="partners">
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="eyebrow">Allies</div>
          <h2 className="h-sec">Partner <span className="grad-text">communities</span></h2>
          <p className="lead" style={{ marginTop: 14 }}>
            Collectives we build, share and ship alongside. Placeholders for now — your real partners drop in here.
          </p>
        </div>
        <div className="partner-grid">
          {data.map((p, i) => (
            <div className="p-card reveal" id={"partner-" + p.id} key={i} style={{ transitionDelay: i * 70 + "ms" }}>
              <div className="p-logo">
                {p.logo ? <img src={p.logo} alt={p.name} /> : p.name.slice(0, 1)}
              </div>
              <div>
                <div className="eyebrow" style={{ marginBottom: 8 }}>{p.tag}</div>
                <h3>{p.name}</h3>
              </div>
              <p className="p-desc">{p.desc}</p>
              <div className="p-links">
                {Object.keys(p.links).map((k) => {
                  const meta = window.SOCIAL_META[k];
                  const I = meta.icon;
                  return (
                    <a className="social-pill" key={k} href={p.links[k]} target="_blank" rel="noreferrer">
                      <I /> {meta.label}
                    </a>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="footer" id="join">
      <div className="wrap">
        <div className="footer-cta reveal">
          <img className="aberr floaty" src={window.EMBLEM} alt="P.E.S.T" />
          <div className="footer-motto"><span className="glitch grad-text" data-text="WE ARE THE PLAGUE">WE ARE THE PLAGUE</span></div>
          <h2>Join the <span className="grad-text">hive</span></h2>
          <p>The door is open. Come share what you know, learn what you don't, and find out if the core is for you.</p>
          <div className="hero-socials" style={{ justifyContent: "center" }}>
            <window.SocialLink kind="discord" href="#" primary label="Join Discord" />
            <window.SocialLink kind="x" href="#" label="Follow on X" />
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} P.E.S.T · pestdao.xyz · <a className="footer-legal" href="legal-notice.html">Legal Notice</a> · <a className="footer-legal" href="privacy.html">Privacy</a></span>
          <div className="footer-socials">
            <a className="icon-btn" href={window.PEST_LINKS.discord} target="_blank" rel="noreferrer" aria-label="Discord"><window.Icon.discord /></a>
            <a className="icon-btn" href={window.PEST_LINKS.x} target="_blank" rel="noreferrer" aria-label="X"><window.Icon.x /></a>
            <a className="icon-btn" href={window.PEST_LINKS.telegram} target="_blank" rel="noreferrer" aria-label="Telegram"><window.Icon.telegram /></a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Manifesto, Structure, Members, Partners, Footer, useReveal });
