// Data Pipelines & ETL — visual DAG designer, CDC, streaming, AI-assisted transforms.
const PIPELINES = [
  { id: "p1", name: "GeM Ingest → Warehouse", type: "Streaming ETL", status: "running", rows: "1.2M/hr", last: "live" },
  { id: "p2", name: "Vendor Master Sync", type: "CDC · Oracle", status: "running", rows: "48K/min", last: "live" },
  { id: "p3", name: "Daily Revenue Rollup", type: "Batch ELT", status: "success", rows: "38.4M", last: "5h ago" },
  { id: "p4", name: "IoT Sensor Aggregation", type: "Streaming · Kafka", status: "running", rows: "12.4K/s", last: "live" },
  { id: "p5", name: "Scheme DBT Reconcile", type: "Batch", status: "failed", rows: "—", last: "1h ago" },
  { id: "p6", name: "Legacy Oracle Migrate", type: "Batch · one-off", status: "paused", rows: "1.8M", last: "2d ago" },
];

const DAG_NODES = [
  { id: "n1", x: 16, y: 40, kind: "source", icon: "cloud", title: "GeM Portal API", sub: "REST · 1.2M/hr", active: true },
  { id: "n2", x: 16, y: 150, kind: "source", icon: "database", title: "Postgres CDC", sub: "logical repl.", active: true },
  { id: "n3", x: 16, y: 260, kind: "source", icon: "activity", title: "Kafka · orders", sub: "12.4K ev/s", active: true },
  { id: "n4", x: 220, y: 150, kind: "transform", icon: "filter", title: "Cleanse & Dedup", sub: "6 rules · 0.4% dropped", active: true },
  { id: "n5", x: 424, y: 96, kind: "ai", icon: "sparkles", title: "AI Join", sub: "vendor_id · 98% conf", active: true },
  { id: "n6", x: 424, y: 236, kind: "transform", icon: "map", title: "Enrich — Geo", sub: "state + district", active: true },
  { id: "n7", x: 628, y: 96, kind: "sink", icon: "layers", title: "gem_transactions", sub: "428.6M rows", active: true },
  { id: "n8", x: 628, y: 236, kind: "sink", icon: "database", title: "ClickHouse mart", sub: "12.4B rows", active: true },
];
const DAG_EDGES = [
  ["n1", "n4"], ["n2", "n4"], ["n3", "n4"], ["n4", "n5"], ["n5", "n7"], ["n5", "n6"], ["n6", "n8"],
];

function PipeNode({ n, selected, onClick }) {
  const styles = {
    source: { bg: "var(--panel-2)", bd: "var(--border-strong)", ic: "var(--ink-2)" },
    transform: { bg: "var(--panel)", bd: "var(--primary)", ic: "var(--primary)" },
    ai: { bg: "var(--primary-tint)", bd: "var(--primary)", ic: "var(--primary)" },
    sink: { bg: "var(--accent-tint)", bd: "var(--accent-2)", ic: "var(--accent-2)" },
  }[n.kind];
  const w = 156, h = 52;
  return (
    <g transform={`translate(${n.x} ${n.y})`} style={{ cursor: 'pointer' }} onClick={() => onClick(n.id)}>
      <rect width={w} height={h} rx="9" fill={styles.bg} stroke={selected ? 'var(--primary)' : styles.bd} strokeWidth={selected ? 2.5 : 1.3}/>
      <circle cx="24" cy={h / 2} r="13" fill={styles.ic} opacity=".12"/>
      <g transform={`translate(17 ${h / 2 - 7})`} color={styles.ic}><Icon name={n.icon} size={14}/></g>
      <text x="44" y={h / 2 - 3} fontSize="11.5" fontWeight="600" fill="var(--ink)" fontFamily="Inter">{n.title.length > 15 ? n.title.slice(0, 14) + '…' : n.title}</text>
      <text x="44" y={h / 2 + 11} fontSize="9.5" fill="var(--ink-3)" fontFamily="JetBrains Mono">{n.sub}</text>
      {n.active && <circle cx={w - 12} cy="12" r="3.5" fill="var(--ok)"><animate attributeName="opacity" values="1;0.3;1" dur="1.6s" repeatCount="indefinite"/></circle>}
    </g>
  );
}

function PipelinesScreen() {
  const [sel, setSel] = useState("p1");
  const [node, setNode] = useState("n5");
  const nodeMap = Object.fromEntries(DAG_NODES.map(n => [n.id, n]));
  const selNode = nodeMap[node];
  const stColor = (s) => s === "running" ? "ok" : s === "success" ? "primary" : s === "failed" ? "danger" : "";

  return (
    <div style={{ display: 'flex', height: 'calc(100vh - 56px)' }}>
      {/* Left: pipeline list */}
      <div style={{ width: 264, borderRight: '1px solid var(--border)', background: 'var(--panel)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div><div style={{ fontWeight: 600, fontSize: 13 }}>Pipelines</div><div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>18 active · 3 streaming</div></div>
          <button className="icon-btn" title="New pipeline"><Icon name="plus" size={15}/></button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 8 }}>
          {PIPELINES.map(p => (
            <div key={p.id} onClick={() => setSel(p.id)}
              style={{ padding: 10, borderRadius: 8, marginBottom: 5, cursor: 'pointer', border: '1px solid ' + (sel === p.id ? 'color-mix(in oklch, var(--primary), transparent 65%)' : 'transparent'), background: sel === p.id ? 'var(--primary-tint)' : 'transparent' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}>
                <span className={`live-dot ${p.status === 'running' ? '' : p.status === 'failed' ? 'danger' : p.status === 'paused' ? 'warn' : ''}`} style={{ background: p.status === 'success' ? 'var(--primary)' : undefined, animation: p.status === 'running' ? undefined : 'none' }}/>
                <span style={{ fontSize: 12.5, fontWeight: sel === p.id ? 600 : 500, color: sel === p.id ? 'var(--primary)' : 'var(--ink)', flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', paddingLeft: 15, fontSize: 10.5, color: 'var(--ink-3)' }}>
                <span>{p.type}</span><span className="mono">{p.rows}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Center: DAG canvas */}
      <div style={{ flex: 1, background: 'var(--panel-2)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ height: 44, borderBottom: '1px solid var(--border)', background: 'var(--panel)', display: 'flex', alignItems: 'center', gap: 8, padding: '0 16px' }}>
          <div style={{ fontSize: 12.5, fontWeight: 600 }}>GeM Ingest → Warehouse</div>
          <span className="tag ok" style={{ fontSize: 10.5 }}><span className="live-dot"/>Running</span>
          <span className="tag" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>Streaming ETL</span>
          <span className="spacer"/>
          <button className="btn sm"><Icon name="sparkles" size={11}/>AI suggest</button>
          <button className="btn sm"><Icon name="pause" size={11}/>Pause</button>
          <button className="btn sm"><Icon name="play" size={11}/>Run</button>
          <button className="btn primary sm">Deploy</button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: 20, backgroundImage: 'radial-gradient(circle, var(--border-strong) 0.7px, transparent 0.7px)', backgroundSize: '20px 20px' }}>
          <svg viewBox="0 0 800 340" width="100%" style={{ minWidth: 620, display: 'block' }}>
            <defs>
              <marker id="pipearrow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0 L6 3 L0 6 Z" fill="var(--border-strong)"/></marker>
            </defs>
            {DAG_EDGES.map(([a, b], i) => {
              const na = nodeMap[a], nb = nodeMap[b];
              const x1 = na.x + 156, y1 = na.y + 26, x2 = nb.x, y2 = nb.y + 26;
              const mx = (x1 + x2) / 2;
              return (
                <path key={i} d={`M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`} stroke="var(--primary)" strokeWidth="1.8" fill="none" opacity=".55" markerEnd="url(#pipearrow)" strokeDasharray="5 5">
                  <animate attributeName="stroke-dashoffset" values="20;0" dur="0.9s" repeatCount="indefinite"/>
                </path>
              );
            })}
            {DAG_NODES.map(n => <PipeNode key={n.id} n={n} selected={node === n.id} onClick={setNode}/>)}
          </svg>
        </div>

        {/* Run log strip */}
        <div style={{ height: 128, borderTop: '1px solid var(--border)', background: 'var(--panel)', padding: '10px 16px', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Icon name="terminal" size={13} style={{ color: 'var(--ink-3)' }}/>
            <span style={{ fontSize: 11.5, fontWeight: 600 }}>Run log</span>
            <span className="tag ok" style={{ fontSize: 10 }}><span className="live-dot"/>tailing</span>
          </div>
          <div className="mono" style={{ fontSize: 10.5, lineHeight: 1.7, color: 'var(--ink-2)', height: 76, overflowY: 'auto' }}>
            <div><span style={{ color: 'var(--ink-4)' }}>14:44:12</span> <span style={{ color: 'var(--ok)' }}>INFO</span>  Cleanse &amp; Dedup — 428,612 rows in, 426,901 out (0.4% dropped)</div>
            <div><span style={{ color: 'var(--ink-4)' }}>14:44:12</span> <span style={{ color: 'var(--primary)' }}>AI</span>    Join resolved vendor_id ↔ vendor_master.id at 98.2% confidence</div>
            <div><span style={{ color: 'var(--ink-4)' }}>14:44:13</span> <span style={{ color: 'var(--ok)' }}>INFO</span>  Enrich — geo-tagged 426,901 rows (state + district)</div>
            <div><span style={{ color: 'var(--ink-4)' }}>14:44:13</span> <span style={{ color: 'var(--ok)' }}>INFO</span>  Sink gem_transactions ← upsert 426,901 · 218ms</div>
            <div><span style={{ color: 'var(--ink-4)' }}>14:44:14</span> <span style={{ color: 'var(--accent-2)' }}>WARN</span>  ClickHouse mart backpressure — buffer 68% · throttling</div>
          </div>
        </div>
      </div>

      {/* Right: inspector */}
      <div style={{ width: 300, borderLeft: '1px solid var(--border)', background: 'var(--panel)', overflowY: 'auto' }}>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Node inspector</div>
          <div style={{ fontWeight: 600, fontSize: 14, marginTop: 2, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name={selNode.icon} size={14} style={{ color: 'var(--primary)' }}/>{selNode.title}</div>
        </div>
        <div style={{ padding: 14 }}>
          {selNode.kind === "ai" && (
            <div style={{ padding: 10, borderRadius: 8, background: 'var(--primary-tint)', border: '1px solid color-mix(in oklch, var(--primary), transparent 75%)', marginBottom: 12, fontSize: 11.5, color: 'var(--ink-2)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontWeight: 600, color: 'var(--primary)', marginBottom: 4 }}><Icon name="sparkles" size={12}/>AI-assisted transform</div>
              Suggested join key <span className="mono">vendor_id ↔ vendor_master.id</span> with 98.2% confidence. Also detected a datatype cast for <span className="mono">gst_no</span>.
            </div>
          )}
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600, marginBottom: 8 }}>Throughput</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 600 }}>{selNode.sub}</div>
            <Sparkline data={[42,48,45,52,58,55,62,68,72,70,76,84]} w={260} h={40} stroke="var(--primary)" fill="var(--primary)" area/>
          </div>
          <div style={{ marginBottom: 14, paddingBottom: 12, borderBottom: '1px solid var(--border)' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600, marginBottom: 8 }}>Config</div>
            {[["Type", selNode.kind], ["Parallelism", "8 workers"], ["On error", "Dead-letter queue"], ["Checkpoint", "every 30s"]].map(([k, v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '5px 0' }}><span style={{ color: 'var(--ink-3)' }}>{k}</span><span className="mono" style={{ fontWeight: 500 }}>{v}</span></div>
            ))}
          </div>
          <div>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600, marginBottom: 8 }}>CDC status</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, marginBottom: 6 }}><span className="live-dot"/><span>Replication lag <b className="mono">0.8s</b></span></div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Log-based CDC on Oracle + Postgres · exactly-once · schema-drift auto-handled.</div>
          </div>
          <button className="btn sm" style={{ width: '100%', marginTop: 14, justifyContent: 'center' }}><Icon name="edit" size={11}/>Edit transform</button>
        </div>
      </div>
    </div>
  );
}

window.PipelinesScreen = PipelinesScreen;
