import React from 'react';

/**
 * ComponentCommitDiff - A component that renders git-style diffs with addition/deletion counts
 * 
 * @param {Object} props
 * @param {string[]} props.diff - Array of diff lines, each prefixed with '+', '-', or nothing
 * @returns {JSX.Element} Rendered diff view with statistics
 */
const ComponentCommitDiff = ({ diff }) => {
  // Calculate counts of additions and deletions
  const counts = diff.reduce((acc, line) => {
    if (line.startsWith('+')) acc.additions++;
    if (line.startsWith('-')) acc.deletions++;
    return acc;
  }, { additions: 0, deletions: 0 });
  
  /**
   * Determines the type, content, and styling for a diff line
   * @param {string} line - The diff line to analyze
   * @returns {Object} Object containing line type, content, and Tailwind classes
   */
  const getLineInfo = (line) => {
    if (line.startsWith('+')) {
      return {
        type: 'addition',
        content: line.substring(1),
        className: 'bg-green-500/20 text-green-500'
      };
    } else if (line.startsWith('-')) {
      return {
        type: 'deletion',
        content: line.substring(1),
        className: 'bg-red-500/20 text-red-500'
      };
    }
    return {
      type: 'unchanged',
      content: line,
      className: ''
    };
  };

  return (
    <div>
      {/* Scrollable diff content */}
      <div className="overflow-auto px-3 py-2.5 card max-h-[256px]">
        <pre className="font-mono text-sm">
          {diff.map((line, index) => {
            const { type, content, className } = getLineInfo(line);
            return (
              <div 
                key={index} 
                className={`flex items-start py-0.5 ${className}`}
              >
                {/* Line prefix indicator (+, -, or space) */}
                <span className="flex-shrink-0 w-6">
                  {type === 'addition' && '+'}
                  {type === 'deletion' && '-'}
                  {type === 'unchanged' && ' '}
                </span>
                {/* Line content */}
                <span className="flex-1">{content}</span>
              </div>
            );
          })}
        </pre>
      </div>
      
      {/* Diff statistics */}
      <div className="flex gap-3 mt-2 text-sm text-muted-foreground">
        <span className="flex gap-1 items-center">
          <span className="text-green-500">+{counts.additions}</span> additions
        </span>
        <span className="flex gap-1 items-center">
          <span className="text-red-500">-{counts.deletions}</span> deletions
        </span>
      </div>
    </div>
  );
};

export default ComponentCommitDiff;