import { useState } from "react";

const styles = `
  @import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&family=DM+Mono:wght@400;500&display=swap');
  * { margin: 0; padding: 0; box-sizing: border-box; }
  :root {
    --bg: #0d1117; --surface: #161b22; --surface2: #1c2330; --border: #21262d;
    --teal: #2dd4bf; --teal-dark: #0d9488; --indigo: #818cf8; --muted: #5a7a96;
    --text: #cdd9e5; --text-dim: #8b949e; --red: #f85149; --amber: #d29922; --green: #3fb950;
  }
  body { background: var(--bg); color: var(--text); font-family: 'DM Sans', sans-serif; overflow: hidden; }
  .shell { display: flex; height: 100vh; overflow: hidden; }

  /* SIDEBAR */
  .sidebar { width: 210px; min-width: 210px; background: var(--surface); border-right: 1px solid var(--border); display: flex; flex-direction: column; }
  .logo-area { padding: 18px 16px 14px; border-bottom: 1px solid var(--border); }
  .logo-word { font-family: 'Syne', sans-serif; font-weight: 800; font-size: 17px; color: var(--teal); letter-spacing: -0.5px; }
  .logo-sub { font-family: 'DM Mono', monospace; font-size: 9px; color: var(--muted); letter-spacing: 2.5px; text-transform: uppercase; margin-top: 2px; }
  .nav { padding: 10px 8px; flex: 1; }
  .nav-section { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); padding: 10px 8px 5px; }
  .nav-item { display: flex; align-items: center; gap: 9px; padding: 7px 9px; border-radius: 5px; font-size: 12.5px; color: var(--text-dim); cursor: pointer; margin-bottom: 1px; border: none; background: none; width: 100%; text-align: left; transition: all 0.12s; }
  .nav-item:hover { background: var(--surface2); color: var(--text); }
  .nav-item.active { background: rgba(45,212,191,0.08); color: var(--teal); }
  .nav-dot { width: 5px; height: 5px; border-radius: 50%; background: var(--muted); flex-shrink: 0; }
  .nav-item.active .nav-dot { background: var(--teal); box-shadow: 0 0 5px var(--teal); }

  /* MAIN */
  .main { flex: 1; display: flex; flex-direction: column; overflow: hidden; min-width: 0; }
  .topbar { height: 50px; border-bottom: 1px solid var(--border); display: flex; align-items: center; padding: 0 18px; gap: 10px; background: var(--surface); flex-shrink: 0; }
  .topbar-title { font-family: 'Syne', sans-serif; font-weight: 700; font-size: 13.5px; color: var(--text); flex: 1; }
  .badge { font-family: 'DM Mono', monospace; font-size: 10px; padding: 2px 7px; border-radius: 3px; }
  .badge-teal { background: rgba(45,212,191,0.1); color: var(--teal); border: 1px solid rgba(45,212,191,0.2); }
  .badge-red { background: rgba(248,81,73,0.1); color: var(--red); border: 1px solid rgba(248,81,73,0.2); }
  .badge-amber { background: rgba(210,153,34,0.1); color: var(--amber); border: 1px solid rgba(210,153,34,0.2); }
  .badge-muted { background: rgba(90,122,150,0.1); color: var(--muted); border: 1px solid rgba(90,122,150,0.15); }
  .live-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--green); margin-right: 6px; animation: pulse 1.5s infinite; }
  @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }

  /* LAYOUT: left=session list, right=trace detail */
  .content { flex: 1; display: flex; overflow: hidden; min-height: 0; }

  /* SESSION LIST */
  .session-list { width: 320px; min-width: 320px; border-right: 1px solid var(--border); display: flex; flex-direction: column; overflow: hidden; }
  .list-header { padding: 10px 14px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 8px; background: var(--bg); flex-shrink: 0; }
  .list-header-title { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); flex: 1; }
  .filter-chip { font-family: 'DM Mono', monospace; font-size: 10px; padding: 3px 9px; border-radius: 12px; border: 1px solid var(--border); background: none; color: var(--text-dim); cursor: pointer; transition: all 0.12s; }
  .filter-chip.active, .filter-chip:hover { border-color: var(--teal); color: var(--teal); background: rgba(45,212,191,0.06); }
  .session-scroll { flex: 1; overflow-y: auto; }
  .session-scroll::-webkit-scrollbar { width: 4px; }
  .session-scroll::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }

  .session-card { padding: 12px 14px; border-bottom: 1px solid rgba(33,38,45,0.7); cursor: pointer; transition: background 0.1s; position: relative; }
  .session-card:hover { background: rgba(22,27,34,0.6); }
  .session-card.active { background: rgba(45,212,191,0.04); border-left: 2px solid var(--teal); padding-left: 12px; }
  .sc-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px; }
  .sc-agent { font-weight: 500; font-size: 13px; color: var(--text); }
  .sc-time { font-family: 'DM Mono', monospace; font-size: 10px; color: var(--muted); }
  .sc-id { font-family: 'DM Mono', monospace; font-size: 10px; color: var(--teal); margin-bottom: 5px; }
  .sc-meta { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
  .sc-pill { font-family: 'DM Mono', monospace; font-size: 9px; padding: 1px 6px; border-radius: 3px; border: 1px solid; }
  .pill-ok { color: var(--green); border-color: rgba(63,185,80,0.3); background: rgba(63,185,80,0.05); }
  .pill-blocked { color: var(--red); border-color: rgba(248,81,73,0.3); background: rgba(248,81,73,0.05); }
  .pill-warn { color: var(--amber); border-color: rgba(210,153,34,0.3); background: rgba(210,153,34,0.05); }
  .sc-stats { display: flex; gap: 10px; margin-top: 6px; }
  .sc-stat { font-family: 'DM Mono', monospace; font-size: 9px; color: var(--muted); }
  .sc-stat span { color: var(--text-dim); }

  /* TRACE DETAIL */
  .trace-detail { flex: 1; display: flex; flex-direction: column; overflow: hidden; min-width: 0; }

  .trace-status-bar { padding: 12px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 28px; background: var(--surface); flex-shrink: 0; }
  .tsb-item { display: flex; flex-direction: column; gap: 2px; }
  .tsb-label { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); }
  .tsb-val { font-family: 'Syne', sans-serif; font-weight: 700; font-size: 18px; letter-spacing: -0.5px; }
  .tsb-ok { color: var(--green); }
  .tsb-blocked { color: var(--red); }
  .tsb-warn { color: var(--amber); }
  .tsb-teal { color: var(--teal); }
  .tsb-divider { width: 1px; height: 32px; background: var(--border); }

  .trace-toolbar { padding: 8px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 8px; background: var(--bg); flex-shrink: 0; }
  .tt-label { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); flex: 1; }
  .tt-btn { font-family: 'DM Mono', monospace; font-size: 10px; padding: 4px 10px; border-radius: 4px; border: 1px solid var(--border); background: none; color: var(--text-dim); cursor: pointer; transition: all 0.12s; }
  .tt-btn:hover, .tt-btn.active { border-color: var(--teal); color: var(--teal); background: rgba(45,212,191,0.05); }

  /* WATERFALL */
  .waterfall-wrap { flex: 1; overflow-y: auto; overflow-x: hidden; }
  .waterfall-wrap::-webkit-scrollbar { width: 5px; }
  .waterfall-wrap::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }

  .wf-header { display: flex; align-items: center; padding: 6px 20px; border-bottom: 1px solid var(--border); position: sticky; top: 0; background: var(--bg); z-index: 10; }
  .wf-h-name { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); width: 320px; min-width: 320px; }
  .wf-h-latency { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); width: 60px; text-align: right; margin-right: 12px; }
  .wf-h-bar { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); flex: 1; }

  /* SPAN ROW */
  .span-row { display: flex; align-items: center; padding: 0 20px; min-height: 34px; border-bottom: 1px solid rgba(33,38,45,0.4); cursor: pointer; transition: background 0.08s; position: relative; }
  .span-row:hover { background: rgba(22,27,34,0.7); }
  .span-row.selected-span { background: rgba(45,212,191,0.04); }

  .span-name-col { width: 320px; min-width: 320px; display: flex; align-items: center; gap: 0; padding: 6px 0; }
  .span-indent { display: flex; align-items: center; }
  .indent-line { width: 16px; height: 100%; border-left: 1px solid rgba(33,38,45,0.8); margin-left: 8px; flex-shrink: 0; }
  .indent-connector { width: 16px; flex-shrink: 0; position: relative; }
  .indent-connector::before { content: ''; position: absolute; left: 0; top: 50%; width: 10px; height: 1px; background: rgba(33,38,45,0.8); }

  .span-chevron { width: 16px; height: 16px; display: flex; align-items: center; justify-content: center; border-radius: 3px; margin-right: 4px; flex-shrink: 0; transition: transform 0.15s; cursor: pointer; color: var(--muted); font-size: 10px; }
  .span-chevron.open { transform: rotate(0deg); }
  .span-chevron.closed { transform: rotate(-90deg); }
  .span-chevron.leaf { opacity: 0; pointer-events: none; }

  .span-icon { width: 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-size: 10px; flex-shrink: 0; margin-right: 7px; }
  .si-agent { background: rgba(45,212,191,0.15); color: var(--teal); }
  .si-tool { background: rgba(129,140,248,0.15); color: var(--indigo); }
  .si-llm { background: rgba(210,153,34,0.15); color: var(--amber); }
  .si-block { background: rgba(248,81,73,0.15); color: var(--red); }
  .si-chain { background: rgba(90,122,150,0.12); color: var(--muted); }
  .si-handoff { background: rgba(129,140,248,0.1); color: var(--indigo); }
  .si-embed { background: rgba(63,185,80,0.1); color: var(--green); }

  .span-name { font-size: 12.5px; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 180px; }
  .span-name.blocked { color: var(--red); }
  .span-name.warn { color: var(--amber); }

  .span-tokens { font-family: 'DM Mono', monospace; font-size: 10px; color: var(--muted); margin-left: 6px; white-space: nowrap; }

  .span-latency-col { width: 60px; min-width: 60px; text-align: right; margin-right: 12px; }
  .span-latency { font-family: 'DM Mono', monospace; font-size: 11px; color: var(--text-dim); white-space: nowrap; }
  .span-latency.slow { color: var(--amber); }

  .span-bar-col { flex: 1; display: flex; align-items: center; gap: 8px; min-width: 0; }
  .span-bar-track { flex: 1; height: 5px; background: rgba(33,38,45,0.8); border-radius: 3px; overflow: hidden; position: relative; }
  .span-bar-fill { height: 100%; border-radius: 3px; transition: width 0.3s; }

  /* SPAN DETAIL DRAWER */
  .span-drawer { border-top: 1px solid var(--border); background: var(--surface); flex-shrink: 0; overflow: hidden; transition: max-height 0.2s ease; }
  .drawer-inner { display: flex; gap: 0; max-height: 260px; overflow: hidden; }
  .drawer-section { flex: 1; padding: 14px 18px; border-right: 1px solid var(--border); overflow-y: auto; min-width: 0; }
  .drawer-section:last-child { border-right: none; }
  .drawer-section::-webkit-scrollbar { width: 3px; }
  .drawer-section::-webkit-scrollbar-thumb { background: var(--border); }
  .ds-label { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); margin-bottom: 10px; padding-bottom: 5px; border-bottom: 1px solid var(--border); }
  .kv { display: flex; justify-content: space-between; padding: 3px 0; gap: 10px; }
  .kv-k { font-family: 'DM Mono', monospace; font-size: 10px; color: var(--muted); flex-shrink: 0; }
  .kv-v { font-family: 'DM Mono', monospace; font-size: 10px; color: var(--text); text-align: right; word-break: break-all; }
  .kv-v.teal { color: var(--teal); }
  .kv-v.red { color: var(--red); }
  .kv-v.amber { color: var(--amber); }
  .code-pre { font-family: 'DM Mono', monospace; font-size: 10px; color: var(--text-dim); line-height: 1.55; background: var(--bg); border: 1px solid var(--border); border-radius: 5px; padding: 8px 10px; white-space: pre-wrap; word-break: break-all; }
`;

// ── Span tree data ──────────────────────────────────────────────────────────
const makeTree = () => [
  {
    id: "s0", kind: "chain", name: "PlannerAgent.run", latencyMs: 12400, pct: 100, tokens: null,
    input: "Plan research pipeline for EV sector market analysis",
    output: "Decomposed into 4 subtasks: retrieval, sentiment, financials, synthesis",
    meta: { framework: "LangGraph", trace_id: "trc_9f2a1b3c", session: "sess_marathon_01" },
    children: [
      {
        id: "s1", kind: "llm", name: "llm.intent_parse", latencyMs: 740, pct: 6, tokens: "↑312 ↓88",
        input: "Parse user intent and extract task structure from: 'Plan research pipeline...'",
        output: '{"intent":"research_pipeline","domain":"EV sector","subtasks":4}',
        meta: { model: "claude-3-5-sonnet-20241022", temperature: "0.2", stop_reason: "end_turn" },
        children: []
      },
      {
        id: "s2", kind: "agent", name: "planner.decompose", latencyMs: 980, pct: 8, tokens: null,
        input: "Break high-level goal into subtasks with dependencies",
        output: "Task graph: [retrieval→sentiment, retrieval→financials, sentiment+financials→synthesis]",
        meta: { pattern: "ReAct", iterations: "2" },
        children: [
          {
            id: "s2a", kind: "llm", name: "llm.task_graph", latencyMs: 860, pct: 7, tokens: "↑540 ↓210",
            input: "Generate task dependency graph for: market analysis pipeline",
            output: "4-node DAG with 3 edges, no cycles detected",
            meta: { model: "claude-3-5-sonnet-20241022", temperature: "0", stop_reason: "end_turn" },
            children: []
          }
        ]
      },
      {
        id: "s3", kind: "tool", name: "web_search", latencyMs: 3100, pct: 25, tokens: null,
        input: "EV sector market overview 2024 TAM growth projections",
        output: "14 results · top: Bloomberg EV Report, McKinsey 2024, IEA Global EV Outlook",
        meta: { provider: "SerpAPI", results: "14", cached: "false" },
        children: [
          {
            id: "s3a", kind: "embed", name: "embed.results", latencyMs: 210, pct: 2, tokens: "↑1,240",
            input: "14 search result snippets",
            output: "Vectors stored: 14 · dim: 1536",
            meta: { model: "text-embedding-3-small", store: "~/.plyra/vectors.db" },
            children: []
          }
        ]
      },
      {
        id: "s4", kind: "tool", name: "web_fetch", latencyMs: 1800, pct: 14, tokens: null,
        input: "https://iea.org/reports/global-ev-outlook-2024",
        output: "Fetched 48kb · extracted 3,200 tokens of relevant content",
        meta: { status: "200", content_type: "text/html", size: "48kb" },
        children: []
      },
      {
        id: "s5", kind: "llm", name: "llm.synthesize_research", latencyMs: 2200, pct: 18, tokens: "↑3,800 ↓620",
        input: "Synthesize: web search results + IEA report → structured research memo",
        output: "Research memo: 620 tokens · 4 sections · 3 key findings flagged",
        meta: { model: "claude-3-5-sonnet-20241022", temperature: "0.3", stop_reason: "end_turn" },
        children: []
      },
      {
        id: "s6", kind: "handoff", name: "handoff → ExecutorAgent", latencyMs: 42, pct: 0.3, tokens: null,
        input: "Task bundle: {subtasks: 4, context_tokens: 980, priority: high}",
        output: "Handoff acknowledged · trace context propagated · child trace: trc_exec_001",
        meta: { to_agent: "ExecutorAgent", protocol: "async", propagation: "W3C TraceContext" },
        children: []
      },
      {
        id: "s7", kind: "agent", name: "ExecutorAgent.run", latencyMs: 2800, pct: 23, tokens: null,
        input: "Execute subtask: financial data retrieval for EV sector",
        output: "PARTIAL: 2/3 tools succeeded, 1 blocked by policy",
        meta: { framework: "LangGraph", parent_trace: "trc_9f2a1b3c" },
        children: [
          {
            id: "s7a", kind: "tool", name: "db.query", latencyMs: 340, pct: 3, tokens: null,
            input: "SELECT * FROM market_data WHERE sector='EV' AND year=2024",
            output: "42 rows returned · 8.2kb",
            meta: { db: "PostgreSQL", rows: "42", latency_db: "12ms" },
            children: []
          },
          {
            id: "s7b", kind: "tool", name: "api.financial_data", latencyMs: 890, pct: 7, tokens: null,
            input: "GET /v1/market/EV/summary?period=2024&metrics=revenue,growth,players",
            output: "{ revenue: $388B, growth: 24.3%, top_players: [...] }",
            meta: { provider: "FinancialModelingPrep", status: "200", cost: "$0.002" },
            children: []
          },
          {
            id: "s7c", kind: "block", name: "guard.evaluate", latencyMs: 68, pct: 0.5, tokens: null,
            input: "Tool: db.bulk_delete · args: {table: 'stale_cache', rows: 'ALL', confirm: false}",
            output: "BLOCKED · policy: no_unconfirmed_deletes · action: escalate · ref: POL-004",
            meta: { policy_file: "policy.yaml", rule: "no_unconfirmed_deletes", action: "escalate", escalated_to: "human" },
            children: []
          },
          {
            id: "s7d", kind: "llm", name: "llm.financial_analysis", latencyMs: 1420, pct: 11, tokens: "↑2,100 ↓480",
            input: "Analyze financial data: {revenue, growth, market_share} for EV sector 2024",
            output: "Analysis complete: 3 insights, 2 risks identified, confidence: 0.87",
            meta: { model: "gpt-4o", temperature: "0.1", stop_reason: "end_turn" },
            children: []
          }
        ]
      },
      {
        id: "s8", kind: "agent", name: "SentimentAgent.run", latencyMs: 1940, pct: 16, tokens: null,
        input: "Analyse EV sector sentiment from fetched web content",
        output: "Sentiment: positive (0.72) · sources: 12 · conflicting signals: 2",
        meta: { framework: "Plain Python", model: "claude-3-haiku" },
        children: [
          {
            id: "s8a", kind: "llm", name: "llm.sentiment_score", latencyMs: 1820, pct: 15, tokens: "↑2,800 ↓140",
            input: "Score sentiment across 14 documents for EV sector. Return JSON.",
            output: '{"overall": 0.72, "bullish_signals": 9, "bearish_signals": 3, "neutral": 2}',
            meta: { model: "claude-3-haiku-20240307", temperature: "0", stop_reason: "end_turn" },
            children: []
          }
        ]
      },
      {
        id: "s9", kind: "llm", name: "llm.final_report", latencyMs: 1890, pct: 15, tokens: "↑4,200 ↓890",
        input: "Generate final analyst report from: research memo + financial analysis + sentiment score",
        output: "Report: 890 tokens · 5 sections · executive summary · 3 recommendations",
        meta: { model: "claude-3-5-sonnet-20241022", temperature: "0.4", stop_reason: "end_turn" },
        children: []
      },
      {
        id: "s10", kind: "tool", name: "file.write", latencyMs: 88, pct: 0.7, tokens: null,
        input: "report_ev_market_2024.md · 18.4kb",
        output: "Written to ~/.plyra/outputs/report_ev_market_2024.md",
        meta: { path: "~/.plyra/outputs/", size: "18.4kb", format: "markdown" },
        children: []
      }
    ]
  }
];

const SESSIONS = [
  { id: "trc_9f2a1b3c", agent: "PlannerAgent", session: "sess_marathon_01", framework: "LangGraph", status: "warn", latency: "12.4s", tokens: "15.8k", spans: 18, time: "2m ago" },
  { id: "trc_3d8e2f4a", agent: "ExecutorAgent", session: "sess_marathon_01", framework: "LangGraph", status: "blocked", latency: "1.2s", tokens: "890", spans: 4, time: "3m ago" },
  { id: "trc_7c1b9e0d", agent: "CoderAgent", session: "sess_coding_44", framework: "AutoGen", status: "ok", latency: "8.1s", tokens: "6.1k", spans: 9, time: "9m ago" },
  { id: "trc_0a4f6c8b", agent: "ResearchAgent", session: "sess_research_12", framework: "CrewAI", status: "ok", latency: "5.2s", tokens: "9.8k", spans: 14, time: "16m ago" },
  { id: "trc_5e2d7a1f", agent: "ReviewAgent", session: "sess_coding_44", framework: "Python", status: "ok", latency: "2.8s", tokens: "2.4k", spans: 6, time: "23m ago" },
];

const KIND_COLOR = { agent: "#2dd4bf", tool: "#818cf8", llm: "#d29922", block: "#f85149", chain: "#5a7a96", handoff: "#818cf8", embed: "#3fb950" };
const KIND_ICON = { agent: "◈", tool: "⬡", llm: "◎", block: "⊗", chain: "◻", handoff: "⇢", embed: "⊛" };
const KIND_CLASS = { agent: "si-agent", tool: "si-tool", llm: "si-llm", block: "si-block", chain: "si-chain", handoff: "si-handoff", embed: "si-embed" };

function SpanRow({ span, depth, collapsed, onToggle, onSelect, isSelected }) {
  const hasChildren = span.children && span.children.length > 0;
  const color = KIND_COLOR[span.kind] || "#5a7a96";
  const isSlow = span.latencyMs > 2000;
  const isBlocked = span.kind === "block";

  const latencyStr = span.latencyMs >= 1000
    ? `${(span.latencyMs / 1000).toFixed(1)}s`
    : `${span.latencyMs}ms`;

  return (
    <div
      className={`span-row ${isSelected ? "selected-span" : ""}`}
      onClick={() => onSelect(span)}
    >
      {/* Name column */}
      <div className="span-name-col">
        {/* Indentation */}
        {Array.from({ length: depth }).map((_, i) => (
          <div key={i} style={{ width: 20, flexShrink: 0, height: 34, borderLeft: i === depth - 1 ? "1px solid rgba(33,38,45,0.7)" : "1px solid rgba(33,38,45,0.4)", marginLeft: i === 0 ? 0 : 0 }} />
        ))}
        {depth > 0 && (
          <div style={{ width: 12, height: 1, background: "rgba(33,38,45,0.7)", flexShrink: 0, marginLeft: -1 }} />
        )}

        {/* Chevron */}
        <div
          className={`span-chevron ${!hasChildren ? "leaf" : collapsed ? "closed" : "open"}`}
          onClick={e => { e.stopPropagation(); onToggle(span.id); }}
        >
          ▾
        </div>

        {/* Icon */}
        <div className={`span-icon ${KIND_CLASS[span.kind]}`}>
          {KIND_ICON[span.kind]}
        </div>

        {/* Name */}
        <span className={`span-name ${isBlocked ? "blocked" : ""}`}>{span.name}</span>
        {span.tokens && <span className="span-tokens">{span.tokens}</span>}
      </div>

      {/* Latency */}
      <div className="span-latency-col">
        <span className={`span-latency ${isSlow ? "slow" : ""}`}>{latencyStr}</span>
      </div>

      {/* Bar */}
      <div className="span-bar-col">
        <div className="span-bar-track">
          <div
            className="span-bar-fill"
            style={{
              width: `${Math.max(span.pct, 1)}%`,
              background: isBlocked
                ? "linear-gradient(90deg, #7f1d1d, #f85149)"
                : `linear-gradient(90deg, ${color}88, ${color})`,
            }}
          />
        </div>
      </div>
    </div>
  );
}

function renderTree(nodes, depth, collapsedMap, onToggle, onSelect, selectedId) {
  const rows = [];
  for (const node of nodes) {
    rows.push(
      <SpanRow
        key={node.id}
        span={node}
        depth={depth}
        collapsed={!!collapsedMap[node.id]}
        onToggle={onToggle}
        onSelect={onSelect}
        isSelected={selectedId === node.id}
      />
    );
    if (node.children && node.children.length > 0 && !collapsedMap[node.id]) {
      rows.push(...renderTree(node.children, depth + 1, collapsedMap, onToggle, onSelect, selectedId));
    }
  }
  return rows;
}

export default function PlyrTraceDeep() {
  const [activeSession, setActiveSession] = useState(SESSIONS[0]);
  const [collapsed, setCollapsed] = useState({});
  const [selectedSpan, setSelectedSpan] = useState(null);
  const [filter, setFilter] = useState("all");
  const tree = makeTree();

  const toggle = (id) => setCollapsed(c => ({ ...c, [id]: !c[id] }));
  const selectSpan = (span) => setSelectedSpan(s => s?.id === span.id ? null : span);

  const filtered = filter === "all" ? SESSIONS : SESSIONS.filter(s => s.status === filter);

  const statusColor = { ok: "tsb-ok", blocked: "tsb-blocked", warn: "tsb-warn" };
  const statusLabel = { ok: "✓ OK", blocked: "⊗ BLOCKED", warn: "⚠ WARN" };
  const pillClass = { ok: "pill-ok", blocked: "pill-blocked", warn: "pill-warn" };

  return (
    <>
      <style>{styles}</style>
      <div className="shell">
        {/* SIDEBAR */}
        <div className="sidebar">
          <div className="logo-area">
            <div className="logo-word">plyra</div>
            <div className="logo-sub">trace</div>
          </div>
          <div className="nav">
            <div className="nav-section">observe</div>
            {["Traces", "Sessions", "Agents", "Tools"].map((item, i) => (
              <button key={item} className={`nav-item ${i === 0 ? "active" : ""}`}>
                <span className="nav-dot" />{item}
              </button>
            ))}
            <div className="nav-section">analyze</div>
            {["Graph View", "Spans", "Policies"].map(item => (
              <button key={item} className="nav-item">
                <span className="nav-dot" />{item}
              </button>
            ))}
            <div className="nav-section">system</div>
            {["Settings", "Exporters"].map(item => (
              <button key={item} className="nav-item">
                <span className="nav-dot" />{item}
              </button>
            ))}
          </div>
        </div>

        {/* MAIN */}
        <div className="main">
          <div className="topbar">
            <div className="topbar-title"><span className="live-dot" />Trace Explorer</div>
            <span className="badge badge-teal">v0.1.0</span>
            <span className="badge badge-muted">localhost:7432</span>
          </div>

          <div className="content">
            {/* SESSION LIST */}
            <div className="session-list">
              <div className="list-header">
                <span className="list-header-title">traces</span>
                {["all","ok","blocked"].map(f => (
                  <button key={f} className={`filter-chip ${filter === f ? "active" : ""}`} onClick={() => setFilter(f)}>{f}</button>
                ))}
              </div>
              <div className="session-scroll">
                {filtered.map(s => (
                  <div
                    key={s.id}
                    className={`session-card ${activeSession.id === s.id ? "active" : ""}`}
                    onClick={() => setActiveSession(s)}
                  >
                    <div className="sc-top">
                      <span className="sc-agent">{s.agent}</span>
                      <span className="sc-time">{s.time}</span>
                    </div>
                    <div className="sc-id">{s.id}</div>
                    <div className="sc-meta">
                      <span className={`sc-pill ${pillClass[s.status]}`}>{s.status}</span>
                      <span className="badge badge-muted" style={{ fontSize: 9 }}>{s.framework}</span>
                    </div>
                    <div className="sc-stats">
                      <span className="sc-stat">latency <span>{s.latency}</span></span>
                      <span className="sc-stat">tokens <span>{s.tokens}</span></span>
                      <span className="sc-stat">spans <span>{s.spans}</span></span>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* TRACE DETAIL */}
            <div className="trace-detail">
              {/* Status bar */}
              <div className="trace-status-bar">
                <div className="tsb-item">
                  <span className="tsb-label">Trace Status</span>
                  <span className={`tsb-val ${statusColor[activeSession.status]}`}>{statusLabel[activeSession.status]}</span>
                </div>
                <div className="tsb-divider" />
                <div className="tsb-item">
                  <span className="tsb-label">Total Latency</span>
                  <span className="tsb-val tsb-teal">{activeSession.latency}</span>
                </div>
                <div className="tsb-divider" />
                <div className="tsb-item">
                  <span className="tsb-label">Total Tokens</span>
                  <span className="tsb-val tsb-teal">{activeSession.tokens}</span>
                </div>
                <div className="tsb-divider" />
                <div className="tsb-item">
                  <span className="tsb-label">Spans</span>
                  <span className="tsb-val tsb-teal">{activeSession.spans}</span>
                </div>
                <div className="tsb-divider" />
                <div className="tsb-item">
                  <span className="tsb-label">Framework</span>
                  <span className="tsb-val" style={{ fontSize: 14, color: "var(--text-dim)" }}>{activeSession.framework}</span>
                </div>
              </div>

              {/* Toolbar */}
              <div className="trace-toolbar">
                <span className="tt-label">span waterfall · {activeSession.id}</span>
                <button className="tt-btn" onClick={() => setCollapsed({})}>expand all</button>
                <button className="tt-btn" onClick={() => {
                  const allIds = {};
                  const collect = (nodes) => nodes.forEach(n => { if (n.children?.length) { allIds[n.id] = true; collect(n.children); } });
                  collect(tree);
                  setCollapsed(allIds);
                }}>collapse all</button>
                <button className="tt-btn active">waterfall</button>
              </div>

              {/* Waterfall */}
              <div className="waterfall-wrap">
                <div className="wf-header">
                  <span className="wf-h-name">span name</span>
                  <span className="wf-h-latency">latency</span>
                  <span className="wf-h-bar">timeline (relative)</span>
                </div>
                {renderTree(tree, 0, collapsed, toggle, selectSpan, selectedSpan?.id)}
              </div>

              {/* Span Detail Drawer */}
              {selectedSpan && (
                <div className="span-drawer">
                  <div className="drawer-inner">
                    <div className="drawer-section">
                      <div className="ds-label">span metadata</div>
                      <div className="kv"><span className="kv-k">name</span><span className="kv-v teal">{selectedSpan.name}</span></div>
                      <div className="kv"><span className="kv-k">kind</span><span className="kv-v">{selectedSpan.kind}</span></div>
                      <div className="kv"><span className="kv-k">latency</span><span className="kv-v">{selectedSpan.latencyMs}ms</span></div>
                      {selectedSpan.tokens && <div className="kv"><span className="kv-k">tokens</span><span className="kv-v">{selectedSpan.tokens}</span></div>}
                      {Object.entries(selectedSpan.meta || {}).map(([k, v]) => (
                        <div key={k} className="kv">
                          <span className="kv-k">{k}</span>
                          <span className={`kv-v ${k === "action" || k === "escalated_to" ? "red" : ""}`}>{v}</span>
                        </div>
                      ))}
                    </div>
                    <div className="drawer-section">
                      <div className="ds-label">input</div>
                      <div className="code-pre">{selectedSpan.input}</div>
                    </div>
                    <div className="drawer-section">
                      <div className="ds-label">output</div>
                      <div className="code-pre" style={{ color: selectedSpan.kind === "block" ? "var(--red)" : selectedSpan.kind === "llm" ? "var(--teal)" : "var(--text-dim)" }}>
                        {selectedSpan.output}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
