// rich_text block — HTML from the shared rich-text editor. Rendered inside the
// same `.prose` styling as wiki/news bodies, sanitized on render as defense in
// depth (the server also sanitizes on save).
import { lazy, Suspense } from 'react'
import DOMPurify from 'dompurify'
import { registerBlock } from '../registry'

const RichTextEditor = lazy(() => import('../../components/RichTextEditor.jsx'))

function RichTextBlock({ props }) {
  return (
    <div
      className="prose page-rich-text"
      dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(props.html || '') }}
    />
  )
}

function RichTextEditorForm({ props, onChange }) {
  return (
    <Suspense fallback={<span className="spin" />}>
      <RichTextEditor
        value={props.html || ''}
        onChange={(html) => onChange({ ...props, html })}
        variant="post"
      />
    </Suspense>
  )
}

registerBlock({
  type: 'rich_text',
  version: 1,
  label: 'Rich text',
  icon: '¶',
  component: RichTextBlock,
  editor: RichTextEditorForm,
  defaults: () => ({ html: '' }),
})
