import { CodeBlock } from '@cameleer/design-system';
import styles from '../ExecutionDiagram.module.css';

interface BodyTabProps {
  body: string | undefined;
  label: string;
}

function detectLanguage(text: string): string {
  const trimmed = text.trimStart();
  if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
    try {
      JSON.parse(text);
      return 'json';
    } catch {
      // not valid JSON
    }
  }
  if (trimmed.startsWith('<')) return 'xml';
  return 'text';
}

function formatBody(text: string, language: string): string {
  if (language === 'json') {
    try {
      return JSON.stringify(JSON.parse(text), null, 2);
    } catch {
      return text;
    }
  }
  return text;
}

export function BodyTab({ body, label }: BodyTabProps) {
  if (!body) {
    return <div className={styles.emptyState}>No {label.toLowerCase()} body available</div>;
  }

  const language = detectLanguage(body);
  const formatted = formatBody(body, language);

  return (
    <div>
      <CodeBlock content={formatted} language={language} copyable />
    </div>
  );
}
