import type { PageSection } from '../../../lib/page-editor-service.js'
import { bool, str, type PostRenderContext } from './parts.js'

/**
 * Renders the post's main body. When `source === 'field'` it shows the
 * post's own Body field (passed via context); otherwise it renders the
 * section's own `body` copy.
 *
 * The Body field is a `richText` field (sanitized HTML on write), so this
 * canvas preview renders it as HTML — exactly like the public site's
 * article-body renderer — to stay WYSIWYG. It previews the author's own
 * in-progress draft; the server sanitizes (sanitize-html) on save.
 */
export function ArticleBodySection({
  section,
  context,
}: {
  section: PageSection
  context?: PostRenderContext
}) {
  const c = section.content
  const source = str(c, 'source', 'field')
  const html = source === 'field' ? (context?.body ?? '') : str(c, 'body')
  const wide = str(c, 'width', 'normal') === 'wide'
  const showToc = bool(c, 'showToc')

  return (
    <div className={`mx-auto px-6 ${wide ? 'max-w-4xl' : 'max-w-2xl'}`}>
      {showToc && (
        <div className="border-border bg-muted mb-8 rounded-lg border p-4">
          <p className="text-muted-foreground text-xs font-semibold tracking-wider uppercase">
            On this page
          </p>
          <p className="text-muted-foreground mt-1 text-sm">
            A table of contents will be generated from the body headings.
          </p>
        </div>
      )}
      {html.trim() ? (
        <div
          className="prose prose-zinc text-foreground max-w-none text-base leading-relaxed"
          dangerouslySetInnerHTML={{ __html: html }}
        />
      ) : (
        <p className="text-muted-foreground text-base leading-relaxed italic">
          {source === 'field'
            ? "This will show the post's Body content."
            : 'Add body copy in the inspector.'}
        </p>
      )}
    </div>
  )
}
