// EditorJSRenderer.jsx — renderiza el output de EditorJS como JSX
function EditorJSRenderer({ data }) {
  if (!data || !Array.isArray(data.blocks) || data.blocks.length === 0) {
    return <p className="im-muted">Este artículo aún no tiene contenido.</p>;
  }
  return (
    <>
      {data.blocks.map((block, i) => {
        const k = block.id || `b-${i}`;
        switch (block.type) {
          case 'header': {
            const level = Math.min(Math.max(block.data.level || 2, 2), 4);
            const Tag = `h${level}`;
            return <Tag key={k} dangerouslySetInnerHTML={{ __html: block.data.text || '' }} />;
          }
          case 'paragraph':
            return <p key={k} dangerouslySetInnerHTML={{ __html: block.data.text || '' }} />;
          case 'list': {
            const Tag = block.data.style === 'ordered' ? 'ol' : 'ul';
            return (
              <Tag key={k}>
                {(block.data.items || []).map((it, j) => (
                  <li key={j} dangerouslySetInnerHTML={{ __html: typeof it === 'string' ? it : (it.content || '') }} />
                ))}
              </Tag>
            );
          }
          case 'quote':
            return (
              <blockquote key={k}>
                <span dangerouslySetInnerHTML={{ __html: block.data.text || '' }} />
                {block.data.caption ? <cite> — {block.data.caption}</cite> : null}
              </blockquote>
            );
          case 'code':
            return <pre key={k}><code>{block.data.code || ''}</code></pre>;
          case 'image': {
            const url = block.data.file?.url || block.data.url;
            if (!url) return null;
            return (
              <figure key={k} className="im-article-figure">
                <img src={url} alt={block.data.caption || ''} loading="lazy" />
                {block.data.caption ? <figcaption dangerouslySetInnerHTML={{ __html: block.data.caption }} /> : null}
              </figure>
            );
          }
          case 'delimiter':
            return <hr key={k} />;
          case 'embed': {
            const { embed, caption, height = 320 } = block.data;
            if (!embed) return null;
            return (
              <figure key={k} className="im-article-figure im-article-embed">
                <div className="im-embed-wrap" style={{ paddingBottom: `${Math.round((height / 580) * 100)}%` }}>
                  <iframe
                    src={embed}
                    frameBorder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                    loading="lazy"
                  />
                </div>
                {caption ? <figcaption dangerouslySetInnerHTML={{ __html: caption }} /> : null}
              </figure>
            );
          }
          default:
            return null;
        }
      })}
    </>
  );
}

window.EditorJSRenderer = EditorJSRenderer;
