import { graphs } from "./graph/data.ts";
import { summarize, type ModuleNode, type ProgramGraph } from "./graph/model.ts";
import { markNativeReady, required } from "./shared/shell.ts";

markNativeReady();
const stage = required<HTMLElement>("[data-graph-stage]");
const svg = required<SVGSVGElement>("[data-graph-lines]");
const summary = required<HTMLElement>("[data-graph-summary]");
let activeGraph: ProgramGraph = graphs.app;
function coordinates(node: ModuleNode): { x: number; y: number } { return { x: stage.clientWidth * node.x / 100, y: stage.clientHeight * node.y / 100 }; }
function render(): void {
  stage.querySelectorAll(".graph-node").forEach((node) => node.remove()); svg.replaceChildren();
  for (const edge of activeGraph.edges) { const from = activeGraph.nodes.find((node) => node.id === edge.from); const to = activeGraph.nodes.find((node) => node.id === edge.to); if (!from || !to) continue; const a = coordinates(from); const b = coordinates(to); const path = document.createElementNS("http://www.w3.org/2000/svg", "path"); path.setAttribute("class", "graph-edge"); path.setAttribute("d", `M ${a.x + 87} ${a.y + 36} C ${(a.x + b.x) / 2 + 87} ${a.y + 36}, ${(a.x + b.x) / 2} ${b.y + 36}, ${b.x} ${b.y + 36}`); if (edge.typeOnly) path.setAttribute("stroke-dasharray", "5 5"); svg.append(path); }
  for (const node of activeGraph.nodes) { const element = document.createElement("div"); const point = coordinates(node); element.className = `graph-node ${node.kind === "entry" || node.kind === "worker" ? "active" : ""}`; element.style.left = `${point.x}px`; element.style.top = `${point.y}px`; element.innerHTML = `<strong>${node.label}</strong><span>${node.kind} · ${node.types} type symbols</span>`; stage.append(element); }
  const data = summarize(activeGraph); summary.textContent = `entry: ${activeGraph.name}\ngeneration: ${data.generation}\nsource files: ${data.files}\nedges: ${data.edges}\ntype symbols: ${data.declarations}\nstatus: ready`;
}
document.querySelectorAll<HTMLButtonElement>("[data-entry]").forEach((button) => button.addEventListener("click", () => { activeGraph = graphs[button.dataset.entry ?? "app"]; document.querySelectorAll("[data-entry]").forEach((item) => item.classList.remove("is-active")); button.classList.add("is-active"); render(); }));
window.addEventListener("resize", render); render();
