// Admin page — hidden behind direct URL navigation (no nav link).
// Lists all buyer accounts with status; approve/deny actions update localStorage.
// NOTE: This is a localStorage-only demo. Real multi-user approval requires a
// shared backend (Supabase). Each visitor's browser has its own account store.

function AdminPage({ onNav, accounts, setAccountStatus, currentUser }) {
  const [filter, setFilter] = React.useState("pending");
  const [confirm, setConfirm] = React.useState(null); // {action: 'approve'|'deny', email}

  // Gate: only an account with isAdmin === true can see this page
  if (!currentUser || !currentUser.isAdmin) {
    return (
      <div className="container" style={{ maxWidth: 480, textAlign: "center", padding: "100px 24px" }}>
        <div style={{
          width: 56, height: 56, borderRadius: "50%",
          background: "var(--bg-sunken)", border: "1px solid var(--line)",
          display: "grid", placeItems: "center", color: "var(--ink-3)",
          margin: "0 auto 22px",
        }}>
          <IcShield size={22} />
        </div>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Admin only</div>
        <h1 style={{ fontSize: 24, fontWeight: 600, letterSpacing: "-0.02em", margin: 0, marginBottom: 12 }}>
          Sign in with an admin account
        </h1>
        <p style={{ color: "var(--ink-2)", fontSize: 14, lineHeight: 1.6, margin: "0 auto 24px", maxWidth: "40ch" }}>
          The buyer approval queue is restricted to Clearspace team members.
        </p>
        <button className="btn btn-primary btn-lg" onClick={() => onNav("login")}>Sign in</button>
      </div>
    );
  }

  // Build a clean list excluding admin accounts and the seed if you want
  const rows = Object.values(accounts)
    .map((a) => a.profile)
    .filter((p) => !p.isAdmin)
    .sort((a, b) => (b.appliedAt || 0) - (a.appliedAt || 0));

  const counts = {
    all: rows.length,
    pending: rows.filter((r) => (r.status || "approved") === "pending").length,
    approved: rows.filter((r) => r.status === "approved").length,
    denied: rows.filter((r) => r.status === "denied").length,
  };

  const filtered = filter === "all" ? rows : rows.filter((r) => (r.status || "approved") === filter);

  const doApprove = (email) => { setAccountStatus(email, "approved"); setConfirm(null); };
  const doDeny = (email) => { setAccountStatus(email, "denied"); setConfirm(null); };

  return (
    <div className="container" style={{ padding: "32px 32px 80px" }}>
      <div className="row between" style={{ alignItems: "flex-end", marginBottom: 28, flexWrap: "wrap", gap: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Clearspace admin · Buyer approval queue</div>
          <h1 className="display" style={{ fontSize: 38, margin: 0 }}>Account approvals</h1>
          <div style={{ fontSize: 14, color: "var(--ink-3)", marginTop: 6 }}>
            Review and approve buyers who applied for platform access.
          </div>
        </div>
      </div>

      <div className="info-banner" style={{
        background: "rgba(37,99,235,0.06)", border: "1px solid rgba(37,99,235,0.20)",
        borderRadius: 12, padding: "14px 18px", marginBottom: 24, display: "flex", gap: 12, alignItems: "flex-start",
      }}>
        <div style={{ flexShrink: 0, marginTop: 2 }}><IcShield size={16} /></div>
        <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>
          <strong>Prototype note:</strong> this approval queue reads from your browser's <code>localStorage</code> only — it does not sync across devices or to other admins. Wire this to Supabase (or another shared DB) before production use.
        </div>
      </div>

      <div className="tabs" style={{ marginBottom: 24 }}>
        {[
          { id: "pending", label: "Pending" },
          { id: "approved", label: "Approved" },
          { id: "denied", label: "Denied" },
          { id: "all", label: "All accounts" },
        ].map((t) => (
          <button key={t.id} className="tab" data-active={filter === t.id} onClick={() => setFilter(t.id)}>
            {t.label}
            <span className="tab-count mono">{counts[t.id]}</span>
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div style={{
          padding: "60px 20px", textAlign: "center", color: "var(--ink-3)",
          border: "1px dashed var(--line)", borderRadius: 12, background: "var(--bg-sunken)",
        }}>
          <div className="mono" style={{ fontSize: 12, letterSpacing: "0.1em", marginBottom: 6, color: "var(--ink-4)" }}>EMPTY</div>
          <div style={{ fontSize: 14 }}>No accounts in this view.</div>
        </div>
      ) : (
        <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden", background: "var(--bg-elev)" }}>
          <div style={{
            display: "grid",
            gridTemplateColumns: "minmax(180px, 1.4fr) minmax(180px, 1.6fr) minmax(140px, 1fr) 110px 220px",
            gap: 0, fontSize: 11, fontFamily: "JetBrains Mono, monospace", letterSpacing: "0.08em",
            textTransform: "uppercase", color: "var(--ink-3)",
            padding: "12px 18px", borderBottom: "1px solid var(--line)", background: "var(--bg-sunken)",
          }}>
            <span>Applicant</span>
            <span>Email</span>
            <span>Company</span>
            <span>Status</span>
            <span style={{ textAlign: "right" }}>Actions</span>
          </div>
          {filtered.map((p, i) => {
            const status = p.status || "approved";
            const statusPill = status === "pending" ? "pill-amber" : status === "approved" ? "pill-primary" : "pill";
            const statusLabel = status === "pending" ? "Pending" : status === "approved" ? "Approved" : "Denied";
            const applied = p.appliedAt ? new Date(p.appliedAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "—";
            return (
              <div key={p.email} style={{
                display: "grid",
                gridTemplateColumns: "minmax(180px, 1.4fr) minmax(180px, 1.6fr) minmax(140px, 1fr) 110px 220px",
                gap: 0, alignItems: "center",
                padding: "14px 18px",
                borderBottom: i < filtered.length - 1 ? "1px solid var(--line)" : "none",
                fontSize: 13,
              }}>
                <div>
                  <div style={{ fontWeight: 600 }}>{p.name}</div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>
                    {p.id} · applied {applied}
                  </div>
                </div>
                <div style={{ color: "var(--ink-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", paddingRight: 12 }}>
                  {p.email}
                </div>
                <div style={{ color: "var(--ink-2)" }}>{p.company || "—"}</div>
                <div>
                  <span className={`pill ${statusPill}`} style={{ padding: "3px 10px", fontSize: 11 }}>{statusLabel}</span>
                </div>
                <div className="row gap-6" style={{ justifyContent: "flex-end" }}>
                  {status !== "approved" && (
                    <button className="btn btn-primary btn-sm" onClick={() => setConfirm({ action: "approve", email: p.email, name: p.name })}>
                      Approve
                    </button>
                  )}
                  {status !== "denied" && (
                    <button className="btn btn-secondary btn-sm" onClick={() => setConfirm({ action: "deny", email: p.email, name: p.name })}>
                      Deny
                    </button>
                  )}
                  {status === "approved" && (
                    <span style={{ fontSize: 12, color: "var(--ink-3)" }}>Active</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {confirm && (
        <div onClick={() => setConfirm(null)} style={{
          position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)",
          display: "grid", placeItems: "center", zIndex: 300, padding: 24,
        }}>
          <div onClick={(e) => e.stopPropagation()} style={{
            background: "var(--bg-elev)", borderRadius: 14, width: "min(420px, 100%)",
            border: "1px solid var(--line)", overflow: "hidden",
          }}>
            <div style={{ padding: "22px 26px 16px", borderBottom: "1px solid var(--line)" }}>
              <div className="stat-kicker" style={{ marginBottom: 6 }}>
                {confirm.action === "approve" ? "Approve buyer" : "Deny buyer"}
              </div>
              <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em", marginBottom: 6 }}>
                {confirm.action === "approve" ? "Grant bidding access?" : "Block bidding access?"}
              </div>
              <p style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, margin: 0 }}>
                <strong>{confirm.name}</strong> will be {confirm.action === "approve" ? "able to bid, watchlist, and Buy Now immediately." : "blocked from bidding until you reverse this decision."}
              </p>
            </div>
            <div style={{ padding: "16px 22px", display: "flex", justifyContent: "flex-end", gap: 10 }}>
              <button className="btn btn-secondary" onClick={() => setConfirm(null)}>Cancel</button>
              <button className={confirm.action === "approve" ? "btn btn-primary" : "btn btn-dark"}
                onClick={() => confirm.action === "approve" ? doApprove(confirm.email) : doDeny(confirm.email)}>
                {confirm.action === "approve" ? "Approve" : "Deny"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AdminPage });
