const NS = 'http://www.w3.org/2000/svg';
const svg = document.querySelector('.flow');
const defs = document.createElementNS(NS, 'defs');
defs.innerHTML = '<marker id="arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path d="M0 0 L8 4 L0 8 Z" fill="var(--muted)"/></marker>';
svg.prepend(defs);
const edgesG = document.getElementById('edges');
const nodesG = document.getElementById('nodes');
const nodes = [
{ x: 30, y: 60, w: 46, h: 30, t: 'Start' },
{ x: 130, y: 60, w: 58, h: 30, t: 'Login' },
{ x: 250, y: 30, w: 50, h: 28, t: 'Error', diamond: true },
{ x: 250, y: 90, w: 58, h: 30, t: 'Home' },
{ x: 380, y: 90, w: 30, h: 30, t: 'Done', circle: true },
];
const edges = [[0, 1], [1, 2], [1, 3], [3, 4]];
function drawNode(n) {
if (n.circle) {
const c = document.createElementNS(NS, 'circle');
c.setAttribute('cx', n.x); c.setAttribute('cy', n.y); c.setAttribute('r', 15);
c.setAttribute('class', 'box');
nodesG.appendChild(c);
} else {
const r = document.createElementNS(NS, 'rect');
r.setAttribute('x', n.x - n.w / 2); r.setAttribute('y', n.y - n.h / 2);
r.setAttribute('width', n.w); r.setAttribute('height', n.h);
r.setAttribute('rx', n.diamond ? 14 : 5);
r.setAttribute('class', 'box');
nodesG.appendChild(r);
}
const t = document.createElementNS(NS, 'text');
t.setAttribute('x', n.x); t.setAttribute('y', n.y + 3);
t.textContent = n.t;
nodesG.appendChild(t);
}
nodes.forEach(drawNode);
edges.forEach(([a, b]) => {
const p = document.createElementNS(NS, 'path');
const A = nodes[a], B = nodes[b];
p.setAttribute('d', 'M' + (A.x + (A.w || 30) / 2) + ' ' + A.y + ' L' + (B.x - (B.w || 30) / 2) + ' ' + B.y);
p.setAttribute('class', 'edge');
edgesG.appendChild(p);
});
const ball = document.getElementById('ball');
const path = [0, 1, 3, 4];
let i = 0;
function step() {
const n = nodes[path[i % path.length]];
const above = n.circle ? 22 : (n.h || 30) / 2 + 12;
ball.setAttribute('cx', n.x);
ball.setAttribute('cy', n.y - above);
i++;
}
step();
setInterval(step, 900);