/* P.E.S.T Web App — Members showcase + modal (with referral links/badges) */
function RefBadges({ refs, projects, className }) {
  if (!refs || refs.length === 0) return null;
  return (
    <div className={className || "ref-badges"}>
      {refs.slice(0, 3).map((r, i) => {
        const proj = projects.find((p) => p.id === r.projectId);
        if (!proj) return null;
        return (
          <div className="ref-badge" key={i} title={"Referral: " + proj.name}>
            {proj.logo ? <img src={window.resolveLogo(proj.logo)} alt={proj.name} /> : <span className="lt" style={{ background: `hsl(${window.hueFromString(proj.name)} 60% 22%)` }}>{proj.name[0]}</span>}
          </div>
        );
      })}
    </div>
  );
}

function MemberCard({ m, refs, projects, onOpen }) {
  const badges = window.memberBadges(m);
  return (
    <div className="m-card" onClick={() => onOpen(m)}>
      {badges.length > 0 && (
        <div className="m-badges">
          {badges.map((b) => <span className={"m-badge " + window.BADGE_META[b].cls} key={b}>{window.BADGE_META[b].short}</span>)}
        </div>
      )}
      <RefBadges refs={refs} projects={projects} />
      <window.MAvatar m={m} withMedals />
      <div className="m-nick">{m.nick}</div>
      <div className="m-role">{window.roleLabel(m)}</div>
    </div>
  );
}

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

function MemberModal({ m, onClose }) {
  const store = useStore();
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  const socials = Object.keys(m.socials || {}).filter((s) => m.socials[s]);
  const badges = window.memberBadges(m);
  const pfp = (m.pfps && m.pfps[idx]) || (m.pfps && m.pfps[0]) || { name: "" };
  const refs = (store.referralsByMember[m.nick] || []);
  const isMe = m.nick === store.user.nick;

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="mm-top">
          <button className="icon-x" onClick={onClose} style={{ position: "absolute", top: 14, right: 14 }}><window.AIcon.close /></button>
          <div className="mm-av">{pfp.img ? <img src={pfp.img} alt={m.nick} /> : <div className="ph">{m.nick.slice(0, 2)}</div>}<window.HMedals m={m} big /></div>
          <div style={{ minWidth: 0 }}>
            <div className="mm-role">{window.roleLabel(m)}</div>
            <div className="mm-nick">{m.nick}</div>
            <div className="mm-pfp">PFP · <b>{pfp.name}</b></div>
            {badges.length > 0 && (
              <div className="mm-chips">
                {badges.map((b) => <span className={"m-badge " + window.BADGE_META[b].cls} key={b}>{window.BADGE_META[b].full}</span>)}
              </div>
            )}
            {window.honoraryBadges(m).length > 0 && (
              <div className="mm-chips 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 && m.pfps.length > 1 && (
            <div className="pfp-strip">
              <span className="lbl">PFP Collection</span>
              <div className="pfp-thumbs">
                {m.pfps.map((p, i) => (
                  <button key={i} className={"pfp-thumb" + (i === idx ? " on" : "")} 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="mm-desc">{m.desc}</p> : <p className="mm-desc faint">No bio yet.</p>}

          {(socials.length > 0 || m.discord) && (
            <React.Fragment>
              <div className="mm-section-label">Personal channels</div>
              <div className="mm-socials">
                {socials.map((s) => { const meta = window.A_SOCIAL[s]; const I = meta.icon; return <a className="pill" key={s} href={m.socials[s]} target="_blank" rel="noreferrer"><I /> {meta.label}</a>; })}
                {m.discord && <DiscordPill user={m.discord} />}
              </div>
            </React.Fragment>
          )}

          <div className="mm-section-label">Referral links {refs.length > 0 && <span style={{ color: "var(--tx-faint)" }}>· support {isMe ? "you" : m.nick}</span>}</div>
          {refs.length === 0 ? (
            <div className="ref-empty">{isMe ? "You haven't added any referral links yet." : "No referral links shared."}</div>
          ) : (
            <div>
              {refs.map((r, i) => {
                const proj = store.projects.find((p) => p.id === r.projectId);
                if (!proj) return null;
                return (
                  <div className="ref-row" key={i}>
                    <LogoTile project={proj} />
                    <div className="ri">
                      <b>{proj.name}</b>
                      <span>{(proj.categories && proj.categories.join(" · ")) || proj.category || ""}</span>
                    </div>
                    <a className="btn btn-sm btn-primary" href={r.url} target="_blank" rel="noreferrer"><window.AIcon.external /> Use ref</a>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Members() {
  const store = useStore();
  const [open, setOpen] = useState(null);
  const data = window.sortMembers(store.members);
  return (
    <div>
      <div className="page-head">
        <div className="eyebrow">Core Members</div>
        <h1>The <span className="grad-text">inner circle</span></h1>
        <p className="sub">Thirty nodes of trust. Tap a member to see their channels — and the referral links they share with the hive.</p>
      </div>
      <div className="member-grid">
        {data.map((m, i) => (
          <MemberCard key={m.nick} m={m} refs={store.referralsByMember[m.nick]} projects={store.projects} onOpen={setOpen} />
        ))}
      </div>
      {open && <MemberModal m={open} onClose={() => setOpen(null)} />}
    </div>
  );
}

window.Members = Members;
window.MemberModal = MemberModal;
