// Workflow builder. Left-to-right lanes on a dotted field, orthogonal connectors
// with square joints, step numbers above each node — deliberately not a spline
// spaghetti canvas.
const NODES = [
  { id: 'n1', step: 1, title: 'Research', code: 'RS', domain: 'intel', meta: '12 fuentes', status: 'done', x: 16, y: 220 },
  { id: 'n2', step: 2, title: 'Análisis de negocio', code: 'AN', domain: 'intel', meta: 'impacto y esfuerzo', status: 'done', x: 256, y: 220 },
  { id: 'n3', step: 3, title: 'Procesos', code: 'PC', domain: 'build', meta: 'mapa AS-IS', status: 'running', x: 496, y: 120 },
  { id: 'n4', step: 4, title: 'Propuestas', code: 'PR', domain: 'comms', meta: 'plantilla v2', status: 'idle', x: 496, y: 320 },
  { id: 'n5', step: 5, title: 'QA', code: 'QA', domain: 'build', meta: 'criterios de salida', status: 'idle', x: 736, y: 220 }
];
const EDGES = [['n1', 'n2'], ['n2', 'n3'], ['n2', 'n4'], ['n3', 'n5'], ['n4', 'n5']];
const NODE_W = 196, NODE_H = 62;

function Connector({ from, to, active }) {
  const x1 = from.x + NODE_W, y1 = from.y + NODE_H / 2;
  const x2 = to.x, y2 = to.y + NODE_H / 2;
  const mid = x1 + (x2 - x1) / 2;
  const d = 'M ' + x1 + ' ' + y1 + ' H ' + mid + ' V ' + y2 + ' H ' + x2;
  return (
    <g>
      <path d={d} fill="none" stroke={active ? 'var(--signal-500)' : 'var(--gray-700)'} strokeWidth="1.5" />
      <rect x={mid - 2.5} y={y1 - 2.5} width="5" height="5" fill={active ? 'var(--signal-500)' : 'var(--gray-650)'} />
      <path d={'M ' + (x2 - 7) + ' ' + (y2 - 4) + ' L ' + x2 + ' ' + y2 + ' L ' + (x2 - 7) + ' ' + (y2 + 4)} fill="none" stroke={active ? 'var(--signal-500)' : 'var(--gray-600)'} strokeWidth="1.5" />
    </g>
  );
}

function ScreenFlows({ go, notify }) {
  const { Panel, Button, IconButton, Badge, WorkflowNode, AgentGlyph, Input, Select, Switch, Checkbox,
          SegmentedControl, ExecutionTrace, Callout, Tag, StatusDot } = window.EG;
  const D = window.EGData;
  const [sel, setSel] = React.useState('n3');
  const node = NODES.find(n => n.id === sel);
  const byId = id => NODES.find(n => n.id === id);

  return (
    <div className="ws-cols-3 ws-cols-3--flows" style={{ flex: 1 }}>
      <aside className="ws-col">
        <div className="ws-subbar" style={{ padding: '0 16px' }}>
          <span className="eg-eyebrow">Agentes</span>
          <IconButton icon="search" label="Buscar" size="sm" style={{ marginLeft: 'auto' }} />
        </div>
        <div className="ws-col-scroll ws-stack">
          {[['Intelligence', 'intel'], ['Build', 'build'], ['Comms', 'comms']].map(([label, dom]) => (
            <div key={dom}>
              <span className="eg-eyebrow">{label}</span>
              <div className="ws-stack-sm" style={{ marginTop: 10 }}>
                {D.agents.filter(a => a.domain === dom).slice(0, 4).map(a => (
                  <div key={a.code} draggable style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '7px 8px', borderRadius: 'var(--radius-sm)', background: 'var(--surface-2)', border: '1px solid var(--border-subtle)', cursor: 'grab' }}>
                    <AgentGlyph code={a.code} domain={a.domain} size="sm" />
                    <span style={{ flex: 1, font: 'var(--type-body-sm)', fontSize: 12.5, color: 'var(--text-secondary)' }}>{a.name}</span>
                    <span className="eg-icon eg-icon--sm" style={{ fontSize: 14, color: 'var(--text-muted)' }}>drag_indicator</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
          <Callout tone="neutral" title="Arrastra para añadir">
            Cada nodo recibe la salida del anterior y el contexto del proyecto.
          </Callout>
        </div>
      </aside>

      <section style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div className="ws-subbar">
          <div className="ws-subbar-meta">
            <span style={{ font: 'var(--type-h5)', flex: 'none' }}>Propuesta comercial</span>
            <Badge tone="signal" icon="bolt">Ejecutando · paso 3 de 5</Badge>
            <span className="ellipsis" style={{ font: 'var(--type-mono-sm)', color: 'var(--text-muted)' }}>v4 · guardado hace 2 min</span>
          </div>
          <div className="ws-subbar-actions">
            <SegmentedControl size="sm" value="build" options={[{ value: 'build', label: 'Constructor' }, { value: 'runs', label: 'Ejecuciones' }]} />
            <Button size="sm" variant="secondary" icon="save">Guardar</Button>
            <Button size="sm" icon="play_arrow" onClick={() => notify({ tone: 'running', title: 'Workflow en ejecución', description: 'Propuesta comercial · 5 pasos' })}>Ejecutar</Button>
          </div>
        </div>
        <div className="wf-canvas">
          <div className="wf-inner">
            <svg width="1120" height="560" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
              {EDGES.map(([a, b]) => <Connector key={a + b} from={byId(a)} to={byId(b)} active={b === 'n3' || a === 'n3'} />)}
            </svg>
            <div style={{ position: 'absolute', left: 16, top: 132, display: 'flex', alignItems: 'center', gap: 9, padding: '8px 11px', borderRadius: 'var(--radius-pill)', background: 'var(--surface-2)', border: '1px dashed var(--border-strong)' }}>
              <span className="eg-icon eg-icon--sm" style={{ color: 'var(--flux-300)' }}>bolt</span>
              <span style={{ font: 'var(--type-mono-sm)', color: 'var(--text-tertiary)' }}>DISPARADOR · reunión finalizada</span>
            </div>
            {NODES.map(n => (
              <div key={n.id} style={{ position: 'absolute', left: n.x, top: n.y }}>
                <WorkflowNode step={n.step} title={n.title} code={n.code} domain={n.domain} meta={n.meta}
                  status={n.status} selected={sel === n.id} onClick={() => setSel(n.id)} />
              </div>
            ))}
            <div style={{ position: 'absolute', left: 960, top: 232, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 34, height: 34, display: 'grid', placeItems: 'center', borderRadius: '50%', background: 'var(--success-quiet)', boxShadow: 'inset 0 0 0 1px var(--success)', color: 'var(--success)' }}>
                <span className="eg-icon eg-icon--sm">description</span>
              </span>
              <span style={{ font: 'var(--type-mono-sm)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-label)' }}>Entregable</span>
            </div>
            <div style={{ position: 'absolute', left: 496, top: 406, width: 196, padding: '9px 11px', borderRadius: 'var(--radius-sm)', background: 'rgba(11,76,250,.07)', border: '1px dashed var(--border-accent)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="eg-icon eg-icon--sm" style={{ color: 'var(--accent-text)' }}>add</span>
              <span style={{ font: 'var(--type-body-sm)', fontSize: 12, color: 'var(--accent-text)' }}>Añadir paso paralelo</span>
            </div>
          </div>
        </div>
      </section>

      <aside className="ws-col ws-col--right">
        <div className="ws-subbar" style={{ padding: '0 16px' }}>
          <span className="eg-eyebrow">Paso {String(node.step).padStart(2, '0')}</span>
          <IconButton icon="delete" label="Eliminar paso" size="sm" style={{ marginLeft: 'auto' }} />
        </div>
        <div className="ws-col-scroll ws-stack">
          <div className="ws-row" style={{ gap: 11 }}>
            <AgentGlyph code={node.code} domain={node.domain} size="lg" running={node.status === 'running'} />
            <div>
              <div style={{ font: 'var(--type-h5)' }}>{node.title}</div>
              <div style={{ font: 'var(--type-mono-sm)', color: 'var(--text-muted)', marginTop: 3 }}>{node.meta}</div>
            </div>
            {node.status === 'running' && <StatusDot state="running" style={{ marginLeft: 'auto' }} />}
          </div>
          <Input label="Nombre del paso" defaultValue={node.title} />
          <Select label="Entrada" options={['Salida del paso anterior', 'Contexto del proyecto', 'Documento seleccionado']} />
          <div>
            <span className="eg-eyebrow">Instrucción</span>
            <div style={{ marginTop: 10, padding: '11px 12px', borderRadius: 'var(--radius-sm)', background: 'var(--surface-inset)', border: '1px solid var(--border-default)', font: 'var(--type-body-sm)', color: 'var(--text-secondary)', lineHeight: 1.5 }}>
              Levanta el proceso comercial real a partir de la transcripción y los documentos del cliente. Marca cada excepción encontrada.
            </div>
          </div>
          <div>
            <span className="eg-eyebrow">Herramientas permitidas</span>
            <div className="ws-row" style={{ flexWrap: 'wrap', gap: 7, marginTop: 10 }}>
              <Tag icon="description" selected>Docs</Tag><Tag icon="database" selected>Data</Tag><Tag icon="public">Web</Tag><Tag icon="code">Code</Tag>
            </div>
          </div>
          <div className="ws-stack-sm">
            <span className="eg-eyebrow">Control</span>
            <Switch checked onChange={() => {}} label="Requiere aprobación humana" />
            <Switch onChange={() => {}} label="Reintentar en caso de error" />
            <Checkbox checked onChange={() => {}} label="Guardar output como artifact" />
          </div>
          <div>
            <span className="eg-eyebrow">Última ejecución del paso</span>
            <div style={{ marginTop: 10 }}>
              <ExecutionTrace compact steps={[
                { label: 'Leyendo documentos', count: '3 docs', status: 'done', duration: '4s' },
                { label: 'Mapeando proceso', status: 'running', detail: '11 pasos detectados' },
                { label: 'Marcando excepciones', status: 'pending' }
              ]} />
            </div>
          </div>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, { ScreenFlows });
