#!/bin/sh -e

# Ensure Debian /usr/share/nodejs is symlinked into node_modules
test -e node_modules/jsdom || pkgjs-ln jsdom

# Create test script
node<<'EOF'


const { JSDOM } = require("jsdom");
const d3 = require("/usr/share/nodejs/d3/dist/d3.js");
const graphlib = require("/usr/share/nodejs/graphlib/dist/graphlib.core.js");
const dagre = require("/usr/share/nodejs/dagre/dist/dagre.core.js");
const dagreD3 = require("/usr/share/nodejs/dagre-d3/dist/dagre-d3.core.js");

// Create virtual DOM with SVG
const dom = new JSDOM(`<svg id="svg" width="600" height="300"></svg>`);
global.document = dom.window.document;
global.window = dom.window;

// fake getBBox
window.SVGElement.prototype.getBBox = function () {
  // Minimal bounding box approximation
  return { x: 0, y: 0, width: 80, height: 20 };
};

window.SVGElement.prototype.getScreenCTM = () => ({
  inverse() { return this; },
  multiply() { return this; },
  translate() { return this; }
});

global.location = { href: "http://localhost/" };

// Build graph
const g = new dagreD3.graphlib.Graph().setGraph({});
g.setNode("A", { label: "Start" });
g.setNode("B", { label: "End" });
g.setEdge("A", "B", {});

// Render
const render = new dagreD3.render();
const svg = d3.select("#svg");
const inner = svg.append("g");
render(inner, g);

// Validate output
const output = dom.window.document.querySelectorAll("svg g g.node");
if (output.length === 0) {
  console.error("No nodes rendered");
  process.exit(1);
}

console.log("Rendered", output.length, "nodes");
process.exit(0)
EOF
