/* P.E.S.T Web App — Profile (username/password + up to 3 referral links) */
function Profile({ onOpenMember }) {
  const store = useStore();
  const me = store.member;
  const [username, setUsername] = useState(store.user.username);
  const [pw, setPw] = useState({ cur: "", next: "", conf: "" });
  const [refModal, setRefModal] = useState(false);
  const [pfpIdx, setPfpIdx] = useState(0);

  const pfps = (me.pfps || []).filter((p) => p.img);
  useEffect(() => {
    if (pfps.length < 2) return;
    const t = setInterval(() => setPfpIdx((x) => (x + 1) % pfps.length), 4200);
    return () => clearInterval(t);
  }, [pfps.length]);

  const myRefs = store.referralsByMember[store.user.nick] || [];

  const saveUsername = async () => {
    if (!username.trim()) { toast("Username can't be empty", "err"); return; }
    await store.setUsername(username.trim());
  };
  const savePassword = async () => {
    if (!pw.cur || !pw.next || !pw.conf) { toast("Fill in all password fields", "err"); return; }
    if (pw.next !== pw.conf) { toast("New passwords don't match", "err"); return; }
    if (pw.next.length < 6) { toast("Use at least 6 characters", "err"); return; }
    const ok = await store.changePassword(pw.cur, pw.next);
    if (ok) setPw({ cur: "", next: "", conf: "" });
  };

  return (
    <div>
      <div className="page-head">
        <div className="eyebrow">Profile</div>
        <h1>Your <span className="grad-text">node</span></h1>
        <p className="sub">Manage your access and the referral links you share with the hive.</p>
      </div>

      <div className="prof-grid">
        <div className="card prof-card cut">
          <div className="prof-pfp">
            {pfps.length > 0
              ? pfps.map((p, k) => <img key={k} src={p.img} alt={p.name} style={{ position: "absolute", inset: 0, opacity: k === pfpIdx ? 1 : 0, transition: "opacity 0.8s var(--ease)" }} />)
              : <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", fontFamily: "var(--font-mono)", fontSize: 38, color: "var(--tx-faint)" }}>{me.nick.slice(0, 2)}</div>}
            <window.HMedals m={me} big />
          </div>
          <div className="prof-name">{me.nick}</div>
          <div className="prof-role">{window.roleLabel(me)}</div>
          <div className="prof-uname">login · <b>{store.user.username}</b></div>
          {pfps.length > 1 && <div className="ref-slots-note" style={{ marginTop: 14 }}>{pfps.length} PFPs · managed by admin</div>}
        </div>

        <div>
          {/* account */}
          <div className="card panel cut">
            <div className="panel-head">
              <div>
                <div className="eyebrow">Account</div>
                <h2>Username</h2>
              </div>
            </div>
            <div className="form-row">
              <div className="field">
                <label>Username</label>
                <input className="input mono" value={username} onChange={(e) => setUsername(e.target.value)} />
              </div>
              <div className="form-actions">
                <button className="btn btn-primary" onClick={saveUsername}><window.AIcon.check /> Save username</button>
              </div>
            </div>
          </div>

          {/* password */}
          <div className="card panel cut">
            <div className="panel-head">
              <div>
                <div className="eyebrow">Security</div>
                <h2>Change password</h2>
              </div>
              <window.AIcon.lock style={{ width: 20, height: 20, color: "var(--tx-faint)" }} />
            </div>
            <div className="form-row">
              <div className="field">
                <label>Current password</label>
                <input className="input mono" type="password" value={pw.cur} onChange={(e) => setPw({ ...pw, cur: e.target.value })} placeholder="••••••••" />
              </div>
              <div className="form-2">
                <div className="field">
                  <label>New password</label>
                  <input className="input mono" type="password" value={pw.next} onChange={(e) => setPw({ ...pw, next: e.target.value })} placeholder="••••••••" />
                </div>
                <div className="field">
                  <label>Confirm</label>
                  <input className="input mono" type="password" value={pw.conf} onChange={(e) => setPw({ ...pw, conf: e.target.value })} placeholder="••••••••" />
                </div>
              </div>
              <div className="form-actions">
                <button className="btn btn-primary" onClick={savePassword}><window.AIcon.key /> Update password</button>
              </div>
            </div>
          </div>

          {/* referrals */}
          <div className="card panel cut">
            <div className="panel-head">
              <div>
                <div className="eyebrow">Referrals</div>
                <h2>Your referral links</h2>
              </div>
              <span className="ref-slots-note">{myRefs.length}/{window.PEST_APP.MAX_REFS}</span>
            </div>
            <p className="sub" style={{ margin: "0 0 16px" }}>Share up to {window.PEST_APP.MAX_REFS} referral links. They appear as badges on your member card so the hive can support you.</p>

            {myRefs.length === 0 && <div className="ref-empty">No referral links yet.</div>}
            {myRefs.length > 0 && (
              <div className="reflist">
                {myRefs.map((r, i) => {
                  const proj = store.projects.find((p) => p.id === r.projectId);
                  if (!proj) return null;
                  return (
                    <div className="refitem" key={i}>
                      <LogoTile project={proj} />
                      <div className="ri">
                        <b>{proj.name}</b>
                        <span>{r.url}</span>
                      </div>
                      <button className="icon-x" onClick={() => store.removeReferral(i)} title="Remove"><window.AIcon.trash /></button>
                    </div>
                  );
                })}
              </div>
            )}

            <div className="form-actions">
              <button className="btn" onClick={() => setRefModal(true)} disabled={myRefs.length >= window.PEST_APP.MAX_REFS}>
                <window.AIcon.plus /> Add referral link
              </button>
            </div>
          </div>
        </div>
      </div>

      {refModal && <AddReferralModal onClose={() => setRefModal(false)} />}
    </div>
  );
}

function AddReferralModal({ onClose }) {
  const store = useStore();
  const myRefs = store.referralsByMember[store.user.nick] || [];
  const usedIds = new Set(myRefs.map((r) => r.projectId));
  const avail = store.projects.filter((p) => !usedIds.has(p.id));
  const [pid, setPid] = useState(avail[0] ? avail[0].id : "");
  const [url, setUrl] = useState("");
  const proj = store.projects.find((p) => p.id === pid);

  useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);

  const save = async () => {
    if (!pid) { toast("Pick a project", "err"); return; }
    if (!url.trim() || !/^https?:\/\//i.test(url.trim())) { toast("Enter a valid URL (https://…)", "err"); return; }
    const ok = await store.addReferral(pid, url.trim());
    if (ok) onClose();
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" style={{ width: "min(460px,100%)" }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h3>Add referral link</h3>
          <button className="icon-x" onClick={onClose}><window.AIcon.close /></button>
        </div>
        <div className="modal-body">
          <div className="form-row">
            <div className="field">
              <label>Project</label>
              <select className="select" value={pid} onChange={(e) => setPid(e.target.value)}>
                {avail.length === 0 && <option value="">No projects left</option>}
                {avail.map((p) => <option key={p.id} value={p.id}>{p.name} · {(p.categories && p.categories[0]) || p.category || ""}</option>)}
              </select>
            </div>
            {proj && (
              <div className="logo-preview">
                <LogoTile project={proj} />
                <div><b>{proj.name}</b><div className="ref-slots-note">{(proj.categories && proj.categories.join(" · ")) || proj.category || ""}</div></div>
              </div>
            )}
            <div className="field">
              <label>Your referral URL</label>
              <input className="input mono" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://…/ref?code=YOU" />
            </div>
            <div className="form-actions">
              <button className="btn btn-primary btn-block" onClick={save}><window.AIcon.check /> Save referral</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Profile = Profile;
