import * as React from 'react';
import { diffLines } from 'diff';
import { cn } from '../lib/utils';

/**
 * Unified-diff renderer — line-by-line color-coded display. Powers the
 * proposal review and revision-history pages. We use `diff.diffLines`
 * (text-line granularity) rather than `diff.createPatch` because we
 * want to render the diff as styled DOM, not as plain monospace text.
 */
export function Diff({
  before,
  after,
  className,
}: {
  before: string;
  after: string;
  className?: string;
}): React.JSX.Element {
  const parts = React.useMemo(() => diffLines(before, after), [before, after]);

  return (
    <pre
      className={cn(
        'overflow-x-auto rounded-md border border-(--color-border) bg-(--color-canvas) p-4 font-mono text-xs leading-relaxed',
        className,
      )}
    >
      {parts.map((part, i) => {
        const color = part.added
          ? 'text-(--color-success)'
          : part.removed
            ? 'text-(--color-danger)'
            : 'text-(--color-fg-muted)';
        const prefix = part.added ? '+ ' : part.removed ? '- ' : '  ';
        const lines = part.value.split('\n');
        // diffLines returns trailing newlines as separate lines; drop the
        // empty tail so we don't render dead rows.
        const trimmed = lines[lines.length - 1] === '' ? lines.slice(0, -1) : lines;
        return (
          <span key={i} className={color}>
            {trimmed.map((line, j) => (
              <span key={j} className="block whitespace-pre-wrap">
                {prefix}
                {line}
              </span>
            ))}
          </span>
        );
      })}
    </pre>
  );
}
