// Admin overview dashboard — site-wide metrics, pending applications, activity.
// Renders at /dashboard when the signed-in user has isAdmin === true.

function AdminDashboard({ onNav, inventory, wins, accounts, setAccountStatus, currentUser }) {
  if (!currentUser || !currentUser.isAdmin) {
    return (
      <div className="container" style={{ maxWidth: 480, textAlign: "center", padding: "100px 24px" }}>
        <p>Admin access only.</p>
      </div>
    );
  }

  const now = Date.now();
  const activeLots = inventory.filter((x) => x.closesAt > now);
  const totalBids = inventory.reduce((s, x) => s + (x.bidCount || 0), 0);
  const totalUnits = activeLots.reduce((s, x) => s + (x.quantity || 0), 0);
  const totalRevenue = wins.reduce((s, w) => s + (w.price || 0), 0);
  const ytdBaseline = 1247800; // demo baseline
  const ytdRevenue = totalRevenue + ytdBaseline;
  const closingSoon = activeLots
    .filter((x) => x.closesAt - now < 1000 * 60 * 60 * 8)
    .sort((a, b) => a.closesAt - b.closesAt)
    .slice(0, 4);

  const pendingApps = Object.values(accounts)
    .map((a) => a.profile)
    .filter((p) => !p.isAdmin && p.status === "pending")
    .sort((a, b) => (b.appliedAt || 0) - (a.appliedAt || 0));

  // Synthesize a recent activity stream from real lot data.
  const activity = inventory
    .filter((x) => x.bidCount > 0)
    .sort((a, b) => (b.currentBid - a.currentBid))
    .slice(0, 6)
    .map((lot, i) => ({
      id: lot.id,
      lot,
      bidder: `Bidder #${(i * 3 + 7) % 12 + 1}`,
      amount: lot.currentBid,
      at: now - (i + 1) * 1000 * 60 * (3 + (i * 7) % 11),
    }));

  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 }}>Admin overview · Clearspace operations</div>
          <h1 className="display" style={{ fontSize: 38, margin: 0 }}>Site dashboard</h1>
          <div style={{ fontSize: 14, color: "var(--ink-3)", marginTop: 6 }}>
            Live operations across all live auctions, buyers, and applications.
          </div>
        </div>
        <div className="row gap-10">
          <button className="btn btn-secondary" onClick={() => onNav("inventory")}>
            View live inventory
          </button>
          <button className="btn btn-primary" onClick={() => onNav("admin")}>
            Buyer approvals {pendingApps.length > 0 && <span className="mono" style={{ marginLeft: 6, padding: "2px 8px", borderRadius: 999, background: "rgba(255,255,255,0.18)", fontSize: 11 }}>{pendingApps.length}</span>}
          </button>
        </div>
      </div>

      {/* Top stat row */}
      <div className="stack-on-mobile" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 32 }}>
        {[
          { k: "Live auctions", v: activeLots.length, sub: `${totalUnits.toLocaleString()} units listed` },
          { k: "Bids placed", v: totalBids, sub: "across all live lots" },
          { k: "Pending approvals", v: pendingApps.length, sub: pendingApps.length > 0 ? "needs review" : "queue clear", pill: pendingApps.length > 0 ? { label: "Action", tone: "amber" } : null },
          { k: "Revenue · 2026 YTD", v: fmt$k(ytdRevenue), sub: `${wins.length} new sales this session`, pill: { label: "Good", tone: "emerald" } },
        ].map((s) => (
          <div key={s.k} style={{
            background: "var(--bg-elev)", border: "1px solid var(--line)",
            borderRadius: 12, padding: "18px 20px",
          }}>
            <div className="row between" style={{ marginBottom: 10 }}>
              <span className="stat-kicker">{s.k}</span>
              {s.pill && (
                <span className={`pill pill-${s.pill.tone}`} style={{ padding: "2px 8px", fontSize: 10 }}>{s.pill.label}</span>
              )}
            </div>
            <div className="mono num" style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em" }}>{s.v}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>{s.sub}</div>
          </div>
        ))}
      </div>

      <div className="stack-on-mobile" style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 32 }}>
        {/* LEFT: closing soon + pending applications */}
        <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>

          {/* Closing soon */}
          <div>
            <div className="row between" style={{ alignItems: "flex-end", marginBottom: 14 }}>
              <div>
                <div className="stat-kicker" style={{ marginBottom: 4 }}>Closing soon</div>
                <h2 style={{ fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em", margin: 0 }}>Auctions ending in &lt; 8 hours</h2>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => onNav("inventory")}>All inventory →</button>
            </div>
            {closingSoon.length === 0 ? (
              <div style={{
                padding: "40px 20px", textAlign: "center", color: "var(--ink-3)",
                border: "1px dashed var(--line)", borderRadius: 12, background: "var(--bg-sunken)", fontSize: 13,
              }}>
                Nothing closing in the next 8 hours.
              </div>
            ) : (
              <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden", background: "var(--bg-elev)" }}>
                {closingSoon.map((lot, i) => {
                  const ms = lot.closesAt - now;
                  const h = Math.floor(ms / 3600000);
                  const m = Math.floor((ms % 3600000) / 60000);
                  const timeLeft = h > 0 ? `${h}h ${String(m).padStart(2, "0")}m` : `${m}m`;
                  return (
                    <div key={lot.id}
                      onClick={() => onNav("listing", { id: lot.id })}
                      style={{
                        display: "grid", gridTemplateColumns: "70px minmax(0, 1fr) 110px 110px 110px",
                        gap: 16, padding: "14px 18px", alignItems: "center", cursor: "pointer",
                        borderBottom: i < closingSoon.length - 1 ? "1px solid var(--line)" : "none",
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-sunken)"}
                      onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                      <img src={lot.photos[0]} alt="" style={{ width: 70, height: 50, objectFit: "cover", borderRadius: 6 }} />
                      <div style={{ minWidth: 0 }}>
                        <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>{lot.id} · {typeLabel(lot.type)}</div>
                        <div style={{ fontSize: 14, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{lot.title}</div>
                      </div>
                      <div>
                        <div className="stat-kicker" style={{ fontSize: 10, marginBottom: 2 }}>Current</div>
                        <div className="mono" style={{ color: "var(--emerald)", fontWeight: 600, fontSize: 14 }}>{fmt$(lot.currentBid)}</div>
                      </div>
                      <div>
                        <div className="stat-kicker" style={{ fontSize: 10, marginBottom: 2 }}>Bids</div>
                        <div className="mono" style={{ fontSize: 14, fontWeight: 500 }}>{lot.bidCount}</div>
                      </div>
                      <div>
                        <div className="stat-kicker" style={{ fontSize: 10, marginBottom: 2 }}>Closes</div>
                        <div className={"mono " + (h < 2 ? "" : "")} style={{ fontSize: 14, fontWeight: 600, color: h < 2 ? "#b45309" : "var(--ink)" }}>{timeLeft}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Pending applications teaser */}
          <div>
            <div className="row between" style={{ alignItems: "flex-end", marginBottom: 14 }}>
              <div>
                <div className="stat-kicker" style={{ marginBottom: 4 }}>Buyer applications</div>
                <h2 style={{ fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em", margin: 0 }}>Pending approval</h2>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => onNav("admin")}>View all →</button>
            </div>
            {pendingApps.length === 0 ? (
              <div style={{
                padding: "40px 20px", textAlign: "center", color: "var(--ink-3)",
                border: "1px dashed var(--line)", borderRadius: 12, background: "var(--bg-sunken)", fontSize: 13,
              }}>
                No pending applications. Queue is clear.
              </div>
            ) : (
              <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden", background: "var(--bg-elev)" }}>
                {pendingApps.slice(0, 4).map((p, i, arr) => {
                  const applied = p.appliedAt
                    ? Math.round((now - p.appliedAt) / (1000 * 60 * 60)) + "h ago"
                    : "—";
                  return (
                    <div key={p.email} style={{
                      display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1.4fr) 100px 180px",
                      gap: 14, padding: "14px 18px", alignItems: "center",
                      borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
                    }}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</div>
                        <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>{p.id} · {applied}</div>
                      </div>
                      <div style={{ minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{p.company}</div>
                        <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.channel || "—"}</div>
                      </div>
                      <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.location || "—"}</div>
                      <div className="row gap-6" style={{ justifyContent: "flex-end" }}>
                        <button className="btn btn-primary btn-sm" onClick={() => setAccountStatus(p.email, "approved")}>Approve</button>
                        <button className="btn btn-secondary btn-sm" onClick={() => setAccountStatus(p.email, "denied")}>Deny</button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        {/* RIGHT: live activity */}
        <aside>
          <div style={{
            background: "var(--bg-elev)", border: "1px solid var(--line)",
            borderRadius: 12, overflow: "hidden", position: "sticky", top: 88,
          }}>
            <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div className="stat-kicker">Recent bids</div>
              <span className="pill pill-primary" style={{ padding: "2px 8px", fontSize: 10 }}>
                <span className="status-dot" /> Live
              </span>
            </div>
            {activity.length === 0 ? (
              <div style={{ padding: "30px 18px", textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
                No bid activity yet.
              </div>
            ) : (
              activity.map((a, i) => (
                <div key={a.id} style={{
                  padding: "12px 18px",
                  borderBottom: i < activity.length - 1 ? "1px solid var(--line)" : "none",
                  cursor: "pointer", transition: "background 120ms",
                }}
                  onClick={() => onNav("listing", { id: a.lot.id })}
                  onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-sunken)"}
                  onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                  <div className="row between" style={{ marginBottom: 4 }}>
                    <span className="mono" style={{ fontWeight: 600, fontSize: 14, color: "var(--emerald)" }}>{fmt$(a.amount)}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>{relTimeAd(a.at)}</span>
                  </div>
                  <div style={{ fontSize: 12, color: "var(--ink-2)" }}>
                    {a.bidder} on <span className="mono" style={{ color: "var(--ink)" }}>{a.lot.id}</span>
                  </div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginTop: 2 }}>
                    {a.lot.title}
                  </div>
                </div>
              ))
            )}
            <div style={{ padding: "10px 16px", borderTop: "1px solid var(--line)", textAlign: "center" }}>
              <button className="btn btn-ghost btn-sm" onClick={() => onNav("inventory")}>
                View all lots
              </button>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function relTimeAd(ts) {
  const d = Date.now() - ts;
  const s = Math.floor(d / 1000);
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

Object.assign(window, { AdminDashboard });
