import { notFound } from 'next/navigation'
import { getPublishedNote } from '@/app/actions/notes-publishing'
import { Flag, Sparkles } from 'lucide-react'
import { format } from 'date-fns'
import { fr } from 'date-fns/locale'
import { computePublishedSourceHash } from '@/lib/publish/template-render'
import { processNoteHtmlForPublish } from '@/lib/publish/process-note-html'
import { REWRITE_SHARED_CSS, KATEX_PUBLISH_CSS } from '@/lib/publish/shared-css'

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const note = await getPublishedNote(slug)
  if (!note) return { title: 'Note introuvable — Memento' }
  return {
    title: `${note.title || 'Note publiée'} — Memento`,
    description: note.content?.replace(/<[^>]+>/g, '').slice(0, 160),
  }
}

export const revalidate = 60

function estimateReadingTime(html: string): number {
  const words = html.replace(/<[^>]+>/g, ' ').trim().split(/\s+/).length
  return Math.max(1, Math.ceil(words / 200))
}

/* ─── MAGAZINE ──────────────────────────────────────────────────────────── */
function MagazinePage({ note, bodyHtml, readingTime, slug, isStale }: PageProps) {
  return (
    <>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
      <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;0,900;1,700&family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500&display=swap" rel="stylesheet" />

      <div className="mag-root">
        <nav className="mag-nav">
          <span className="mag-nav-brand">Memento</span>
          <div className="mag-nav-right">
            <span className="mag-badge"><Sparkles size={10} /> Article</span>
            <a href={`/p/${slug}/report`} className="mag-report"><Flag size={11} /> Signaler</a>
          </div>
        </nav>

        {/* Header pleine largeur */}
        <header className="mag-header">
          <div className="mag-header-inner">
            <div className="mag-category">ARTICLE · {note.publishedAt ? format(new Date(note.publishedAt), 'd MMMM yyyy', { locale: fr }) : ''} · {readingTime} min</div>
            <h1 className="mag-title">{note.title || 'Sans titre'}</h1>
            {note.user?.name && (
              <div className="mag-author">
                {note.user.image && <img src={note.user.image} alt="" className="mag-avatar" />}
                <span>par <strong>{note.user.name}</strong></span>
              </div>
            )}
          </div>
        </header>

        <div className="mag-content">
          <div dir="auto" className="mag-body pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
        </div>

        <footer className="mag-footer">
          <span>Memento</span> — Votre mémoire augmentée par l&rsquo;IA
          {isStale && <p className="mag-stale">Le contenu source a évolué depuis la dernière publication.</p>}
        </footer>
      </div>

      <style>{`
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        .mag-root { min-height: 100vh; background: #fff; color: #111; font-family: 'Inter', sans-serif; }

        .mag-nav {
          position: sticky; top: 0; z-index: 20;
          background: #111; color: #fff;
          display: flex; align-items: center; justify-content: space-between;
          padding: 12px 28px;
        }
        .mag-nav-brand { font-family: 'Playfair Display', serif; font-size: 17px; font-weight: 900; letter-spacing: 0.04em; }
        .mag-nav-right { display: flex; align-items: center; gap: 12px; }
        .mag-badge { display: flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 600; letter-spacing: 0.12em; color: #f5c96a; text-transform: uppercase; }
        .mag-report { display: flex; align-items: center; gap: 4px; font-size: 11px; color: rgba(255,255,255,0.45); text-decoration: none; }
        .mag-report:hover { color: #fff; }

        .mag-header { background: #111; color: #fff; padding: 64px 28px 72px; text-align: center; }
        .mag-header-inner { max-width: 780px; margin: 0 auto; }
        .mag-category { font-size: 11px; font-weight: 600; letter-spacing: 0.2em; color: #f5c96a; text-transform: uppercase; margin-bottom: 28px; }
        .mag-title {
          font-family: 'Playfair Display', Georgia, serif;
          font-size: clamp(36px, 7vw, 72px);
          font-weight: 900; line-height: 1.05; letter-spacing: -0.02em;
          margin-bottom: 28px;
        }
        .mag-author { display: inline-flex; align-items: center; gap: 10px; font-size: 14px; color: rgba(255,255,255,0.65); }
        .mag-avatar { width: 30px; height: 30px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.2); }

        .mag-content { max-width: 760px; margin: 0 auto; padding: 64px 28px 80px; }

        /* Body article magazine */
        .mag-body { font-family: 'Source Serif 4', Georgia, serif; font-size: 19px; line-height: 1.85; color: #1a1a1a; }
        .mag-body .pub-tpl { all: unset; display: block; }

        .mag-body .pub-magazine-dek {
          font-size: 1.3em; line-height: 1.6; color: #333; margin-bottom: 2.5em;
          padding-bottom: 2em; border-bottom: 2px solid #111;
          font-style: italic;
        }
        .mag-body .pub-pull-quote {
          font-family: 'Playfair Display', serif;
          font-size: clamp(1.5em, 4vw, 2em); font-style: italic; font-weight: 700;
          color: #111; line-height: 1.35;
          margin: 2.5em 0; padding: 0;
          border: none; border-top: 4px solid #f5c96a; border-bottom: 4px solid #f5c96a;
          padding: 1.5em 0; text-align: center;
        }
        .mag-body .pub-pull-quote p { margin: 0; }

        .mag-body .pub-hero { margin: 0 -28px 3rem; border-radius: 0; max-height: 560px; aspect-ratio: 16/9; background: #222; overflow: hidden; }
        .mag-body .pub-hero-img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .mag-body .pub-body-source { }
        .mag-body h2 { font-family: 'Playfair Display', serif; font-size: 1.6em; font-weight: 700; margin-top: 2.5em; margin-bottom: 0.6em; }
        .mag-body h3 { font-size: 1.2em; font-weight: 600; margin-top: 2em; margin-bottom: 0.5em; }
        .mag-body p { margin: 1.1em 0; }
        .mag-body blockquote { border-left: 4px solid #f5c96a; padding-left: 1.2em; margin: 1.5em 0; color: #444; font-style: italic; }
        .mag-body ul, .mag-body ol { padding-left: 1.5em; margin: 1em 0; }
        .mag-body li { margin: 0.4em 0; }
        .mag-body pre { background: #f6f6f4; padding: 20px; border-radius: 8px; overflow-x: auto; font-size: 14px; margin: 1.5em 0; }
        .mag-body code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.88em; background: #f3f2ef; padding: 1px 5px; border-radius: 3px; }
        .mag-body pre code { background: none; padding: 0; }
        .mag-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; }
        .mag-body th { background: #111; color: #fff; padding: 10px 14px; text-align: left; font-size: 13px; letter-spacing: 0.05em; }
        .mag-body td { border-bottom: 1px solid #e5e5e5; padding: 10px 14px; }
        .mag-body a { color: #b8832a; text-decoration: underline; text-underline-offset: 3px; }
        .mag-body .pub-figure { margin: 2.5em 0; text-align: center; }
        .mag-body .pub-figure-img { max-width: 100%; border-radius: 4px; box-shadow: 0 12px 40px rgba(0,0,0,0.12); }
        .mag-body .pub-figure-caption { margin-top: 0.6em; font-size: 0.82em; color: #888; font-style: italic; }
        .mag-body .pub-gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-top: 3em; }
        .mag-body .pub-gallery-img { width: 100%; height: 200px; object-fit: cover; border-radius: 4px; display: block; }
        .mag-body .pub-callout { border-radius: 6px; padding: 14px 18px; margin: 1.5em 0; }
        ${KATEX_PUBLISH_CSS}

        .mag-footer { background: #111; color: rgba(255,255,255,0.4); padding: 36px 28px; text-align: center; font-size: 13px; font-family: 'Playfair Display', serif; }
        .mag-footer span { color: #f5c96a; font-weight: 700; }
        .mag-stale { margin-top: 8px; font-size: 11px; color: rgba(255,255,255,0.25); font-family: 'Inter', sans-serif; }

        @media (min-width: 900px) {
          .mag-body .pub-hero { margin-left: -60px; margin-right: -60px; }
          .mag-content { padding-left: 60px; padding-right: 60px; }
        }

        /* Variables magazine pour blocs réécriture — accents dorés, texte toujours lisible */
        .mag-body {
          --pub-accent: #9a7212;
          --pub-summary-color: #333;
          --pub-exercise-border: #e0d4c3;
          --pub-exercise-header-bg: #faf6ee;
          --pub-solution-bg: #faf6ee;
          --pub-definition-border: #e0d4c3;
          --pub-definition-bg: #fafaf8;
          --pub-toggle-border: #e5e5e5;
          --pub-toggle-header-bg: #f7f7f5;
          --pub-highlight-bg: #faf6ee;
          --pub-checklist-bg: rgba(0,0,0,0.03);
        }
        .mag-body .pub-rewrite-body .pub-code { background: #0d0d0d; }
        .mag-body .pub-rewrite-body .pub-code code { background: #0d0d0d; color: #e8e3d5; }
        .mag-body .pub-rewrite-body .pub-definition-term { background: #e8c96a; color: #1a1a1a; }
        .mag-body .pub-rewrite-body .pub-step-num { background: #9a7212; color: #fff; }
        .mag-body .pub-rewrite-body .pub-exercise-num { color: #9a7212; }
        .mag-body .pub-rewrite-body .pub-solution > summary { color: #9a7212; }
        .mag-body .pub-rewrite-body .pub-checklist li::before { color: #9a7212; }
        .mag-body .pub-magazine-dek { color: #333; }
        ${REWRITE_SHARED_CSS}
      `}</style>
    </>
  )
}

/* ─── BRIEF ─────────────────────────────────────────────────────────────── */
function BriefPage({ note, bodyHtml, readingTime, slug, isStale }: PageProps) {
  return (
    <>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet" />

      <div className="br-root">
        <nav className="br-nav">
          <span className="br-brand">Memento</span>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <span className="br-badge"><Sparkles size={9} /> Fiche expert</span>
            <a href={`/p/${slug}/report`} className="br-report"><Flag size={11} /></a>
          </div>
        </nav>

        <header className="br-header">
          <div className="br-header-inner">
            <div className="br-meta">
              <span className="br-tag">Fiche expert</span>
              <span className="br-dot">·</span>
              <span>{readingTime} min de lecture</span>
              {note.publishedAt && <><span className="br-dot">·</span><span>{format(new Date(note.publishedAt), 'd MMM yyyy', { locale: fr })}</span></>}
            </div>
            <h1 className="br-title">{note.title || 'Sans titre'}</h1>
            {note.user?.name && (
              <div className="br-author">
                {note.user.image && <img src={note.user.image} alt="" className="br-avatar" />}
                <span>{note.user.name}</span>
              </div>
            )}
          </div>
        </header>

        <div className="br-layout">
          <div className="br-content">
            <div dir="auto" className="br-body pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
          </div>
        </div>

        <footer className="br-footer">
          <strong>Memento</strong> — Fiche générée par IA
          {isStale && <p style={{ fontSize: 11, color: '#aaa', marginTop: 6 }}>Le contenu source a évolué depuis la publication.</p>}
        </footer>
      </div>

      <style>{`
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        .br-root { min-height: 100vh; background: #F4F6F9; color: #1a2433; font-family: 'DM Sans', system-ui, sans-serif; }

        .br-nav {
          position: sticky; top: 0; z-index: 20; background: #fff;
          border-bottom: 1px solid #e8ecf2;
          display: flex; align-items: center; justify-content: space-between;
          padding: 10px 28px;
        }
        .br-brand { font-weight: 700; font-size: 15px; color: #1a2433; }
        .br-badge { display: flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 600; color: #2563eb; background: #eff6ff; padding: 3px 8px; border-radius: 20px; letter-spacing: 0.04em; }
        .br-report { color: #aaa; text-decoration: none; display: flex; }
        .br-report:hover { color: #666; }

        .br-header { background: linear-gradient(135deg, #1e3a5f 0%, #0f1f35 100%); color: #fff; padding: 56px 28px 60px; }
        .br-header-inner { max-width: 820px; margin: 0 auto; }
        .br-meta { display: flex; align-items: center; gap: 8px; font-size: 12px; color: rgba(255,255,255,0.55); font-weight: 500; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 20px; }
        .br-tag { background: #2563eb; color: #fff; font-size: 10px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; padding: 3px 8px; border-radius: 4px; }
        .br-dot { color: rgba(255,255,255,0.3); }
        .br-title { font-size: clamp(24px, 4.5vw, 44px); font-weight: 700; line-height: 1.2; letter-spacing: -0.02em; margin-bottom: 24px; }
        .br-author { display: flex; align-items: center; gap: 8px; font-size: 13px; color: rgba(255,255,255,0.5); }
        .br-avatar { width: 26px; height: 26px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.2); }

        .br-layout { max-width: 820px; margin: 0 auto; padding: 48px 28px 80px; }

        .br-body { font-size: 16px; line-height: 1.75; color: #1a2433; }
        .br-body .pub-tpl { all: unset; display: block; }

        /* Brief lead summary */
        .br-body .pub-brief-lead {
          background: #fff; border-radius: 12px;
          border-left: 5px solid #2563eb;
          padding: 24px 28px; margin-bottom: 2em;
          box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        }
        .br-body .pub-brief-lead p { margin: 0; font-size: 1.08em; line-height: 1.75; color: #1a2433; font-weight: 500; }

        /* Key points */
        .br-body .pub-key-points {
          background: #fff; border-radius: 12px; padding: 24px 28px;
          margin-bottom: 2em; box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        }
        .br-body .pub-key-points-label {
          font-size: 10px; text-transform: uppercase; letter-spacing: 0.2em;
          font-weight: 700; color: #2563eb; margin-bottom: 14px; display: block;
        }
        .br-body .pub-key-points ul { list-style: none; padding: 0; margin: 0; }
        .br-body .pub-key-points li {
          padding: 10px 12px 10px 40px; border-radius: 8px;
          background: #f4f6f9; margin-bottom: 8px; position: relative;
          font-size: 0.95em; font-weight: 500;
        }
        .br-body .pub-key-points li::before {
          content: '✓'; position: absolute; left: 12px; top: 10px;
          color: #2563eb; font-weight: 700; font-size: 14px;
        }

        /* Source body */
        .br-body .pub-body-source {
          background: #fff; border-radius: 12px; padding: 32px 36px;
          box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        }

        .br-body .pub-hero { margin: 0 0 2rem; border-radius: 12px; overflow: hidden; max-height: 400px; aspect-ratio: 16/9; background: #dce3ed; }
        .br-body .pub-hero-img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .br-body h2 { font-size: 1.25em; font-weight: 700; margin-top: 2em; margin-bottom: 0.6em; color: #0f1f35; border-bottom: 2px solid #e8ecf2; padding-bottom: 0.4em; }
        .br-body h3 { font-size: 1.08em; font-weight: 600; margin-top: 1.5em; margin-bottom: 0.4em; color: #1e3a5f; }
        .br-body p { margin: 0.9em 0; }
        .br-body blockquote { border-left: 4px solid #2563eb; padding-left: 1em; margin: 1.2em 0; color: #3d5a80; font-style: italic; }
        .br-body ul, .br-body ol { padding-left: 1.4em; margin: 1em 0; }
        .br-body li { margin: 0.4em 0; }
        .br-body pre { background: #1a2433; color: #e2e8f0; padding: 20px; border-radius: 10px; overflow-x: auto; font-size: 13px; margin: 1.5em 0; font-family: 'DM Mono', monospace; }
        .br-body code { font-family: 'DM Mono', monospace; font-size: 0.87em; background: #e8ecf2; padding: 1px 5px; border-radius: 3px; color: #1e3a5f; }
        .br-body pre code { background: none; color: inherit; padding: 0; }
        .br-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; border-radius: 8px; overflow: hidden; }
        .br-body th { background: #1e3a5f; color: #fff; padding: 10px 14px; text-align: left; font-size: 13px; }
        .br-body td { border-bottom: 1px solid #e8ecf2; padding: 10px 14px; }
        .br-body tr:last-child td { border-bottom: none; }
        .br-body a { color: #2563eb; text-decoration: underline; text-underline-offset: 3px; }
        .br-body .pub-figure { margin: 2em 0; text-align: center; }
        .br-body .pub-figure-img { max-width: 100%; border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
        .br-body .pub-figure-caption { margin-top: 0.5em; font-size: 0.82em; color: #7a8fa6; }
        .br-body .pub-gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin-top: 2em; }
        .br-body .pub-gallery-img { width: 100%; height: 160px; object-fit: cover; border-radius: 8px; display: block; }
        .br-body .pub-callout { border-radius: 8px; padding: 12px 16px; margin: 1.2em 0; }
        ${KATEX_PUBLISH_CSS}

        .br-footer { background: #0f1f35; color: rgba(255,255,255,0.35); padding: 32px 28px; text-align: center; font-size: 13px; }
        .br-footer strong { color: #fff; }

        /* Variables brief pour blocs réécriture */
        .br-body {
          --pub-accent: #2563eb;
          --pub-summary-color: #3d5a80;
          --pub-exercise-border: #bfdbfe;
          --pub-exercise-header-bg: #eff6ff;
          --pub-solution-bg: #f0f7ff;
          --pub-definition-border: #bfdbfe;
          --pub-definition-bg: #f8faff;
          --pub-toggle-border: #e2e8f0;
          --pub-toggle-header-bg: #f8fafc;
          --pub-highlight-bg: #eff6ff;
          --pub-checklist-bg: #f4f6f9;
        }
        .br-body .pub-rewrite-body .pub-code { background: #1a2433; }
        .br-body .pub-rewrite-body .pub-code code { background: #1a2433; color: #e2e8f0; }
        .br-body .pub-rewrite-body .pub-body-source {
          background: #fff; border-radius: 12px; padding: 32px 36px;
          box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        }
        ${REWRITE_SHARED_CSS}
      `}</style>
    </>
  )
}

/* ─── ESSAY ──────────────────────────────────────────────────────────────── */
function EssayPage({ note, bodyHtml, readingTime, slug, isStale }: PageProps) {
  return (
    <>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
      <link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,600;1,400;1,600&family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500&display=swap" rel="stylesheet" />

      <div className="es-root">
        <nav className="es-nav">
          <span className="es-brand">Memento</span>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <span className="es-badge"><Sparkles size={10} /> Essai</span>
            <a href={`/p/${slug}/report`} className="es-report"><Flag size={11} /></a>
          </div>
        </nav>

        <main className="es-main">
          <div className="es-rule-top" />
          <header className="es-header">
            {note.publishedAt && (
              <time className="es-date">{format(new Date(note.publishedAt), 'd MMMM yyyy', { locale: fr })}</time>
            )}
            <h1 className="es-title">{note.title || 'Sans titre'}</h1>
            <div className="es-rule-thin" />
            {note.user?.name && (
              <div className="es-author">
                {note.user.image && <img src={note.user.image} alt="" className="es-avatar" />}
                <div>
                  <span className="es-author-name">{note.user.name}</span>
                  <span className="es-reading-time">{readingTime} min de lecture</span>
                </div>
              </div>
            )}
          </header>

          <div dir="auto" className="es-body pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />

          <div className="es-rule-thin" style={{ marginTop: '4rem' }} />
          <footer className="es-footer">
            Publié sur <strong>Memento</strong>
            {isStale && <p style={{ fontSize: 11, color: '#bbb', marginTop: 6 }}>Le contenu source a évolué depuis la publication.</p>}
          </footer>
        </main>
      </div>

      <style>{`
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        .es-root { min-height: 100vh; background: #FDFBF7; color: #2c2416; font-family: 'Inter', sans-serif; }

        .es-nav {
          position: sticky; top: 0; z-index: 20;
          background: rgba(253,251,247,0.9); backdrop-filter: blur(10px);
          border-bottom: 1px solid #e8e0d0;
          display: flex; align-items: center; justify-content: space-between;
          padding: 12px 40px;
        }
        .es-brand { font-family: 'Lora', Georgia, serif; font-size: 16px; font-style: italic; color: #5c4a2a; }
        .es-badge { display: flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 500; color: #8b6c3a; font-family: 'Inter', sans-serif; }
        .es-report { color: #bbb; text-decoration: none; display: flex; }
        .es-report:hover { color: #666; }

        .es-main { max-width: 680px; margin: 0 auto; padding: 60px 36px 100px; }
        .es-rule-top { width: 60px; height: 3px; background: #5c4a2a; margin: 48px auto 0; }

        .es-header { text-align: center; padding: 40px 0 36px; }
        .es-date { display: block; font-size: 12px; font-weight: 500; letter-spacing: 0.15em; text-transform: uppercase; color: #a08b5c; margin-bottom: 24px; }
        .es-title {
          font-family: 'Lora', Georgia, serif;
          font-size: clamp(28px, 5vw, 52px);
          font-weight: 600; font-style: italic; line-height: 1.2;
          letter-spacing: -0.01em; color: #1e160c;
          margin-bottom: 32px;
        }
        .es-rule-thin { height: 1px; background: #d8cebc; margin: 0 auto; width: 100%; }
        .es-author { display: flex; align-items: center; gap: 12px; margin-top: 24px; justify-content: center; }
        .es-avatar { width: 40px; height: 40px; border-radius: 50%; border: 2px solid #d8cebc; }
        .es-author-name { display: block; font-size: 14px; font-weight: 600; color: #3d2f14; }
        .es-reading-time { display: block; font-size: 12px; color: #a08b5c; }

        /* Essay body */
        .es-body { margin-top: 52px; font-family: 'Lora', Georgia, serif; font-size: 19px; line-height: 2; color: #2c2416; }
        .es-body .pub-tpl { all: unset; display: block; }

        /* Epigraph avec guillemet décoratif */
        .es-body .pub-epigraph {
          position: relative;
          text-align: center; font-size: 1.15em; font-style: italic; color: #6b5337;
          margin: 0 0 3em; padding: 1.5em 2.5em 1em;
          border-top: 1px solid #d8cebc; border-bottom: 1px solid #d8cebc;
        }
        .es-body .pub-epigraph::before {
          content: '"';
          position: absolute; top: -0.3em; left: 50%; transform: translateX(-50%);
          font-family: 'Lora', Georgia, serif; font-size: 5em; color: #d8cebc;
          line-height: 1; pointer-events: none; font-style: normal;
        }

        .es-body .pub-essay-summary {
          font-size: 1.15em; line-height: 1.8; color: #4a3726;
          margin-bottom: 2.5em; font-style: italic;
          padding-left: 1.5em; border-left: 2px solid #c8b99a;
        }

        .es-body .pub-body-source p { text-indent: 1.8em; }
        .es-body .pub-body-source p:first-of-type { text-indent: 0; }
        .es-body .pub-body-source > p:first-child { text-indent: 0; }

        .es-body .pub-hero { margin: 0 -36px 3em; overflow: hidden; border-radius: 0; max-height: 480px; aspect-ratio: 16/9; background: #e8e0d0; }
        .es-body .pub-hero-img { width: 100%; height: 100%; object-fit: cover; display: block; filter: sepia(10%); }
        .es-body h2 { font-family: 'Lora', serif; font-size: 1.45em; font-style: italic; font-weight: 600; margin-top: 2.5em; margin-bottom: 0.7em; color: #1e160c; }
        .es-body h3 { font-family: 'Lora', serif; font-size: 1.2em; font-weight: 600; margin-top: 2em; margin-bottom: 0.5em; }
        .es-body p { margin: 0 0 0.2em; }
        .es-body blockquote {
          border: none; margin: 2em 0; padding: 0 2em;
          font-size: 1.15em; color: #5c4a2a; font-style: italic;
          text-align: center; position: relative;
        }
        .es-body ul, .es-body ol { padding-left: 1.4em; margin: 1em 0; }
        .es-body li { margin: 0.5em 0; }
        .es-body pre { background: #f2ede4; padding: 20px; border-radius: 6px; overflow-x: auto; font-family: 'SF Mono', Menlo, monospace; font-size: 13px; margin: 1.5em 0; }
        .es-body code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.85em; background: #ede7da; padding: 1px 5px; border-radius: 3px; }
        .es-body pre code { background: none; padding: 0; }
        .es-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; }
        .es-body th { border-bottom: 2px solid #5c4a2a; padding: 8px 12px; text-align: left; font-size: 14px; color: #5c4a2a; }
        .es-body td { border-bottom: 1px solid #e8e0d0; padding: 8px 12px; }
        .es-body a { color: #7a5c2e; text-decoration: underline; text-decoration-style: dotted; text-underline-offset: 3px; }
        .es-body .pub-figure { margin: 2.5em 0; text-align: center; }
        .es-body .pub-figure-img { max-width: 100%; border-radius: 2px; box-shadow: 0 6px 24px rgba(0,0,0,0.1); filter: sepia(5%); }
        .es-body .pub-figure-caption { margin-top: 0.65em; font-size: 0.8em; color: #9a8470; font-style: italic; }
        .es-body .pub-gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin-top: 2.5em; }
        .es-body .pub-gallery-img { width: 100%; height: 160px; object-fit: cover; border-radius: 2px; display: block; filter: sepia(8%); }
        .es-body .pub-callout { border-radius: 4px; padding: 12px 16px; margin: 1.5em 0; }
        ${KATEX_PUBLISH_CSS}

        .es-footer { text-align: center; padding: 32px 0 0; font-size: 13px; color: #a08b5c; font-family: 'Inter', sans-serif; }
        .es-footer strong { color: #5c4a2a; }

        /* Variables essay pour blocs réécriture */
        .es-body {
          --pub-accent: #7a5c2e;
          --pub-summary-color: #5c4a2a;
          --pub-exercise-border: #d8cebc;
          --pub-exercise-header-bg: #f5f0e8;
          --pub-solution-bg: rgba(122,92,46,0.05);
          --pub-definition-border: #d8cebc;
          --pub-definition-bg: #fdfbf7;
          --pub-toggle-border: #e2d9ca;
          --pub-toggle-header-bg: #f7f3ec;
          --pub-highlight-bg: #fdf6eb;
          --pub-checklist-bg: rgba(0,0,0,0.025);
        }
        .es-body .pub-rewrite-body .pub-code { background: #2c2416; }
        .es-body .pub-rewrite-body .pub-code code { background: #2c2416; color: #f0e8da; }
        ${REWRITE_SHARED_CSS}
      `}</style>
    </>
  )
}

/* ─── SIMPLE (pas d'IA) ─────────────────────────────────────────────────── */
function SimplePage({ note, bodyHtml, readingTime, slug }: PageProps) {
  return (
    <>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
      <link href="https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />

      <div style={{ minHeight: '100vh', background: '#FAF9F5', color: '#1a1a1a', fontFamily: "'Inter', sans-serif" }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'rgba(250,249,245,0.9)', backdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(0,0,0,0.06)', padding: '10px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: "'Source Serif 4', serif", fontWeight: 600, fontSize: '15px' }}>Memento</span>
          <a href={`/p/${slug}/report`} style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '12px', color: '#888', textDecoration: 'none', padding: '4px 10px', borderRadius: '6px', border: '1px solid rgba(0,0,0,0.1)' }}><Flag size={12} /> Signaler</a>
        </div>
        <article style={{ maxWidth: '720px', margin: '0 auto', padding: '48px 24px 80px' }}>
          <div style={{ fontSize: '12px', color: '#999', marginBottom: '16px' }}>
            {note.publishedAt ? format(new Date(note.publishedAt), 'd MMM yyyy', { locale: fr }) : ''} · {readingTime} min de lecture
          </div>
          <h1 style={{ fontFamily: "'Source Serif 4', Georgia, serif", fontSize: 'clamp(28px,5vw,40px)', fontWeight: 600, lineHeight: 1.2, letterSpacing: '-0.02em', margin: '0 0 12px' }}>{note.title || 'Sans titre'}</h1>
          {note.user?.name && (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '36px' }}>
              {note.user.image && <img src={note.user.image} alt="" style={{ width: '28px', height: '28px', borderRadius: '50%' }} />}
              <span style={{ fontSize: '14px', color: '#666' }}>par {note.user.name}</span>
            </div>
          )}
          <div style={{ height: '1px', background: 'rgba(0,0,0,0.08)', marginBottom: '36px' }} />
          <div dir="auto" className="pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
          <style>{`
            .pub-article { font-family: 'Source Serif 4', Georgia, serif; font-size: 17px; line-height: 1.85; }
            .pub-article h2, .pub-article h3 { font-weight: 600; margin-top: 1.8em; margin-bottom: 0.6em; }
            .pub-article h2 { font-size: 1.4em; }
            .pub-article h3 { font-size: 1.15em; }
            .pub-article p { margin: 1em 0; }
            .pub-article ul, .pub-article ol { padding-left: 1.5em; margin: 1em 0; }
            .pub-article li { margin: 0.4em 0; }
            .pub-article blockquote { border-left: 3px solid #A47148; padding-left: 1em; margin: 1.2em 0; color: #555; font-style: italic; }
            .pub-article pre { background: #f4f3ef; padding: 16px; border-radius: 8px; overflow-x: auto; font-size: 14px; margin: 1.2em 0; }
            .pub-article code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.87em; }
            .pub-article table { border-collapse: collapse; width: 100%; margin: 1.2em 0; }
            .pub-article th, .pub-article td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
            .pub-article th { background: #f4f3ef; font-weight: 600; }
            .pub-article a { color: #A47148; text-decoration: underline; text-underline-offset: 3px; }
            .pub-article .pub-figure { margin: 2em 0; text-align: center; }
            .pub-article .pub-figure-img { max-width: 100%; border-radius: 8px; box-shadow: 0 6px 24px rgba(0,0,0,0.08); }
            .pub-article .pub-figure-caption { margin-top: 0.6em; font-size: 0.82em; color: #888; font-style: italic; }
            .pub-article .pub-callout { border-radius: 8px; padding: 12px 16px; margin: 1em 0; }
            ${KATEX_PUBLISH_CSS}
          `}</style>
        </article>
        <footer style={{ borderTop: '1px solid rgba(0,0,0,0.08)', padding: '28px 24px', textAlign: 'center', fontSize: '13px', color: '#999' }}>
          <span style={{ fontFamily: "'Source Serif 4', serif", fontWeight: 600, color: '#A47148' }}>Memento</span>
          {' — Votre mémoire augmentée par l\'IA'}
        </footer>
      </div>
    </>
  )
}

/* ─── Types ─────────────────────────────────────────────────────────────── */
type NoteData = NonNullable<Awaited<ReturnType<typeof getPublishedNote>>>
interface PageProps {
  note: NoteData
  bodyHtml: string
  readingTime: number
  slug: string
  isStale: boolean
}

/* ─── Route ──────────────────────────────────────────────────────────────── */
export default async function PublishedNotePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const note = await getPublishedNote(slug)
  if (!note) notFound()

  const usesAiLayout = Boolean(note.publishedContent)
  const rawHtml = usesAiLayout ? note.publishedContent! : (note.content || '')
  // Toujours passer par processNoteHtmlForPublish : KaTeX + sanitisation compatible équations
  const bodyHtml = processNoteHtmlForPublish(rawHtml)

  const readingSource = usesAiLayout ? note.publishedContent! : (note.content || '')
  const readingTime = estimateReadingTime(readingSource)
  const isStale = Boolean(
    note.publishedSourceHash
    && computePublishedSourceHash(note.content || '') !== note.publishedSourceHash
  )

  const props: PageProps = { note, bodyHtml, readingTime, slug, isStale }

  if (!usesAiLayout) return <SimplePage {...props} />
  if (note.publishedTemplate === 'brief') return <BriefPage {...props} />
  if (note.publishedTemplate === 'essay') return <EssayPage {...props} />
  return <MagazinePage {...props} />
}
