// Simple diff highlighting function
function computeDiff(original, modified) {
  const originalWords = original.split(/(\s+)/);
  const modifiedWords = modified.split(/(\s+)/);

  let result = [];
  let i = 0, j = 0;

  while (i < originalWords.length || j < modifiedWords.length) {
    if (i >= originalWords.length) {
      // Remaining words are additions
      while (j < modifiedWords.length) {
        result.push({ type: 'add', value: modifiedWords[j] });
        j++;
      }
    } else if (j >= modifiedWords.length) {
      // Remaining words are deletions
      while (i < originalWords.length) {
        result.push({ type: 'delete', value: originalWords[i] });
        i++;
      }
    } else if (originalWords[i] === modifiedWords[j]) {
      // Words match
      result.push({ type: 'equal', value: originalWords[i] });
      i++;
      j++;
    } else {
      // Find best match
      let foundMatch = false;

      // Look ahead for matching words
      for (let k = 1; k <= 3 && j + k < modifiedWords.length; k++) {
        if (originalWords[i] === modifiedWords[j + k]) {
          // Add inserted words
          for (let l = 0; l < k; l++) {
            result.push({ type: 'add', value: modifiedWords[j + l] });
          }
          j += k;
          foundMatch = true;
          break;
        }
      }

      if (!foundMatch) {
        for (let k = 1; k <= 3 && i + k < originalWords.length; k++) {
          if (originalWords[i + k] === modifiedWords[j]) {
            // Add deleted words
            for (let l = 0; l < k; l++) {
              result.push({ type: 'delete', value: originalWords[i + l] });
            }
            i += k;
            foundMatch = true;
            break;
          }
        }
      }

      if (!foundMatch) {
        // Replace word
        result.push({ type: 'delete', value: originalWords[i] });
        result.push({ type: 'add', value: modifiedWords[j] });
        i++;
        j++;
      }
    }
  }

  return result;
}

function renderDiff(diff) {
  return diff.map(part => {
    if (part.type === 'add') {
      return `<span class="diff-add">${escapeHtml(part.value)}</span>`;
    } else if (part.type === 'delete') {
      return `<span class="diff-delete">${escapeHtml(part.value)}</span>`;
    } else {
      return escapeHtml(part.value);
    }
  }).join('');
}

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}