/* DEV Architecture — live 3-layer view with right side panel on SP_COLAB_SALES */

const DevArchitecture = ({ onOpenChat }) => {
  const [selected, setSelected] = React.useState('sp_colab_sales');

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 14, padding: 16 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>DEV · ARCHITECTURE · LIVE · TAP ANY NODE</div>
            <h2 className="font-display" style={{ margin: '4px 0 0', fontSize: 22, fontWeight: 600 }}>3‑layer system map</h2>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-xs"><Icon name="eye" size={11} />Filter layer</button>
            <button className="btn btn-xs"><Icon name="refresh" size={11} />Live</button>
          </div>
        </div>

        {/* LAYER 1 */}
        <LayerBlock num="1" title="Entry + Routing" sub="Ingress · identificação · modo">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr 1fr', gap: 10, alignItems: 'center' }}>
            <Node id="wh_wa" label="WhatsApp webhook" sub="+351 918 780 180" tag="92 req/min" status="ok" onClick={setSelected} selected={selected === 'wh_wa'} metric={[12,14,11,18,22,19,24]} />
            <FlowArrow label="identificar_contacto" sub="colab_db → Gestor → Primavera" />
            <Node id="mode_router" label="Mode router" sub="4 modos · p50 42ms" status="ok" onClick={setSelected} selected={selected === 'mode_router'} />
          </div>
        </LayerBlock>

        {/* LAYER 2 */}
        <LayerBlock num="2" title="Agent layer" sub="SP prompts · FRAMEs · skills · sub-agentes">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {[
              { id: 'sp_clientes', label: 'SP_CLIENTES', v: 'v1.12.4', frames: 6, status: 'ok' },
              { id: 'sp_colab', label: 'SP_COLABORADORES', v: 'v2.3.1', frames: 8, status: 'ok' },
              { id: 'sp_dev', label: 'SP_DEV', v: 'v1.4.0', frames: 3, status: 'ok' },
              { id: 'sp_board', label: 'SP_BOARD', v: 'v1.1.7', frames: 2, status: 'ok' },
            ].map(p => (
              <Node key={p.id} id={p.id} label={p.label} sub={`${p.v} · ${p.frames} FRAMEs`} status={p.status} mono onClick={setSelected} selected={selected === p.id} />
            ))}
          </div>
          <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--border)' }}>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>└── SP_COLABORADORES submódulos</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
              {[
                { id: 'sp_colab_sales', label: 'SALES', v: 'v2.3.1', status: 'ok' },
                { id: 'sp_colab_sat', label: 'SAT', v: 'v2.0.9', status: 'ok' },
                { id: 'sp_colab_ops', label: 'OPS', v: 'v1.8.2', status: 'warn' },
                { id: 'sp_colab_mkt', label: 'MKT', v: 'v2.1.0', status: 'ok' },
                { id: 'sp_colab_fin', label: 'FIN', v: 'v1.9.4', status: 'ok' },
                { id: 'sp_colab_hr', label: 'HR', v: 'v1.3.0', status: 'ok' },
                { id: 'sp_colab_bi', label: 'BI', v: 'v1.2.1', status: 'ok' },
                { id: 'sp_colab_bnd', label: 'BRAND', v: 'v1.0.5', status: 'ok' },
              ].map(p => (
                <Node key={p.id} id={p.id} label={p.label} sub={p.v} status={p.status} mono small onClick={setSelected} selected={selected === p.id} />
              ))}
            </div>
          </div>
          <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed var(--border)' }}>
            <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>Shared: brand sub-agentes</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
              {['Mimaki', 'BIOND', 'Decal', 'Sensek'].map(b => (
                <Node key={b} id={`brand_${b}`} label={b} sub="always-on" status="ok" small onClick={setSelected} selected={selected === `brand_${b}`} />
              ))}
            </div>
          </div>
        </LayerBlock>

        {/* LAYER 3 */}
        <LayerBlock num="3" title="RAG Engine + KB + Tools" sub="query → retrieval → generation">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 }}>
            {['Query Analysis', 'Retrieval', 'Reranking', 'Context Asm.', 'Generation', 'Post‑proc.'].map((s, i) => (
              <div key={s} style={{ padding: '8px 10px', border: '1px solid var(--border)', borderRadius: 6, background: 'var(--bg-sunken)', display: 'flex', flexDirection: 'column', gap: 4 }}>
                <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{i + 1}/6</div>
                <div style={{ fontSize: 11, fontWeight: 500 }}>{s}</div>
                <div style={{ fontSize: 9, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>p50 {[8,42,38,12,820,18][i]}ms</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div style={{ padding: 10, border: '1px solid var(--border)', borderRadius: 6 }}>
              <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>KB SOURCES · 15 · 83.551 chunks</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 4 }}>
                {[
                  ['store_kb', 21070, 'ok'],['mimaki_kb', 2551, 'ok'],['biond_kb', 1840, 'ok'],['decal_kb', 1240, 'ok'],['sensek_kb', 980, 'ok'],
                  ['colab_db', 193, 'ok'],['sat_kb', 14800, 'ok'],['fin_kb', 8120, 'ok'],['ops_kb', 6210, 'ok'],['mkt_kb', 4200, 'ok'],
                  ['hr_kb', 3180, 'ok'],['bi_kb', 2100, 'ok'],['brand_kb', 1820, 'ok'],['quality_kb', 0, 'crit'],['board_kb', 1247, 'ok'],
                ].map(([n, c, s]) => (
                  <div key={n} title={`${n} · ${c} chunks`} style={{ padding: 6, border: '1px solid var(--border)', borderRadius: 4, background: s === 'crit' ? 'color-mix(in oklch, var(--danger) 10%, var(--bg-elev))' : 'var(--bg-elev)' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <StatusDot status={s} />
                      <span className="font-mono" style={{ fontSize: 8, color: 'var(--text-dim)' }}>{c > 1000 ? (c/1000).toFixed(1) + 'k' : c}</span>
                    </div>
                    <div className="font-mono" style={{ fontSize: 9, marginTop: 3, color: s === 'crit' ? 'var(--danger)' : 'inherit' }}>{n}</div>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ padding: 10, border: '1px solid var(--border)', borderRadius: 6 }}>
              <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>TOOLS PYTHON · 5</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
                {[['simulate_financing','ok'],['search_primavera','ok'],['search_kb','ok'],['generate_mockup','ok'],['send_email','ok']].map(([t, s]) => (
                  <div key={t} style={{ padding: '6px 8px', background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <StatusDot status={s} />
                    <span className="font-mono" style={{ fontSize: 10 }}>{t}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 8, padding: '6px 8px', fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', background: 'var(--bg-sunken)', borderRadius: 4 }}>
                IVFFlat probes=10 · HNSW pending · 61G free
              </div>
            </div>
          </div>
        </LayerBlock>
      </div>

      {/* Side panel — SP_COLAB_SALES detail */}
      <DevNodeDetail selected={selected} onOpenChat={onOpenChat} />
    </div>
  );
};

const LayerBlock = ({ num, title, sub, children }) => (
  <div className="card" style={{ padding: 0, position: 'relative' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderBottom: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
      <div style={{ width: 22, height: 22, borderRadius: 4, background: 'var(--brand-900)', color: 'var(--ai-500)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 11 }}>L{num}</div>
      <h3 className="font-display" style={{ margin: 0, fontSize: 13, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Camada {num} — {title}</h3>
      <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{sub}</span>
      <div style={{ flex: 1 }} />
      <StatusDot status="ok" />
    </div>
    <div style={{ padding: 14 }}>{children}</div>
  </div>
);

const Node = ({ id, label, sub, status = 'ok', onClick, selected, mono, small, tag, metric }) => (
  <button onClick={() => onClick?.(id)} style={{
    padding: small ? 8 : 10, borderRadius: 6,
    border: selected ? '1px solid var(--ai-500)' : '1px solid var(--border)',
    background: selected ? 'color-mix(in oklch, var(--ai-500) 10%, var(--bg-elev))' : 'var(--bg-elev)',
    textAlign: 'left', width: '100%',
    boxShadow: selected ? 'var(--ai-glow)' : 'none',
    transition: 'all 0.15s',
  }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
        <StatusDot status={status} />
        <span className={mono ? 'font-mono' : ''} style={{ fontSize: small ? 10 : 12, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
      </div>
      {tag && <span className="font-mono" style={{ fontSize: 9, color: 'var(--ai-500)' }}>{tag}</span>}
    </div>
    {sub && <div className="font-mono" style={{ fontSize: small ? 9 : 10, color: 'var(--text-dim)', marginTop: 3 }}>{sub}</div>}
    {metric && <div style={{ marginTop: 6 }}><Spark data={metric} width={100} height={18} /></div>}
  </button>
);

const FlowArrow = ({ label, sub }) => (
  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, padding: '0 8px' }}>
    <div style={{ fontSize: 10, color: 'var(--ai-500)', fontFamily: 'var(--font-mono)' }}>{label}</div>
    <svg width="100%" height="14" viewBox="0 0 100 14" preserveAspectRatio="none"><path d="M2 7 L94 7 M88 2 L94 7 L88 12" stroke="var(--ai-500)" strokeWidth="1" fill="none" strokeLinecap="round" /></svg>
    {sub && <div style={{ fontSize: 9, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', textAlign: 'center' }}>{sub}</div>}
  </div>
);

const DevNodeDetail = ({ selected, onOpenChat }) => {
  const detail = {
    sp_colab_sales: {
      title: 'SP_COLAB_SALES',
      version: 'v2.3.1',
      sub: 'Prompt do módulo Comercial',
      owner: 'FC',
      lastEdit: '2d ago · by FC',
      lines: 864,
      frames: ['FRAME-VISIT-BRIEF', 'FRAME-CRESCIMENTO-CLIENTE', 'FRAME-SIMULACAO-FIN', 'FRAME-PROSPECCAO'],
      metrics: [
        ['p50 latency', '1.24s'],
        ['p95 latency', '3.80s'],
        ['Success rate', '98.2%'],
        ['Avg tokens', '4.8k in · 1.1k out'],
        ['Cost / turn', '$0.038'],
        ['Calls today', '141'],
      ],
      errors: [
        { t: '08:42', m: 'kb.store_kb timeout after 12s', sev: 'warn' },
        { t: '06:18', m: 'tool.simulate_financing · null response', sev: 'warn' },
        { t: '22:03', m: 'rate_limit (Opus) · 3× retry ok', sev: 'info' },
      ],
    },
  };
  const d = detail[selected] || detail.sp_colab_sales;

  return (
    <aside className="card" style={{ padding: 0, position: 'sticky', top: 'calc(var(--topbar-h) + 16px)', height: 'fit-content', maxHeight: 'calc(100vh - var(--topbar-h) - 32px)', overflowY: 'auto' }}>
      <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <StatusDot status="ok" />
        <div style={{ flex: 1 }}>
          <div className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{d.sub}</div>
          <div className="font-display" style={{ fontSize: 15, fontWeight: 600, letterSpacing: '0.02em' }}>{d.title}</div>
        </div>
        <span className="font-mono" style={{ fontSize: 10, color: 'var(--ai-500)', padding: '2px 6px', border: '1px solid color-mix(in oklch, var(--ai-500) 30%, transparent)', borderRadius: 4 }}>{d.version}</span>
      </div>

      <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 14, fontSize: 12 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, fontSize: 11 }}>
          <div><span style={{ color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>owner</span><br />{d.owner}</div>
          <div><span style={{ color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>last edit</span><br />{d.lastEdit}</div>
          <div><span style={{ color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>lines</span><br />{d.lines}</div>
          <div><span style={{ color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>env</span><br /><span style={{ color: 'var(--success)' }}>staging + prod sync</span></div>
        </div>

        <div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>METRICS · 24h</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4 }}>
            {d.metrics.map(([k, v]) => (
              <div key={k} style={{ padding: '6px 8px', background: 'var(--bg-sunken)', borderRadius: 4 }}>
                <div className="font-mono" style={{ fontSize: 9, color: 'var(--text-dim)' }}>{k}</div>
                <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{v}</div>
              </div>
            ))}
          </div>
        </div>

        <div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>FRAMES ANEXADOS · {d.frames.length}</div>
          {d.frames.map(f => (
            <div key={f} style={{ padding: '6px 8px', marginBottom: 3, background: 'var(--bg-sunken)', borderRadius: 4, display: 'flex', justifyContent: 'space-between' }}>
              <span className="font-mono" style={{ fontSize: 10 }}>{f}</span>
              <span className="font-mono" style={{ fontSize: 9, color: 'var(--text-dim)' }}>v1.2</span>
            </div>
          ))}
        </div>

        <div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>RECENT ERRORS · 24h · 3</div>
          {d.errors.map((e, i) => (
            <div key={i} style={{ padding: '6px 8px', marginBottom: 3, background: 'var(--bg-sunken)', borderRadius: 4, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <StatusDot status={e.sev} />
              <div style={{ flex: 1 }}>
                <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{e.t}</div>
                <div style={{ fontSize: 11 }}>{e.m}</div>
              </div>
            </div>
          ))}
        </div>

        <div className="ai-surface" style={{ padding: 10, borderRadius: 6 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <span className="ai-chip" style={{ fontSize: 10 }}><span className="ai-dot" />Digi sugere</span>
          </div>
          <div style={{ fontSize: 11.5, lineHeight: 1.5 }}>
            Este SP tem <strong>864 linhas</strong>, acima do recomendado (200). Refatorar para FRAMEs reduz custo ~18% e latência p95. Queres ver o plano?
          </div>
          <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
            <button className="btn btn-xs btn-ai" onClick={onOpenChat}>Ver plano</button>
            <button className="btn btn-xs">Dispensar</button>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-xs" style={{ flex: 1, justifyContent: 'center' }}><Icon name="doc" size={11} />Open editor</button>
          <button className="btn btn-xs" style={{ flex: 1, justifyContent: 'center' }}><Icon name="zap" size={11} />Deploy</button>
        </div>
      </div>
    </aside>
  );
};

window.DevArchitecture = DevArchitecture;
