// Dashboard view
function Dashboard({ openTask }) {
  const G = window.Gastronaut;
  const liveActivity = G?.useActivityFeed(mockActivityFeed) || { items: mockActivityFeed, status: "mock" };
  const activityFeed = liveActivity.items;
  const livePreviews = G?.useAgents(null);
  const agentPreviews = (livePreviews && livePreviews.length ? livePreviews : mockAgentPreviews).slice(0, 3);
  const liveQuotes = G?.useQuotes();
  const kpis = G?.useKpis ? G.useKpis(null) : null;
  const now = new Date();
  const dateLabel = `Overview · ${now.toLocaleDateString(undefined, { day: "2-digit", month: "short", year: "numeric" })} · ${now.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}`;
  return (
    <div style={{ padding: "40px 48px 60px", position: "relative" }}>
      <div className="bg-aurora"/>

      <SectionHead
        eyebrow={dateLabel}
        title="Your agentic team, at a glance."
        sub={kpis ? `${kpis.activeAgents} of ${kpis.provisioned} agents live · orchestrated by Prime on VPS w8h8.com · server uptime ${kpis.uptime}.` : "Seven Claude Code agents running on VPS w8h8.com, orchestrated under the Gastronaut charter."}
        action={
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn"><Icon.Filter size={13}/> 24h</button>
            <button className="btn"><Icon.Terminal size={13}/> Open shell</button>
          </div>
        }
      />

      {/* KPI strip — editorial, large numerals */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginTop: 24 }}>
        <Kpi label="Active agents" value={kpis ? String(kpis.activeAgents) : "7"} unit={kpis ? `of ${kpis.provisioned} provisioned` : "of 12 provisioned"} spark={[3,4,4,5,5,6,6,7,7]}/>
        <Kpi label="Tasks completed" value={kpis ? String(kpis.tasksCompleted24h) : "143"} unit="since server start" spark={[8,10,9,12,11,14,13,16,15,18,17,19]}/>
        <Kpi label="Token spend · today" value={kpis?.spendToday || "$41.20"} unit={kpis ? `${(kpis.tokensIn + kpis.tokensOut).toLocaleString()} tokens` : "of $120 budget"} good spark={[4,5,4,5,3,4,3,4,3,3,2,3]} color="var(--gold)"/>
        <Kpi label="Avg load" value={kpis ? Math.round(kpis.loadAvg * 100) + "%" : "—"} unit="across team" live spark={[10,10,11,11,10,12,12,13,13,14,13,14,15]} color="var(--accent)"/>
      </div>

      {/* Two-column grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 14, marginTop: 14 }}>
        {/* Activity stream */}
        <Card style={{ padding: 0 }}>
          <div style={{ padding: "18px 20px 14px", borderBottom: "1px solid var(--line-1)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div className="eyebrow">Live activity</div>
              <div style={{ fontSize: 15, marginTop: 4 }}>System stream</div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span className="dot live"/>
              <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>STREAMING</span>
            </div>
          </div>
          <div style={{ padding: "6px 8px 12px", maxHeight: 360, overflow: "auto" }} className="scroll-y">
            {activityFeed.map((a, i) => (
              <ActivityRow key={i} {...a}/>
            ))}
          </div>
        </Card>

        {/* Right stack */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {/* Trading mini widget — with Privacy Fog */}
          <TradingMini quotes={liveQuotes}/>

          {/* Today's priorities */}
          <Card>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Today · Charter</div>
            <div style={{ fontSize: 14, lineHeight: 1.5, color: "var(--ink-2)", marginBottom: 14 }}>
              <span className="display" style={{ fontSize: 22, color: "var(--ink-1)" }}>Ship the Tadpole landing page </span>
              <span>and monitor the Friday gold fix. Maintain an editorial tone in Creative Director outputs.</span>
            </div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {["landing-v3", "gold-friday-fix", "content-calendar", "incident-p3"].map(t => (
                <span key={t} className="mono" style={{ fontSize: 11, padding: "3px 8px", borderRadius: 4, background: "rgba(255,255,255,0.03)", border: "1px solid var(--line-1)", color: "var(--ink-3)" }}>#{t}</span>
              ))}
            </div>
          </Card>
        </div>
      </div>

      {/* Agent cards row */}
      <div style={{ marginTop: 28 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
          <div>
            <div className="eyebrow">The Team</div>
            <div className="display" style={{ fontSize: 22, marginTop: 4 }}>Sub-agents, by domain</div>
          </div>
          <button className="btn">View all <Icon.ArrowRight size={12}/></button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
          {agentPreviews.map((a) => <AgentCard key={a.name} {...a}/>)}
        </div>
      </div>
    </div>
  );
}

// --- pieces ---

function Kpi({ label, value, delta, unit, spark, color = "var(--accent)", good = false, live = false }) {
  return (
    <Card style={{ padding: 18 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div className="eyebrow">{label}</div>
        {live && <span className="dot live"/>}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginTop: 12 }}>
        <div className="display" style={{ fontSize: 40, lineHeight: 1, color: "var(--ink-1)" }}>{value}</div>
        {delta && (
          <div className="mono" style={{
            fontSize: 11,
            color: good || delta.startsWith("+") ? "var(--good)" : delta === "live" ? color : "var(--danger)",
            padding: "2px 6px", borderRadius: 4,
            border: "1px solid var(--line-1)",
          }}>{delta}</div>
        )}
      </div>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginTop: 10 }}>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{unit}</div>
        {spark && <Sparkline data={spark} color={color} w={72} h={22}/>}
      </div>
    </Card>
  );
}

const mockActivityFeed = [
  { agent: "Market Sentry", color: "gold", action: "Flagged elevated XAG realized vol", time: "2s", detail: "1m vol 38.2% · threshold 35%", level: "warn" },
  { agent: "Creative Director", color: "cyan", action: "Drafted hero copy · landing-v3", time: "28s", detail: "3 variants written · awaiting review", level: "info" },
  { agent: "Research Specialist", color: "cyan", action: "Finished brief: ‘Gastronaut OEM sourcing’", time: "1m", detail: "14 sources · 4 citations pinned", level: "ok" },
  { agent: "Ops Steward", color: "cyan", action: "Rotated VPS backup key", time: "4m", detail: "next rotation · 28 Apr 04:00 UTC", level: "info" },
  { agent: "Market Sentry", color: "gold", action: "Executed paper order · XAU long 0.25", time: "8m", detail: "entry 2,384.10 · stop 2,368.00", level: "info" },
  { agent: "Scribe", color: "cyan", action: "Committed 3 files to claude-code-vps", time: "12m", detail: "feat(sidebar): add pinned agents", level: "ok" },
  { agent: "Research Specialist", color: "cyan", action: "Skimmed 42 papers on agentic evals", time: "19m", detail: "4 relevant · summary queued", level: "info" },
  { agent: "Market Sentry", color: "gold", action: "Daily LBMA fix logged", time: "31m", detail: "AM 2,391.05 · PM pending", level: "info" },
];

function relTime(t) {
  if (!t) return "";
  const s = Math.max(0, (Date.now() - new Date(t).getTime()) / 1000);
  if (s < 1) return "now";
  if (s < 60) return `${Math.floor(s)}s`;
  if (s < 3600) return `${Math.floor(s / 60)}m`;
  if (s < 86400) return `${Math.floor(s / 3600)}h`;
  return `${Math.floor(s / 86400)}d`;
}

function ActivityRow({ agent, color, action, time, t, detail, level }) {
  const displayTime = time ?? relTime(t);
  const dotColor = color === "gold" ? "var(--gold)" : "var(--accent)";
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "10px 1fr auto", gap: 12,
      padding: "10px 12px", alignItems: "flex-start",
      borderRadius: 8,
      cursor: "default",
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.02)"}
    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
    >
      <div style={{
        width: 6, height: 6, borderRadius: "50%", marginTop: 7,
        background: dotColor,
        boxShadow: `0 0 8px ${dotColor}`,
        opacity: level === "warn" ? 1 : 0.85,
      }}/>
      <div>
        <div style={{ fontSize: 13, color: "var(--ink-1)", display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ color: "var(--ink-2)", fontWeight: 500 }}>{agent}</span>
          <span style={{ color: "var(--ink-3)" }}>·</span>
          <span>{action}</span>
          {level === "warn" && <span className="mono" style={{ fontSize: 9.5, padding: "1px 5px", borderRadius: 3, background: "oklch(0.68 0.2 25 / 0.15)", color: "var(--danger)", border: "1px solid oklch(0.68 0.2 25 / 0.3)" }}>ALERT</span>}
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 3 }}>{detail}</div>
      </div>
      <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-4)" }}>{displayTime} ago</div>
    </div>
  );
}

const mockAgentPreviews = [
  { name: "Market Sentry", role: "Markets & risk", status: "live", color: "gold", load: 0.68, tasks: 4, summary: "Watches XAU/XAG tape, flags regime shifts, runs paper orders only." },
  { name: "Creative Director", role: "Brand & copy", status: "working", color: "cyan", load: 0.42, tasks: 2, summary: "Writes landing pages and product decks in the Gastronaut voice." },
  { name: "Research Specialist", role: "Primary research", status: "live", color: "cyan", load: 0.31, tasks: 3, summary: "Reads widely, cites narrowly. Pins sources; never invents numbers." },
];

function AgentCard({ name, role, status, color, load, tasks, summary }) {
  const c = color === "gold" ? "var(--gold)" : "var(--accent)";
  return (
    <Card>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
        <Orb size={44} color={c} small/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, color: "var(--ink-1)" }}>{name}</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{role}</div>
        </div>
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)", padding: "2px 6px", border: "1px solid var(--line-1)", borderRadius: 4 }}>{status.toUpperCase()}</span>
      </div>
      <p style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.55, marginTop: 14, marginBottom: 14 }}>{summary}</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div>
          <div className="eyebrow" style={{ fontSize: 9.5 }}>Load</div>
          <div style={{ marginTop: 6, height: 3, background: "rgba(255,255,255,0.05)", borderRadius: 2, overflow: "hidden" }}>
            <div style={{ width: `${load * 100}%`, height: "100%", background: c, boxShadow: `0 0 8px ${c}` }}/>
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{ fontSize: 9.5 }}>Active tasks</div>
          <div style={{ marginTop: 4, fontSize: 13, fontFamily: "var(--font-mono)" }}>{tasks}</div>
        </div>
      </div>
    </Card>
  );
}

// Orb — our signature node
function Orb({ size = 80, color = "var(--accent)", small = false }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      position: "relative", flex: "none",
      background: `radial-gradient(circle at 35% 30%, ${color}, oklch(0.2 0.05 230) 70%, #06070A 100%)`,
      boxShadow: `0 0 ${size*0.4}px ${color}`,
      border: `1px solid rgba(255,255,255,0.12)`,
    }}>
      <div style={{
        position: "absolute", inset: 2, borderRadius: "50%",
        background: `radial-gradient(circle at 35% 25%, rgba(255,255,255,0.5), transparent 30%)`,
        mixBlendMode: "overlay",
      }}/>
      {!small && (
        <div style={{
          position: "absolute", inset: -6, borderRadius: "50%",
          border: `1px solid ${color}`,
          opacity: 0.2,
          animation: "orbit 14s linear infinite",
        }}/>
      )}
    </div>
  );
}

// Trading mini widget (dashboard) with privacy fog
function TradingMini({ quotes }) {
  const [reveal, setReveal] = useState(false);
  const xau = quotes?.XAU || { price: 2384.10, change: 0.42 };
  const xag = quotes?.XAG || { price: 28.91, change: -0.18 };
  const fmt = (n) => Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const pct = (n) => (n >= 0 ? "+" : "") + Number(n).toFixed(2) + "%";
  return (
    <Card style={{ padding: 0, overflow: "hidden" }}
      onMouseEnter={() => setReveal(true)}
      onMouseLeave={() => setReveal(false)}
    >
      <div style={{ padding: "16px 18px 10px", display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <div>
          <div className="eyebrow" style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="dot gold"/> Trading · Spot
          </div>
          <div style={{ fontSize: 15, marginTop: 4, color: "var(--ink-1)" }}>XAU · XAG · live tape</div>
        </div>
        <button title="Reveal sensitive data" style={{ background: "transparent", border: "none", color: "var(--ink-3)", cursor: "pointer" }}>
          {reveal ? <Icon.Eye size={15}/> : <Icon.EyeOff size={15}/>}
        </button>
      </div>
      <div style={{ position: "relative", padding: "0 18px 16px" }}>
        <div style={{ filter: reveal ? "none" : "blur(7px)", transition: "filter 300ms ease" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <MiniQuote sym="XAU/USD" price={fmt(xau.price)} change={pct(xau.change)} up={xau.change >= 0}/>
            <MiniQuote sym="XAG/USD" price={fmt(xag.price)} change={pct(xag.change)} up={xag.change >= 0}/>
          </div>
          <div style={{ marginTop: 14, height: 52, background: "linear-gradient(90deg, rgba(255,255,255,0.02), transparent)", borderRadius: 6, position: "relative", overflow: "hidden" }}>
            <Sparkline data={[10,12,11,13,14,13,15,16,15,17,18,17,19,18,20,21,20,22]} color="var(--gold)" w={260} h={52}/>
          </div>
          <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 8 }}>
            Astrological transit · Mercury sq. Jupiter · noted, not traded
          </div>
        </div>
        {!reveal && (
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", pointerEvents: "none" }}>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)", padding: "4px 10px", borderRadius: 999, border: "1px solid var(--line-2)", background: "rgba(0,0,0,0.25)" }}>
              hover to reveal
            </div>
          </div>
        )}
      </div>
    </Card>
  );
}

function MiniQuote({ sym, price, change, up }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)", letterSpacing: "0.08em" }}>{sym}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 4 }}>
        <div className="display" style={{ fontSize: 26, color: "var(--ink-1)" }}>{price}</div>
        <div className="mono" style={{ fontSize: 11, color: up ? "var(--good)" : "var(--danger)" }}>{change}</div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.Orb = Orb;
