import type { ToolResultMessage } from "@jaeswift/jae-ai";
import { html } from "lit";
import { GitBranch } from "lucide";
import { registerToolRenderer, renderHeader } from "../renderer-registry.js";
import type { ToolRenderer, ToolRenderResult } from "../types.js";

export class MermaidRenderer implements ToolRenderer {
	render(params: any, result: ToolResultMessage | undefined, isStreaming?: boolean): ToolRenderResult {
		const rawContent = result?.content;
		const resultText = Array.isArray(rawContent)
			? rawContent
					.filter((c: any) => c.type === "text")
					.map((c: any) => c.text)
					.join("\n")
			: typeof rawContent === "string"
				? rawContent
				: "";
		const diagram = params?.diagram || params?.code || resultText || "";
		const state = result ? (result.isError ? "error" : "complete") : "inprogress";
		const id = "mermaid-" + Math.random().toString(36).slice(2);

		return {
			content: html`
        <div class="space-y-3">
          ${renderHeader(state, GitBranch, "Diagram")}
          ${
					diagram
						? html`
            <div class="p-4 bg-background rounded-lg border border-border overflow-auto">
              <div .id=${id} class="mermaid">${diagram}</div>
              <script>
                (function() {
                  var el = document.getElementById('${id}');
                  if (!el) return;
                  if (window.mermaid) {
                    window.mermaid.initialize({ startOnLoad: false });
                    window.mermaid.run({ nodes: [el] });
                  } else {
                    var s = document.createElement('script');
                    s.src = 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js';
                    s.onload = function() {
                      window.mermaid.initialize({ startOnLoad: false });
                      window.mermaid.run({ nodes: [el] });
                    };
                    document.head.appendChild(s);
                  }
                })();
              </script>
            </div>
          `
						: ""
				}
        </div>
      `,
			isCustom: false,
		};
	}
}

registerToolRenderer("mermaid", new MermaidRenderer());
registerToolRenderer("diagram", new MermaidRenderer());
