// Buyer dashboard

function DashboardPage({ onNav, state, inventory, watching, onWatch, userBids, wins, currentUser }) {
  const [tab, setTab] = React.useState("active");
  const [recap, setRecap] = React.useState(null);
  const buyer = currentUser;
  const activity = window.CLEARSPACE_ACTIVITY;

  if (!buyer) {
    return (
      <div className="container" style={{ maxWidth: 520, 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 }}>Buyer portal</div>
        <h1 style={{ fontSize: 30, fontWeight: 600, letterSpacing: "-0.02em", margin: 0, marginBottom: 12 }}>
          Sign in to view your dashboard
        </h1>
        <p style={{ color: "var(--ink-2)", fontSize: 15, lineHeight: 1.6, margin: "0 auto 28px", maxWidth: "42ch" }}>
          Your dashboard tracks active bids, your watchlist, won lots, and order status — all tied to your buyer account.
        </p>
        <div className="row gap-12" style={{ justifyContent: "center" }}>
          <button className="btn btn-primary btn-lg" onClick={() => onNav("login")}>Sign in</button>
          <button className="btn btn-secondary btn-lg" onClick={() => onNav("access-request")}>Create account</button>
        </div>
      </div>
    );
  }

  const myActiveLots = inventory.filter((x) => userBids[x.id]);
  const savedLots = inventory.filter((x) => watching.has(x.id));

  return (
    <div className="container" style={{ padding: "32px 32px 80px" }}>
      {/* Header */}
      <div className="row between" style={{ alignItems: "flex-end", marginBottom: 28, flexWrap: "wrap", gap: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Buyer portal · {buyer.id}</div>
          <h1 className="display" style={{ fontSize: 40, margin: 0 }}>Your dashboard</h1>
          <p style={{ color: "var(--ink-3)", fontSize: 14, margin: "8px 0 0" }}>
            {buyer.company} · Approved buyer since {buyer.memberSince}
          </p>
        </div>
        <button className="btn btn-primary" onClick={() => onNav("inventory")}>
          Browse inventory <IcArrow size={15} />
        </button>
      </div>

      {/* Alerts */}
      <div className="stack-on-mobile" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 32 }}>
        {[
          { k: "Active bids", v: myActiveLots.length, sub: "in progress", pill: null },
          { k: "Outbid", v: activity.filter((a) => a.type === "outbid").length, sub: "needs attention", pill: "amber" },
          { k: "Watching", v: watching.size, sub: "saved lots", pill: null },
          { k: "Won in 2026", v: buyer.wins, sub: "$184,200 total", pill: "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 center">
              <span className="stat-kicker">{s.k}</span>
              {s.pill === "amber" && <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 11 }}>Action</span>}
              {s.pill === "emerald" && <span className="pill pill-emerald" style={{ padding: "2px 8px", fontSize: 11 }}>Good</span>}
            </div>
            <div className="stat-num mono" style={{ fontSize: 30, marginTop: 8 }}>{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 340px", gap: 32 }}>
        <div>
          {/* Tabs */}
          <div className="tabs">
            {[
              { id: "active", label: "Active bids", n: myActiveLots.length },
              { id: "watching", label: "Watching", n: watching.size },
              { id: "won", label: "Won / closed", n: wins.length || buyer.wins },
            ].map((t) => (
              <button key={t.id} className="tab" data-active={tab === t.id} onClick={() => setTab(t.id)}>
                {t.label}
                {t.n != null && <span className="tab-count mono">{t.n}</span>}
              </button>
            ))}
          </div>

          {tab === "active" && (
            <DashTable lots={myActiveLots} onNav={onNav} emptyMsg="No active bids yet. Head to inventory to start bidding."
              emptyAction={() => onNav("inventory")} onWatch={onWatch} watching={watching}
              userBids={userBids} showYourBid />
          )}
          {tab === "watching" && (
            <DashTable lots={savedLots} onNav={onNav} emptyMsg="Nothing saved yet. Tap the bookmark on any listing."
              onWatch={onWatch} watching={watching} userBids={userBids} />
          )}
          {tab === "won" && (
            <WonList wins={wins} onNav={onNav} onOpenRecap={setRecap} />
          )}
        </div>

        {/* Activity feed */}
        <aside>
          <div style={{
            background: "var(--bg-elev)", border: "1px solid var(--line)",
            borderRadius: 12, overflow: "hidden",
          }}>
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>Activity</span>
              <span className="pill pill-primary" style={{ padding: "2px 8px", fontSize: 11 }}>
                <span className="status-dot" /> Live
              </span>
            </div>
            {activity.map((a, i) => (
              <div key={i} style={{ padding: "14px 18px", borderBottom: i < activity.length - 1 ? "1px solid var(--line)" : "none" }}>
                <div className="row gap-10 center" style={{ marginBottom: 6 }}>
                  {a.type === "outbid" && <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 10 }}>Outbid</span>}
                  {a.type === "closing" && <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 10 }}>Closing</span>}
                  {a.type === "new" && <span className="pill pill-primary" style={{ padding: "2px 8px", fontSize: 10 }}>New match</span>}
                  {a.type === "won" && <span className="pill pill-emerald" style={{ padding: "2px 8px", fontSize: 10 }}>Won</span>}
                  <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{a.lot}</span>
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{a.msg}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 6 }}>
                  {Math.round((Date.now() - a.at) / 60000)}m ago
                </div>
              </div>
            ))}
          </div>
        </aside>
      </div>
      {recap && <DealRecapModal win={recap} onClose={() => setRecap(null)} onNav={onNav} />}
    </div>
  );
}

function DashTable({ lots, onNav, onWatch, watching, userBids, showYourBid, emptyMsg, emptyAction }) {
  if (lots.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "60px 20px", border: "1px dashed var(--line)", borderRadius: 12, color: "var(--ink-3)" }}>
        <div style={{ marginBottom: 14 }}>{emptyMsg}</div>
        {emptyAction && <button className="btn btn-secondary btn-sm" onClick={emptyAction}>Browse inventory</button>}
      </div>
    );
  }
  return (
    <div style={{ background: "var(--bg-elev)", border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden" }}>
      {lots.map((item, i) => {
        const cd = { h: Math.floor((item.closesAt - Date.now()) / 3600000) };
        const yourBid = userBids?.[item.id];
        const leading = yourBid && yourBid >= item.currentBid;
        return (
          <div key={item.id} onClick={() => onNav("listing", { id: item.id })}
            style={{
              display: "grid",
              gridTemplateColumns: "80px 1fr 120px 120px 120px 120px",
              alignItems: "center", gap: 16, padding: "14px 18px",
              borderBottom: i < lots.length - 1 ? "1px solid var(--line)" : "none",
              cursor: "pointer",
            }}>
            <img src={item.photos[0]} style={{ width: 80, height: 56, borderRadius: 6, objectFit: "cover" }} />
            <div>
              <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{item.title}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{item.id} · {item.brand}</div>
            </div>
            <div>
              <div className="stat-kicker" style={{ fontSize: 10 }}>Current</div>
              <div className="mono num" style={{ fontSize: 14, fontWeight: 600, color: "var(--emerald)" }}>{fmt$(item.currentBid)}</div>
            </div>
            {showYourBid && (
              <div>
                <div className="stat-kicker" style={{ fontSize: 10 }}>Your bid</div>
                <div className="mono num" style={{ fontSize: 14, fontWeight: 600 }}>{fmt$(yourBid)}</div>
              </div>
            )}
            {!showYourBid && (
              <div>
                <div className="stat-kicker" style={{ fontSize: 10 }}>Buy now</div>
                <div className="mono num" style={{ fontSize: 14 }}>{item.buyNow ? fmt$(item.buyNow) : "—"}</div>
              </div>
            )}
            <div>
              <div className="stat-kicker" style={{ fontSize: 10 }}>Status</div>
              {showYourBid ? (
                leading
                  ? <span className="pill pill-emerald" style={{ padding: "2px 8px", fontSize: 11 }}>Leading</span>
                  : <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 11 }}>Outbid</span>
              ) : (
                <span className="pill" style={{ padding: "2px 8px", fontSize: 11 }}>Watching</span>
              )}
            </div>
            <div>
              <div className="stat-kicker" style={{ fontSize: 10 }}>Closes</div>
              <div className="mono" style={{ fontSize: 13 }}>{cd.h > 24 ? `${Math.floor(cd.h/24)}d ${cd.h%24}h` : `${cd.h}h`}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function WonList({ wins, onNav, onOpenRecap }) {
  const past = [
    { id: "LOT-2799", title: "40× Haworth Fern task chairs", price: 14200, date: "Mar 14, 2026", status: "Delivered" },
    { id: "LOT-2771", title: "Category lot — 60× Steelcase Series 2", price: 10800, date: "Feb 28, 2026", status: "Picked up" },
    { id: "LOT-2754", title: "Premium — Saarinen tulip conference set", price: 3400, date: "Feb 10, 2026", status: "Delivered" },
  ];
  const allWins = [...wins.map((w) => ({ ...w, status: "Awaiting logistics" })), ...past];
  return (
    <div style={{ background: "var(--bg-elev)", border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden" }}>
      {allWins.map((w, i) => (
        <div key={i} style={{
          display: "grid", gridTemplateColumns: "1fr 140px 140px 140px 120px",
          gap: 16, padding: "14px 18px",
          borderBottom: i < allWins.length - 1 ? "1px solid var(--line)" : "none",
          alignItems: "center",
        }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{w.title}</div>
            <div className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{w.id}</div>
          </div>
          <div>
            <div className="stat-kicker" style={{ fontSize: 10 }}>Won at</div>
            <div className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{fmt$(w.price)}</div>
          </div>
          <div>
            <div className="stat-kicker" style={{ fontSize: 10 }}>Date</div>
            <div style={{ fontSize: 13 }}>{w.date}</div>
          </div>
          <div>
            {w.status === "Awaiting logistics"
              ? <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 11 }}>{w.status}</span>
              : <span className="pill pill-emerald" style={{ padding: "2px 8px", fontSize: 11 }}>{w.status}</span>}
          </div>
          <button className="btn btn-secondary btn-sm" onClick={() => onOpenRecap(w)}>View</button>
        </div>
      ))}
    </div>
  );
}

function AccountTab({ buyer }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
      {[
        { t: "Company", rows: [["Name", buyer.company], ["Buyer ID", buyer.id], ["Since", buyer.memberSince], ["Approved by", "Clearspace admin · R. Tanaka"]] },
        { t: "Contact", rows: [["Primary", buyer.name], ["Role", buyer.role], ["Email", "andressa@northfieldinteriors.com"], ["Phone", "(415) 555-0140"]] },
        { t: "Logistics defaults", rows: [["Preferred fulfillment", "Clearspace delivery"], ["Delivery radius", "Bay Area + Sacramento"], ["Dock hours", "Mon–Fri, 7am–3pm"]] },
        { t: "Payment defaults", rows: [["Preferred method", "ACH (net 7)"], ["Billing email", "ap@northfieldinteriors.com"], ["Tax ID", "On file"]] },
      ].map((card) => (
        <div key={card.t} style={{
          background: "var(--bg-elev)", border: "1px solid var(--line)",
          borderRadius: 12, padding: "18px 20px",
        }}>
          <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>{card.t}</div>
          {card.rows.map(([k, v]) => (
            <div key={k} className="row between" style={{ padding: "8px 0", borderBottom: "1px solid var(--line)", fontSize: 13 }}>
              <span style={{ color: "var(--ink-3)" }}>{k}</span>
              <span style={{ color: "var(--ink)", fontWeight: 500 }}>{v}</span>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

function DealRecapModal({ win, onClose, onNav }) {
  const [stage] = React.useState(win.status === "Awaiting logistics" ? "awaiting" : win.status.toLowerCase());

  const timeline = [
    { label: "Auction closed", date: win.date, done: true },
    { label: "Logistics scheduled", date: stage === "awaiting" ? "Pending" : win.date, done: stage !== "awaiting" },
    { label: "Payment settled", date: stage === "awaiting" ? "—" : win.date, done: stage !== "awaiting" },
    { label: "Delivered / picked up", date: win.status === "Delivered" || win.status === "Picked up" ? win.date : "—", done: win.status === "Delivered" || win.status === "Picked up" },
  ];

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)",
      display: "grid", placeItems: "center", zIndex: 200, padding: 24,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--bg-elev)", borderRadius: 14, width: "min(720px, 100%)",
        maxHeight: "90vh", overflow: "auto", border: "1px solid var(--line)",
      }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="stat-kicker">Deal recap</div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>{win.title}</div>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}>
            <IcClose size={16} />
          </button>
        </div>

        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)", display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
          <div>
            <div className="stat-kicker">Won at</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, color: "var(--emerald)" }}>{fmt$(win.price)}</div>
          </div>
          <div>
            <div className="stat-kicker">Lot</div>
            <div className="mono" style={{ fontSize: 14, marginTop: 6 }}>{win.id}</div>
          </div>
          <div>
            <div className="stat-kicker">Status</div>
            <div style={{ marginTop: 6 }}>
              {win.status === "Awaiting logistics"
                ? <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 11 }}>{win.status}</span>
                : <span className="pill pill-emerald" style={{ padding: "2px 8px", fontSize: 11 }}>{win.status}</span>}
            </div>
          </div>
        </div>

        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 14 }}>Timeline</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {timeline.map((t, i) => (
              <div key={i} className="row gap-12 center">
                <div style={{
                  width: 18, height: 18, borderRadius: 999,
                  background: t.done ? "var(--emerald)" : "var(--bg-sunken)",
                  border: `1px solid ${t.done ? "var(--emerald)" : "var(--line)"}`,
                  display: "grid", placeItems: "center", color: "white", flexShrink: 0,
                }}>
                  {t.done && <IcCheck size={11} />}
                </div>
                <div style={{ flex: 1, fontSize: 13, color: t.done ? "var(--ink)" : "var(--ink-3)" }}>{t.label}</div>
                <div className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{t.date}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: "20px 24px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div>
            <div className="stat-kicker">Logistics</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 8, lineHeight: 1.55 }}>
              Clearspace delivery · Bay Area<br />
              ETA window confirmed post-payment<br />
              Contact: clearspace.sols@gmail.com
            </div>
          </div>
          <div>
            <div className="stat-kicker">Payment</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 8, lineHeight: 1.55 }}>
              Method: ACH (net 7)<br />
              Invoice #: INV-{win.id.replace("LOT-", "")}<br />
              {win.status === "Awaiting logistics" ? "Awaiting invoice" : "Settled"}
            </div>
          </div>
        </div>

        <div style={{ padding: "16px 24px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <button className="btn btn-secondary btn-sm" onClick={onClose}>Close</button>
          <button className="btn btn-primary btn-sm">Download recap PDF <IcDownload size={13} /></button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardPage });