import React from 'react';
import { ScrollView, Text, View } from 'react-native';

import type { DiffLine } from '../toolWidgetUtils';
import { toolWidgetStyles } from './toolWidgetStyles';

const SIGNS: Record<DiffLine['type'], string> = {
  added: '+',
  context: ' ',
  removed: '-',
};

// The essence of the web builder's diff modal, without its web-only dependencies.
export function DiffView({ lines }: { lines: DiffLine[] }) {
  return (
    <View style={toolWidgetStyles.diffWrap}>
      <ScrollView
        nestedScrollEnabled
        showsVerticalScrollIndicator
        style={toolWidgetStyles.diffVerticalScroll}
      >
        <ScrollView
          horizontal
          nestedScrollEnabled
          showsHorizontalScrollIndicator
          style={toolWidgetStyles.diffHorizontalScroll}
        >
          <View style={toolWidgetStyles.diffContent}>
            {lines.map((line, index) => (
              <DiffRow key={index} line={line} />
            ))}
          </View>
        </ScrollView>
      </ScrollView>
    </View>
  );
}

function DiffRow({ line }: { line: DiffLine }) {
  const rowStyle =
    line.type === 'added'
      ? toolWidgetStyles.diffLineAdded
      : line.type === 'removed'
        ? toolWidgetStyles.diffLineRemoved
        : null;
  const textStyle =
    line.type === 'added'
      ? toolWidgetStyles.diffTextAdded
      : line.type === 'removed'
        ? toolWidgetStyles.diffTextRemoved
        : toolWidgetStyles.diffTextContext;

  return (
    <View style={[toolWidgetStyles.diffLine, rowStyle]}>
      <Text style={[toolWidgetStyles.diffLineSign, textStyle]}>{SIGNS[line.type]}</Text>
      {/* One line, sized to its full content — never wrap. This is what makes the
          row wider than the viewport so the horizontal ScrollView can scroll. */}
      <Text numberOfLines={1} style={[toolWidgetStyles.diffLineText, textStyle]}>{line.text || ' '}</Text>
    </View>
  );
}
