/* P.E.S.T Web App — Dashboard (orbit: rotating PFP + pinned project nodes) */
function RotatingPFP({ member }) {
  const pfps = (member.pfps || []).filter((p) => p.img);
  const [i, setI] = useState(0);
  useEffect(() => {
    if (pfps.length < 2) return;
    const t = setInterval(() => setI((x) => (x + 1) % pfps.length), 4200);
    return () => clearInterval(t);
  }, [pfps.length]);
  return (
    <div className="orbit-core">
      <div className="glow"></div>
      <div className="ring"></div>
      <div className="pfp">
        {pfps.length === 0 && <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 34, color: "var(--tx-faint)" }}>{member.nick.slice(0, 2)}</div>}
        {pfps.map((p, k) => (
          <img key={k} className={k === i ? "show" : ""} src={p.img} alt={p.name} />
        ))}
      </div>
      <span className="uname">{member.nick}</span>
    </div>
  );
}

function orbitPositions(n) {
  // evenly distribute exactly n nodes on an ellipse, first at top
  const rx = 41, ry = 38;
  const out = [];
  for (let i = 0; i < n; i++) {
    const a = (-90 + (360 / n) * i) * (Math.PI / 180);
    out.push({ x: 50 + rx * Math.cos(a), y: 50 + ry * Math.sin(a) });
  }
  return out;
}

function Dashboard({ onNavigate }) {
  const store = useStore();
  const me = store.member; // full member object of logged-in user
  const pinned = store.user.pinned
    .map((id) => store.projects.find((p) => p.id === id))
    .filter(Boolean);
  // Only render real pinned projects — no empty/placeholder nodes.
  const pos = orbitPositions(pinned.length);

  const [qa, setQa] = useState(null);
  const [pickTokens, setPickTokens] = useState(false);
  const [clock, setClock] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setClock(new Date()), 30000);
    return () => clearInterval(t);
  }, []);
  const hh = String(clock.getHours()).padStart(2, "0");
  const mm = String(clock.getMinutes()).padStart(2, "0");
  const dateStr = clock.toLocaleDateString("en-GB", { weekday: "short", day: "2-digit", month: "short" });

  return (
    <div className="dash">
      <div className="dash-greet">
        <div>
          <div className="eyebrow">Dashboard</div>
          <h1>Welcome back, <span className="grad-text">{me.nick}</span></h1>
        </div>
        <div className="dash-greet-side">
          <div className="dash-clock"><b>{hh}:{mm}</b>{dateStr} · {pinned.length}/{window.PEST_APP.MAX_PINS} pinned</div>
          <button className="btn btn-sm" onClick={() => onNavigate("projects")}><window.AIcon.plus /> Pin projects</button>
        </div>
      </div>

      <div className="orbit-stage">
        <div className="orbit">
          <div className="orbit-ring"></div>
          <div className="orbit-ring r2"></div>

          <RotatingPFP member={me} />

          {pinned.map((p, i) => (
            <div key={p.id} className="orbit-node" style={{ left: pos[i].x + "%", top: pos[i].y + "%" }} onClick={() => setQa(p)}>
              <LogoTile project={p} className="nlogo" />
              <span className="nlabel">{p.name}</span>
            </div>
          ))}
        </div>
      </div>

      {pinned.length === 0 && (
        <div className="dash-empty" style={{ margin: "0 auto" }}>
          <p>Your hive is empty. Pin the projects you use most from the <b style={{ color: "var(--tx)" }}>Projects</b> page — they'll orbit your node here for one-tap access.</p>
          <button className="btn btn-primary" onClick={() => onNavigate("projects")} style={{ marginTop: 6 }}><window.AIcon.projects /> Browse projects</button>
        </div>
      )}

      <window.TokenWatchlist onManage={() => setPickTokens(true)} />

      {qa && <QuickAccess project={qa} onClose={() => setQa(null)} />}
      {pickTokens && <window.TokenPicker onClose={() => setPickTokens(false)} />}
    </div>
  );
}

function QuickAccess({ project, onClose }) {
  const store = useStore();
  useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  const links = Object.keys(project.links || {}).filter((k) => project.links[k]);
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" style={{ width: "min(420px,100%)" }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-body">
          <div className="qa-pop">
            <div className="qa-head">
              <LogoTile project={project} />
              <div>
                <h3>{project.name}</h3>
                <div className="p-cats">
                  {((project.categories && project.categories.length) ? project.categories : (project.category ? [project.category] : [])).map((c) => <span key={c} className={"tag cat-" + c.replace(/[^A-Za-z0-9]/g, "")}>{c}</span>)}
                </div>
              </div>
            </div>
            <div className="qa-links">
              {links.map((k) => {
                const meta = window.A_SOCIAL[k]; const I = meta.icon;
                return <a className="pill" key={k} href={project.links[k]} target="_blank" rel="noreferrer"><I /> {meta.label}</a>;
              })}
              {links.length === 0 && <span className="ref-slots-note">No links yet.</span>}
            </div>
            <div className="qa-actions">
              {project.links.website && <a className="btn btn-primary btn-block" href={project.links.website} target="_blank" rel="noreferrer"><window.AIcon.external /> Open</a>}
              <button className="btn btn-ghost" onClick={() => { store.unpinProject(project.id); toast("Removed from dashboard"); onClose(); }} title="Unpin"><window.AIcon.pinned /></button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.orbitPositions = orbitPositions;
window.QuickAccess = QuickAccess;
