import { useEffect, useRef, useState, useId } from 'react';
import mermaid from 'mermaid';
const MERMAID_FONT_FAMILY =
'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
/**
* Browser-side Mermaid normalization:
* - Convert escaped newlines in quoted labels (`\n`, `\\n`) to HTML line breaks.
* Mermaid web rendering handles `
` labels more reliably than escaped `\n`.
*/
function normalizeMermaidCodeForBrowser(code: string): string {
const trimmed = code.trim();
let normalized = '';
let inDoubleQuote = false;
let inSingleQuote = false;
for (let i = 0; i < trimmed.length; i++) {
const char = trimmed[i];
const prev = i > 0 ? trimmed[i - 1] : '';
if (char === '"' && !inSingleQuote && prev !== '\\') {
inDoubleQuote = !inDoubleQuote;
normalized += char;
continue;
}
if (char === "'" && !inDoubleQuote && prev !== '\\') {
inSingleQuote = !inSingleQuote;
normalized += char;
continue;
}
if ((inDoubleQuote || inSingleQuote) && char === '\\') {
let j = i;
while (trimmed[j] === '\\') {
j++;
}
if (trimmed[j] === 'n') {
normalized += '
';
i = j;
continue;
}
}
normalized += char;
}
return normalized;
}
/**
* Force Mermaid SVG output to scale with container width.
* This keeps text and shapes proportional when the container shrinks/expands.
*/
function makeSvgResponsive(svg: string): string {
return svg.replace(/