// Agents / Tasks / Trading / Settings views
const MOCK_AGENTS_VIEW = [
  { name: "Prime", role: "Orchestrator", model: "Sonnet 4.6", status: "live", color: "cyan", load: 0.52, tasks: 12, cost: "$18.40", uptime: "13d 4h" },
  { name: "Market Sentry", role: "Markets & risk", model: "Haiku 4.5", status: "live", color: "gold", load: 0.68, tasks: 4, cost: "$7.10", uptime: "13d 4h" },
  { name: "Creative Director", role: "Brand & copy", model: "Sonnet 4.6", status: "working", color: "cyan", load: 0.42, tasks: 2, cost: "$6.30", uptime: "6d 12h" },
  { name: "Research Specialist", role: "Primary research", model: "Sonnet 4.6", status: "live", color: "cyan", load: 0.31, tasks: 3, cost: "$4.80", uptime: "6d 12h" },
  { name: "Ops Steward", role: "Infra & secrets", model: "Haiku 4.5", status: "idle", color: "cyan", load: 0.08, tasks: 1, cost: "$0.90", uptime: "13d 4h" },
  { name: "Scribe", role: "Git & docs", model: "Haiku 4.5", status: "working", color: "cyan", load: 0.22, tasks: 5, cost: "$1.40", uptime: "3d 2h" },
  { name: "Tape Reader", role: "Tick ingest", model: "Haiku 4.5", status: "live", color: "gold", load: 0.81, tasks: 1, cost: "$2.30", uptime: "13d 4h" },
];

function AgentsView() {
  const G = window.Gastronaut;
  const liveAgents = G?.useAgents ? G.useAgents([]) : [];
  const agents = liveAgents.length ? liveAgents.map(a => ({
    name: a.name,
    role: a.role,
    model: a.model ? a.model.replace("claude-", "").replace(/-/g, " ") : "",
    status: a.status,
    color: a.color,
    load: a.load ?? 0,
    tasks: a.tasksCompleted ?? a.tasks ?? 0,
    cost: a.cost || "$0.00",
    uptime: a.uptime || "—",
  })) : MOCK_AGENTS_VIEW;
  return (
    <div style={{ padding: "40px 48px 60px", position: "relative" }}>
      <div className="bg-aurora"/>
      <SectionHead
        eyebrow="Agents · Roster"
        title="Seven hands. One charter."
        sub="Provision new agents from the Gastronaut template. Each inherits role scopes, secret policies and a cost budget."
        action={<div style={{ display: "flex", gap: 8 }}><button className="btn"><Icon.Filter size={13}/> All roles</button><button className="btn primary"><Icon.Plus size={13}/> Provision agent</button></div>}
      />
      <Card style={{ padding: 0, marginTop: 10, overflow: "hidden" }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: "2fr 1.2fr 0.8fr 0.8fr 1fr 0.8fr 0.8fr 40px",
          padding: "12px 20px",
          borderBottom: "1px solid var(--line-1)",
          fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase",
          color: "var(--ink-3)", fontFamily: "var(--font-mono)",
        }}>
          <div>Agent</div><div>Model</div><div>Status</div><div>Load</div><div>Tasks (24h)</div><div>Cost · today</div><div>Uptime</div><div/>
        </div>
        {agents.map((a, i) => <AgentRow key={i} {...a}/>)}
      </Card>
    </div>
  );
}

function AgentRow({ name, role, model, status, color, load, tasks, cost, uptime }) {
  const c = color === "gold" ? "var(--gold)" : "var(--accent)";
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "2fr 1.2fr 0.8fr 0.8fr 1fr 0.8fr 0.8fr 40px",
        padding: "16px 20px",
        alignItems: "center",
        borderBottom: "1px solid var(--line-1)",
        cursor: "pointer",
      }}
      onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.015)"}
      onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <Orb size={32} color={c} small/>
        <div>
          <div style={{ fontSize: 13.5, color: "var(--ink-1)" }}>{name}</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{role}</div>
        </div>
      </div>
      <div className="mono" style={{ fontSize: 11.5, color: "var(--ink-2)" }}>{model}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        <span className={`dot ${status === "live" ? "live" : ""}`} style={status !== "live" ? { background: status === "idle" ? "var(--ink-4)" : c, boxShadow: "none", opacity: 0.7 } : undefined}/>
        <span style={{ fontSize: 12, color: "var(--ink-2)" }}>{status}</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ flex: 1, height: 2, background: "rgba(255,255,255,0.05)", borderRadius: 2, overflow: "hidden", maxWidth: 80 }}>
          <div style={{ width: `${load * 100}%`, height: "100%", background: c }}/>
        </div>
        <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{Math.round(load*100)}%</span>
      </div>
      <div className="mono" style={{ fontSize: 12 }}>{tasks}</div>
      <div className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>{cost}</div>
      <div className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{uptime}</div>
      <div style={{ color: "var(--ink-3)", display: "grid", placeItems: "center" }}><Icon.More size={14}/></div>
    </div>
  );
}

// ---- Tasks ----
function TasksView({ openTask }) {
  const G = window.Gastronaut;
  const live = !!G?.live;
  const tasks = G?.useTasks ? G.useTasks([]) : [];
  const cols = [
    { title: "Queued",     status: "queued",  items: tasks.filter(t => t.status === "queued") },
    { title: "Running",    status: "running", items: tasks.filter(t => t.status === "running") },
    { title: "Done",       status: "done",    items: tasks.filter(t => t.status === "done") },
    { title: "Error",      status: "error",   items: tasks.filter(t => t.status === "error") },
  ];
  const totalActive = tasks.filter(t => t.status === "queued" || t.status === "running").length;
  return (
    <div style={{ padding: "40px 48px 60px", position: "relative" }}>
      <div className="bg-aurora"/>
      <SectionHead
        eyebrow="Tasks · Kanban"
        title="Work-in-flight."
        sub={live ? `Live from the server — ${tasks.length} task${tasks.length === 1 ? "" : "s"} total, ${totalActive} active. Click any card to see the full conversation.` : "Tasks are atomic units of delegated work. Each carries an owning agent, a scope, and a receipt."}
        action={<div style={{ display: "flex", gap: 8 }}><button className="btn"><Icon.Filter size={13}/> All</button></div>}
      />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginTop: 10 }}>
        {cols.map(c => (
          <div key={c.title}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 4px 10px" }}>
              <div style={{ fontSize: 12, color: "var(--ink-2)" }}>{c.title}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{c.items.length}</div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {c.items.length === 0 && (
                <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-4)", padding: "14px 4px", textAlign: "center", border: "1px dashed var(--line-1)", borderRadius: 8 }}>
                  empty
                </div>
              )}
              {c.items.map((t) => <TaskCard key={t.id} task={t} onOpen={openTask}/>)}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function TaskCard({ task, onOpen }) {
  const color = task.agentColor === "gold" ? "var(--gold)" : "var(--accent)";
  const elapsedMs = task.finishedAt
    ? new Date(task.finishedAt) - new Date(task.createdAt)
    : (task.startedAt ? Date.now() - new Date(task.startedAt) : 0);
  const elapsed = elapsedMs > 0 ? `${Math.round(elapsedMs / 1000)}s` : "";
  return (
    <Card style={{ padding: 14, cursor: "pointer", transition: "border-color 160ms" }}
      onClick={() => onOpen?.(task.id)}
      onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--line-2)"}
      onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--line-1)"}
    >
      <div style={{ fontSize: 13, color: "var(--ink-1)", lineHeight: 1.4, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>
        {task.prompt}
      </div>
      {task.status === "running" && (
        <div style={{ height: 2, background: "rgba(255,255,255,0.05)", borderRadius: 2, overflow: "hidden", marginTop: 12, position: "relative" }}>
          <div style={{ position: "absolute", inset: 0, background: `linear-gradient(90deg, transparent, ${color}, transparent)`, animation: "slide 1.6s linear infinite" }}/>
          <style>{`@keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(100%); } }`}</style>
        </div>
      )}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 5, height: 5, borderRadius: "50%", background: color, boxShadow: `0 0 6px ${color}` }}/>
          <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{task.agentName || task.agentId}</span>
        </div>
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{elapsed || task.priority}</span>
      </div>
    </Card>
  );
}

window.AgentsView = AgentsView;
window.TasksView = TasksView;
