<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';

  mermaid.initialize({
    startOnLoad: false,
    theme: 'dark',
    themeVariables: {
      primaryColor: '{{primaryColor}}',
      primaryTextColor: '{{primaryTextColor}}',
      primaryBorderColor: '{{primaryBorderColor}}',
      lineColor: '{{lineColor}}',
      secondaryColor: '{{secondaryColor}}',
      tertiaryColor: '{{secondaryColor}}',
      background: '{{background}}',
      mainBkg: '{{mainBkg}}',
      secondBkg: '{{secondBkg}}',
      border1: '{{border1}}',
      border2: '{{border2}}',
      note: '{{note}}',
      noteBkgColor: '{{noteBkgColor}}',
      noteTextColor: '{{noteTextColor}}',
      noteBorderColor: '{{noteBorderColor}}',
      arrowheadColor: '{{arrowheadColor}}',
      fontFamily: '{{fontFamily}}',
      fontSize: '{{fontSize}}',
      darkMode: '{{darkMode}}',
      edgeLabelBackground: '{{edgeLabelBackground}}',
      clusterBkg: '{{clusterBkg}}',
      clusterBorder: '{{clusterBorder}}',
      defaultLinkColor: '{{defaultLinkColor}}',
      titleColor: '{{titleColor}}',
      nodeTextColor: '{{nodeTextColor}}'
    },
    flowchart: {
      htmlLabels: true,
      curve: 'basis',
      useMaxWidth: true,
      padding: 20
    },
    securityLevel: 'loose'
  });

  // Use both DOMContentLoaded and load events for better compatibility
  function initMermaid() {
    const mermaidBlocks = document.querySelectorAll(
      'pre.language-mermaid code'
    );

    if (mermaidBlocks.length === 0) {
      console.log('No mermaid blocks found');
      return;
    }

    console.log(`Found ${mermaidBlocks.length} mermaid blocks, converting...`);

    mermaidBlocks.forEach((block, index) => {
      const mermaidDiv = document.createElement('div');
      mermaidDiv.className = 'mermaid';
      mermaidDiv.id = `mermaid-diagram-${index}`;
      mermaidDiv.textContent = block.textContent;
      block.parentElement.replaceWith(mermaidDiv);
    });

    setTimeout(() => {
      mermaid
        .run()
        .then(() => {
          console.log('Mermaid diagrams rendered successfully');
        })
        .catch((err) => {
          console.error('Mermaid rendering error:', err);
        });
    }, 100);
  }

  // Try multiple event listeners to ensure it runs
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initMermaid);
  } else {
    // DOM already loaded
    initMermaid();
  }

  window.addEventListener('load', () => {
    // Failsafe: run again on window load if diagrams still missing
    if (document.querySelectorAll('.mermaid svg').length === 0) {
      initMermaid();
    }
  });
</script>
