/*
 *  Mermaid.tsx
 *  Zyquo Cloud Web
 *
 *  Author: Simon-Pierre Boucher
 *  Mail: contact@spboucher.ai
 *
 *  Mermaid diagram rendering — the library (~1 MB) is lazy-loaded only when a
 *  ```mermaid block actually appears, keeping the main bundle slim.
 */

import { useEffect, useRef, useState } from 'react'

let mermaidPromise: Promise<typeof import('mermaid')> | null = null
let renderCounter = 0

export default function Mermaid({ code }: { code: string }) {
  const [svg, setSvg] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    let live = true
    mermaidPromise ??= import('mermaid')
    void mermaidPromise
      .then(async (mod) => {
        const mermaid = mod.default
        mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'strict' })
        const { svg } = await mermaid.render(`zyquo-mermaid-${++renderCounter}`, code)
        if (live) setSvg(svg)
      })
      .catch((err: unknown) => {
        if (live) setError(err instanceof Error ? err.message : 'Diagram failed to render')
      })
    return () => {
      live = false
    }
  }, [code])

  if (error) {
    return (
      <div className="code-block">
        <div className="code-block-header">
          <span>mermaid (failed)</span>
        </div>
        <pre>
          <code>{code}</code>
        </pre>
      </div>
    )
  }
  if (!svg) {
    return <div style={{ color: 'var(--z-text-tertiary)', fontSize: 12 }}>Rendering diagram…</div>
  }
  return (
    <div
      ref={ref}
      style={{ overflowX: 'auto', background: 'var(--z-surface)', borderRadius: 10, padding: 8 }}
      dangerouslySetInnerHTML={{ __html: svg }}
    />
  )
}
