// 3B Printing — single blog post page (#/blog/<slug>). Mirrors PapersPage's shell:
// header, back link, cover, title, body, footer.

// ponytail: markdown-lite — headings, images, bullets, bold, links. That covers everything
// the blog editor offers; swap in a real parser only if posts start needing tables/code.
// Rendered as React elements (never dangerouslySetInnerHTML), so post text can't inject HTML.
function mdInline(text) {
  const out = [];
  const re = /\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)]+)\)/g;
  let last = 0, m, key = 0;
  while ((m = re.exec(text)) !== null) {
    if (m.index > last) out.push(text.slice(last, m.index));
    if (m[1] !== undefined) {
      out.push(<strong key={key++}>{m[1]}</strong>);
    } else {
      out.push(
        <a key={key++} href={m[3]} target="_blank" rel="noopener noreferrer"
          style={{ color: 'var(--accent-copper)' }}>{m[2]}</a>
      );
    }
    last = re.lastIndex;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
}

function Markdown({ text, lang }) {
  const blocks = String(text || '').replace(/\r\n/g, '\n').split(/\n{2,}/).map((b) => b.trim()).filter(Boolean);
  const bodyStyle = {
    margin: '0 0 var(--space-5)', fontSize: 'var(--text-body-size)',
    lineHeight: lang === 'th' ? 'var(--leading-body-thai)' : 'var(--leading-body)',
    color: 'var(--ink-soft)', whiteSpace: 'pre-line',
  };
  return (
    <div>
      {blocks.map((block, i) => {
        const img = block.match(/^!\[([^\]]*)\]\(([^)]+)\)$/);
        if (img) {
          return (
            <figure key={i} style={{ margin: '0 0 var(--space-6)' }}>
              <img src={img[2]} alt={img[1]} style={{ width: '100%', borderRadius: 'var(--radius-card)', display: 'block' }} />
              {img[1] ? (
                <figcaption style={{ marginTop: 'var(--space-2)', fontSize: 'var(--text-caption)', color: 'var(--ink-faint)' }}>{img[1]}</figcaption>
              ) : null}
            </figure>
          );
        }
        const head = block.match(/^(#{2,3})\s+(.*)$/);
        if (head) {
          const big = head[1].length === 2;
          return (
            <h2 key={i} style={{
              margin: 'var(--space-6) 0 var(--space-3)',
              fontFamily: lang === 'th' ? 'var(--font-heading-thai)' : 'var(--font-heading)',
              fontSize: big ? 24 : 19,
              lineHeight: lang === 'th' ? 'var(--leading-h3-thai)' : 'var(--leading-h3)',
              color: 'var(--ink)', fontWeight: 600,
            }}>{mdInline(head[2])}</h2>
          );
        }
        if (block.split('\n').every((line) => /^[-*]\s+/.test(line))) {
          return (
            <ul key={i} style={{ ...bodyStyle, whiteSpace: 'normal', paddingLeft: '1.25em' }}>
              {block.split('\n').map((line, j) => (
                <li key={j} style={{ marginBottom: 'var(--space-1)' }}>{mdInline(line.replace(/^[-*]\s+/, ''))}</li>
              ))}
            </ul>
          );
        }
        return <p key={i} style={bodyStyle}>{mdInline(block)}</p>;
      })}
    </div>
  );
}

function BlogPostPage({ lang, setLang, route, cms, slug }) {
  const { t, Header, SectionTitle, SiteFooter } = window.Shared;
  const s = t[lang];
  const footerContent = cms.sections.footer && cms.sections.footer.content;
  const post = cms.blogPosts.find((p) => p.slug === slug);

  React.useEffect(() => { window.scrollTo(0, 0); }, [slug]);

  const section = { maxWidth: 760, margin: '0 auto', padding: 'var(--space-9) var(--space-6) var(--space-9)' };
  const backLink = (
    <a href={window.Shared.url('/')} style={{ display: 'inline-block', marginBottom: 'var(--space-5)', color: 'var(--ink-faint)', textDecoration: 'none', fontSize: 14 }}>
      {s.backHome}
    </a>
  );

  return (
    <div className="page-mobile-pad" style={{ background: 'var(--bg-light)', fontFamily: 'var(--font-body)', color: 'var(--ink)', minHeight: '100vh' }}>
      <Header lang={lang} setLang={setLang} route={route} footerContent={footerContent} />
      <article style={section}>
        {backLink}
        {post ? (
          <React.Fragment>
            {(lang === 'th' ? post.dateTh : post.dateEn) ? (
              <div style={{ fontSize: 'var(--text-caption)', color: 'var(--ink-faint)', marginBottom: 'var(--space-2)' }}>
                {lang === 'th' ? post.dateTh : post.dateEn}
              </div>
            ) : null}
            <SectionTitle lang={lang}>{lang === 'th' ? post.titleTh : (post.titleEn || post.titleTh)}</SectionTitle>
            {post.src || (post.images && post.images.length) ? (
              <img src={post.src || post.images[0]} alt=""
                style={{ width: '100%', borderRadius: 'var(--radius-card)', margin: '0 0 var(--space-6)', display: 'block' }} />
            ) : null}
            <Markdown text={lang === 'th' ? post.bodyTh : (post.bodyEn || post.bodyTh)} lang={lang} />
          </React.Fragment>
        ) : (
          <p style={{ color: 'var(--ink-faint)' }}>{lang === 'th' ? 'ไม่พบบทความนี้' : 'Post not found.'}</p>
        )}
      </article>
      <SiteFooter lang={lang} footer={footerContent} />
    </div>
  );
}

window.BlogPostPage = BlogPostPage;
