// Agent Builder — Visual flow-builder section (animated)
// Recreates the node-canvas reference and animates the wiring.

const COMPONENTS = [
  { c: "#22c5e8", t: "Input & Output" },
  { c: "#7c4dff", t: "Models & Agents" },
  { c: "#f0337f", t: "LLM Operations" },
  { c: "#f5c518", t: "Knowledge" },
];

// node positions as % of the canvas box (mirrors the reference layout)
const NODES = [
  { id: "input",  cls: "",          accent: "#22c5e8", label: "Chat Input",  body: "User Message",   left: 3,  top: 17 },
  { id: "agent",  cls: "is-agent",  accent: "#7c4dff", label: "Agent",       body: "Análise · 2 tools", left: 39, top: 46 },
  { id: "guard",  cls: "",          accent: "#f0337f", label: "Guardrails",  body: "PII · LGPD",     left: 73, top: 11 },
];
// directed wires between node ids — the wire is drawn grey; the pulse is coloured
const WIRES = [
  { from: "input", to: "agent", color: "#22c5e8" },
  { from: "agent", to: "guard", color: "#7c4dff" },
];

function FlowBuilder() {
  const canvasRef = useRef(null);
  const nodeRefs = useRef({});
  const [links, setLinks] = useState([]);
  const [box, setBox] = useState({ w: 0, h: 0 });
  const [entered, setEntered] = useState(false);

  const measure = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const W = canvas.clientWidth, H = canvas.clientHeight;
    const anchor = (id, side) => {
      const el = nodeRefs.current[id];
      if (!el) return { x: 0, y: 0 };
      const x = side === "right" ? el.offsetLeft + el.offsetWidth : el.offsetLeft;
      const y = el.offsetTop + el.offsetHeight / 2;
      return { x, y };
    };
    const out = WIRES.map((w) => {
      const s = anchor(w.from, "right");
      const t = anchor(w.to, "left");
      const mx = s.x + (t.x - s.x) * 0.5;
      const d = `M ${s.x},${s.y} C ${mx},${s.y} ${mx},${t.y} ${t.x},${t.y}`;
      return { d, color: w.color };
    });
    setBox({ w: W, h: H });
    setLinks(out);
  };

  useEffect(() => {
    const raf = requestAnimationFrame(() => { measure(); requestAnimationFrame(() => setEntered(true)); });
    window.addEventListener("resize", measure);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", measure); };
  }, []);

  return (
    <section className="section" id="construcao">
      <div className="container">
        <SectionHead
          center
          eyebrow="Construção visual"
          title="Construir Agentes de IA não precisa<br />ser coisa de outro mundo."
          lede="Arraste componentes, ligue entradas, modelos, ferramentas e guardrails. O fluxo que você desenha é exatamente o agente que entra em produção."
        />
        <Reveal className="flow-wrap">
          <div className="flow-scroll">
            <div className="flow-window">
              <div className="flow-bar">
                <span className="tl"><i></i><i></i><i></i></span>
                <span className="flow-url"><b>agentbuilder.maitha.com</b> <span className="cur">/ construir</span></span>
              </div>
              <div className="flow-main">
                <aside className="flow-side">
                  <div className="lbl">Componentes</div>
                  <ul>
                    {COMPONENTS.map((c) => (
                      <li key={c.t}><span className="cdot" style={{ background: c.c, color: c.c }}></span>{c.t}</li>
                    ))}
                  </ul>
                </aside>
                <div className="flow-canvas" ref={canvasRef}>
                  <svg className="flow-links" viewBox={"0 0 " + (box.w || 1) + " " + (box.h || 1)} preserveAspectRatio="none">
                    {links.map((l, i) => <path key={"b" + i} className="link-base" d={l.d} />)}
                  </svg>

                  {NODES.map((n, idx) => (
                    <div
                      key={n.id}
                      ref={(el) => { nodeRefs.current[n.id] = el; }}
                      className={"fnode " + n.cls}
                      style={{ left: n.left + "%", top: n.top + "%" }}
                    >
                      <div className="nhead">
                        <span className="nbar" style={{ background: n.accent, color: n.accent }}></span>
                        <span className="nlabel" style={{ color: n.accent }}>{n.label}</span>
                      </div>
                      <div className="nbody">{n.body}</div>
                    </div>
                  ))}

                  {links.map((l, i) => (
                    <span
                      key={"d" + i}
                      className="flow-dot"
                      style={{ offsetPath: "path('" + l.d + "')", WebkitOffsetPath: "path('" + l.d + "')", background: l.color, boxShadow: "0 0 10px " + l.color + ", 0 0 4px " + l.color, animationDelay: (1.0 + i * 1.3) + "s" }}
                    ></span>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { FlowBuilder });
