/**
 * Convertit du Markdown Mistral en HTML avec inline styles.
 * Inline styles = zéro dépendance CSS, fonctionne dans tout contexte Vue (scoped, v-html, etc.)
 */
export function useMarkdown() {
  const S = {
    p:      'style="margin:0 0 0.45em;line-height:1.6;"',
    strong: 'style="font-weight:700;"',
    em:     'style="font-style:italic;"',
    h2:     'style="font-weight:700;display:block;margin-bottom:0.2em;"',
    h3:     'style="font-weight:700;display:block;font-size:0.95em;margin-bottom:0.15em;"',
    ul:     'style="margin:0.3em 0 0.3em 1.2em;padding:0;list-style:disc;"',
    li:     'style="margin-bottom:0.15em;"',
    a:      'style="text-decoration:underline;opacity:0.85;"',
  }

  function render(text: string): string {
    if (!text) return ''
    let html = text
      .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
      .replace(/^### (.+)$/gm, `<strong ${S.h3}>$1</strong>`)
      .replace(/^## (.+)$/gm,  `<strong ${S.h2}>$1</strong>`)
      .replace(/^# (.+)$/gm,   `<strong ${S.h2}>$1</strong>`)
      .replace(/\*\*(.+?)\*\*/g, `<strong ${S.strong}>$1</strong>`)
      .replace(/\*(.+?)\*/g,     `<em ${S.em}>$1</em>`)
      .replace(/^[-•]\s+(.+)$/gm, `<li ${S.li}>$1</li>`)
      .replace(/\[([^\]]+)\]\(([^)]+)\)/g, `<a href="$2" target="_blank" rel="noopener" ${S.a}>$1</a>`)

    html = html.replace(/(<li[^>]*>.*<\/li>\n?)+/g, m => `<ul ${S.ul}>${m}</ul>`)
    html = html.replace(/\n{2,}/g, `</p><p ${S.p}>`)
    html = html.replace(/\n/g, '<br>')
    return `<p ${S.p}>${html}</p>`
  }

  return { render }
}
