'use client';

import { useMemo, useRef } from 'react';
import { StatusPill } from '../../components/admin/admin-page.jsx';
import { fixIframe, wrapArtifactContent } from '../../components/dashboard/artifact-utils.js';
import MarkdownPreview from './album-thumbnails/markdown.jsx';

export default function PreviewBody({ item }) {
  if (item.source_type === 'file' && item.local_only) {
    return (
      <div className="project-preview-locked">
        <StatusPill tone="warn">Local only</StatusPill>
        <p>This document is marked local-only. Its contents stay on disk and are never sent to non-local engines or the preview surface.</p>
        {item.storage_path ? <code>{item.storage_path}</code> : null}
      </div>
    );
  }
  if (item.render_kind === 'html' && item.body) return <HtmlPreview content={item.body} title={item.title || item.name} />;
  if (item.render_kind === 'markdown' && item.body) {
    return <div className="project-preview-markdown"><MarkdownPreview>{item.body}</MarkdownPreview>{item.body_truncated ? <small className="project-preview-truncated">Preview truncated — open the file to see everything.</small> : null}</div>;
  }
  if (item.body) {
    return <><pre className="project-preview-pre">{item.body}</pre>{item.body_truncated ? <small className="project-preview-truncated">Preview truncated — open the file to see everything.</small> : null}</>;
  }
  return <p>Preview unavailable for this {item.source_type === 'artifact' ? 'artifact' : item.kind || 'file'}.</p>;
}

function HtmlPreview({ content, title }) {
  const ref = useRef(null);
  const srcDoc = useMemo(() => wrapArtifactContent(content), [content]);
  return (
    <iframe
      ref={ref}
      className="project-slideover-iframe"
      srcDoc={srcDoc}
      sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox"
      title={title || 'Artifact preview'}
      onLoad={fixIframe}
    />
  );
}
