// Top nav + shared shell

function TopNav({ page, onNav, toasts, currentUser, onLogout }) {
  const buyer = currentUser;
  const activity = window.CLEARSPACE_ACTIVITY;
  const [accountOpen, setAccountOpen] = React.useState(false);
  const [notifOpen, setNotifOpen] = React.useState(false);
  const isAdmin = !!(buyer && buyer.isAdmin);
  const navLinks = isAdmin
    ? [
        { id: "dashboard", label: "Overview" },
        { id: "inventory", label: "Inventory" },
        { id: "admin", label: "Approvals" },
      ]
    : [
        { id: "home", label: "Home" },
        { id: "inventory", label: "Inventory" },
        ...(buyer ? [{ id: "dashboard", label: "Dashboard" }] : []),
      ];
  const unread = buyer && !isAdmin ? activity.filter((a) => a.type === "outbid" || a.type === "closing").length : 0;
  const initials = buyer ? (buyer.name || buyer.email || "")
    .split(" ").filter(Boolean).slice(0, 2).map((s) => s[0]).join("").toUpperCase() || "B" : "";

  return (
    <>
      <nav className="top-nav">
        <div className="top-nav-inner">
          <a className="clearspace-logo-lockup" href="#" style={{ textDecoration: "none" }} onClick={(e) => { e.preventDefault(); onNav("home"); }}>
            <img src="public/design-assets/logo-02-mark.png" alt="Clearspace logo" />
            <span className="brand-divider"></span>
            <span>
              Clearspace<br />
              <span className="solutions">Solutions</span>
            </span>
          </a>
          <div className="nav-links">
            {navLinks.map((n) => (
              <button key={n.id} className="nav-link" data-active={page === n.id}
                onClick={() => onNav(n.id)}>
                {n.label}
              </button>
            ))}
          </div>
          <div className="nav-actions">
            {/* Notifications (logged-in non-admin only) */}
            {buyer && !isAdmin && (
            <div style={{ position: "relative" }}>
              <button className="btn btn-ghost btn-sm" title="Notifications"
                style={{ width: 36, padding: 0, position: "relative" }}
                onClick={() => setNotifOpen((v) => !v)}>
                <IcBell size={16} />
                {unread > 0 && (
                  <span style={{
                    position: "absolute", top: 5, right: 5,
                    width: 7, height: 7, borderRadius: "50%",
                    background: "var(--primary)", border: "2px solid var(--bg-elev)",
                  }} />
                )}
              </button>
              {notifOpen && (
                <>
                  <div onClick={() => setNotifOpen(false)}
                    style={{ position: "fixed", inset: 0, zIndex: 140 }} />
                  <div style={{
                    position: "absolute", top: "calc(100% + 8px)", right: 0,
                    width: 340, background: "var(--bg-elev)",
                    border: "1px solid var(--line)", borderRadius: 12,
                    boxShadow: "var(--shadow-md)", zIndex: 150, overflow: "hidden",
                  }}>
                    <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <span style={{ fontWeight: 600, fontSize: 14 }}>Notifications</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}
                        onClick={() => {
                          setNotifOpen(false);
                          const inv = window.CLEARSPACE_INVENTORY;
                          if (a.lot && inv && inv.find((x) => x.id === a.lot)) {
                            onNav("listing", { id: a.lot });
                          }
                        }}
                        style={{
                          padding: "12px 16px",
                          borderBottom: i < activity.length - 1 ? "1px solid var(--line)" : "none",
                          cursor: "pointer", transition: "background 120ms",
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-sunken)"}
                        onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                        <div className="row gap-8 center" style={{ marginBottom: 4 }}>
                          {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 soon</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-4)" }}>
                            {Math.round((Date.now() - a.at) / 60000)}m ago
                          </span>
                        </div>
                        <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{a.msg}</div>
                      </div>
                    ))}
                    <div style={{ padding: "10px 16px", borderTop: "1px solid var(--line)", textAlign: "center" }}>
                      <button className="btn btn-ghost btn-sm"
                        onClick={() => { setNotifOpen(false); onNav("dashboard"); }}>
                        View all activity
                      </button>
                    </div>
                  </div>
                </>
              )}
            </div>
            )}

            {buyer ? (
              <div className="account-chip" onClick={() => setAccountOpen(true)} title="Account" style={{ position: "relative" }}>
                <div className="account-avatar" style={isAdmin ? { background: "var(--primary)", color: "#fff" } : buyer.status === "pending" ? { background: "#b45309" } : undefined}>{initials}</div>
                <div className="account-meta">
                  <span className="account-name">{buyer.name}</span>
                  <span className="account-co" style={isAdmin ? { color: "var(--primary)", fontWeight: 600 } : buyer.status === "pending" ? { color: "#b45309", fontWeight: 600 } : undefined}>
                    {isAdmin ? "Clearspace admin" : buyer.status === "pending" ? "Pending review" : (buyer.company || buyer.role || "")}
                  </span>
                </div>
              </div>
            ) : (
              <div className="row gap-8 center">
                <button className="btn btn-ghost btn-sm" onClick={() => onNav("login")}>
                  Sign in
                </button>
                <button className="btn btn-primary btn-sm" onClick={() => onNav("access-request")}>
                  Create account
                </button>
              </div>
            )}
          </div>
        </div>
      </nav>
      <ToastHost toasts={toasts} />
      {accountOpen && buyer && <AccountDrawer buyer={buyer} onClose={() => setAccountOpen(false)} onNav={onNav} onLogout={onLogout} />}
    </>
  );
}

function AccountDrawer({ buyer, onClose, onNav, onLogout }) {
  const initials = (buyer.name || buyer.email || "")
    .split(" ").filter(Boolean).slice(0, 2).map((s) => s[0]).join("").toUpperCase() || "B";
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(15,23,42,0.45)",
      zIndex: 250, display: "flex", justifyContent: "flex-end",
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: "min(460px, 100%)", height: "100%", background: "var(--bg-elev)",
        borderLeft: "1px solid var(--line)", overflow: "auto",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ padding: "22px 26px 18px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div className="row gap-14 center">
            <div style={{ width: 48, height: 48, borderRadius: 999, background: "var(--ink)", color: "var(--bg-elev)", display: "grid", placeItems: "center", fontWeight: 600, fontSize: 16, letterSpacing: "0.02em" }}>{initials}</div>
            <div>
              <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em" }}>{buyer.name}</div>
              <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{[buyer.role, buyer.company].filter(Boolean).join(" · ") || "Buyer"}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 4 }}>{buyer.id} · since {buyer.memberSince}</div>
            </div>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ width: 32, padding: 0 }}>
            <IcX size={16} />
          </button>
        </div>

        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 24, flex: 1 }}>
          <AccountSection title="Contact" rows={[
            ["Email", buyer.email || "—"],
            ["Phone", buyer.phone || "—"],
          ]} />
          <AccountSection title="Company" rows={[
            ["Name", buyer.company || "—"],
            ["Role", buyer.role || "—"],
            ["Channel", buyer.channel || "—"],
            ["Location", buyer.location || "—"],
          ]} />
          <AccountSection title="Account" rows={[
            ["Buyer ID", buyer.id],
            ["Member since", buyer.memberSince],
            ["Status", buyer.status === "pending"
              ? <span className="pill pill-amber" style={{ padding: "2px 8px", fontSize: 11 }}>Pending review</span>
              : buyer.status === "denied"
                ? <span className="pill" style={{ padding: "2px 8px", fontSize: 11, background: "rgba(239,68,68,0.10)", color: "#b42318" }}>Denied</span>
                : <span className="pill pill-primary" style={{ padding: "2px 8px", fontSize: 11 }}>Verified</span>],
          ]} />

          <div style={{ marginTop: "auto", paddingTop: 20, borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
              Need changes? Contact <a href="mailto:clearspace.sols@gmail.com" style={{ color: "var(--ink-2)" }}>clearspace.sols@gmail.com</a>
            </div>
            <div className="row gap-8">
              <button className="btn btn-secondary btn-sm" disabled>Edit details</button>
              <button className="btn btn-ghost btn-sm" onClick={() => { onClose(); onLogout && onLogout(); }}>
                Sign out
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function AccountSection({ title, rows }) {
  return (
    <div>
      <div className="stat-kicker" style={{ marginBottom: 10 }}>{title}</div>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {rows.map(([k, v]) => (
          <div key={k} className="row between" style={{
            fontSize: 13, padding: "9px 0",
            borderBottom: "1px solid var(--line)",
          }}>
            <span style={{ color: "var(--ink-3)" }}>{k}</span>
            <span style={{ color: "var(--ink)", fontWeight: 500 }}>{v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ToastHost({ toasts }) {
  return (
    <div className="toast-host">
      {toasts.map((t) => (
        <div key={t.id} className="toast">
          {t.icon || <IcCheck size={16} />}
          <span>{t.msg}</span>
        </div>
      ))}
    </div>
  );
}

function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="container row between center" style={{ flexWrap: "wrap", gap: 24 }}>
        <div className="row gap-12 center">
          <div className="clearspace-logo-lockup">
            <img src="public/design-assets/logo-02-mark.png" alt="Clearspace logo" />
            <span className="brand-divider"></span>
            <span>
              Clearspace<br />
              <span className="solutions">Solutions</span>
            </span>
          </div>
          <span>· Bay Area office liquidation</span>
        </div>
        <div className="row gap-24" style={{ alignItems: "center" }}>
          <a href="mailto:clearspace.sols@gmail.com">clearspace.sols@gmail.com</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("terms"); }}>Buyer agreement</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("terms"); }}>Terms</a>
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>
          v1.0 · BUY-0142
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { TopNav, Footer, ToastHost, AccountDrawer });
