/**
 * app/share/artifact-content.jsx — Shared artifact render block for public share
 * pages. Plain (no 'use client') so it works in both the server-rendered space
 * page and the client-side OTP gate.
 *
 * XSS safety mirrors app/share/[token]/page.js: markdown is escaped FIRST, HTML
 * artifacts are isolated in a sandboxed iframe — no raw user content reaches the
 * parent DOM unescaped.
 */

function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function simpleMarkdownToHtml(md) {
  if (!md) return '';
  let html = escapeHtml(md);
  html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
  html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
  html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
  html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
  html = html.replace(/^\- (.+)$/gm, '<li>$1</li>');
  html = html.replace(/\n{2,}/g, '</p><p>');
  return '<p>' + html + '</p>';
}

const HTML_KINDS = ['html', 'ui', 'mines_investor_presentation', 'mines_project_package'];

export default function ArtifactBlock({ kind, content, title }) {
  const k = (kind || '').toLowerCase();

  if (HTML_KINDS.includes(k)) {
    return (
      <iframe
        title={title || 'Artifact'}
        srcDoc={content}
        sandbox="allow-scripts allow-same-origin"
        style={{ width: '100%', minHeight: '60vh', border: '1px solid #e5e7eb', borderRadius: '8px', background: '#fff' }}
      />
    );
  }

  if (k === 'md' || k === 'markdown') {
    const safeHtml = simpleMarkdownToHtml(content);
    return (
      <div
        className="share-markdown"
        style={{ lineHeight: 1.7, color: '#1a1a1a' }}
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: safeHtml }}
      />
    );
  }

  if (k === 'json') {
    let formatted = content;
    try { formatted = JSON.stringify(JSON.parse(content), null, 2); } catch {}
    return (
      <pre style={{ background: '#f6f8fa', padding: '1.25rem', borderRadius: '8px', overflow: 'auto', fontSize: '0.8125rem', lineHeight: 1.6, border: '1px solid #e5e7eb' }}>
        <code>{formatted}</code>
      </pre>
    );
  }

  return (
    <pre style={{ background: '#f6f8fa', padding: '1.25rem', borderRadius: '8px', overflow: 'auto', fontSize: '0.875rem', lineHeight: 1.6, whiteSpace: 'pre-wrap', wordBreak: 'break-word', border: '1px solid #e5e7eb' }}>
      {content || ''}
    </pre>
  );
}
