/**
 * text-field-edit
 * https://github.com/fregante/text-field-edit
 * 
 * MIT License
 * Copyright (c) Federico Brigante <opensource@bfred.it> (bfred.it)
 */

const textFieldEdit = {
  /**
   * Inserts text at the specified position in a field
   * @param {HTMLInputElement|HTMLTextAreaElement} field - The input or textarea element
   * @param {string} text - The text to insert
   * @param {number} [position] - The position where to insert the text (defaults to the current cursor position)
   * @returns {number} - The new cursor position
   */
  insert: function(field, text, position) {
    // Get cursor position if not specified
    if (position === undefined) {
      position = field.selectionStart;
    }

    // Get the current field value
    const value = field.value;

    // Insert the text at the specified position
    field.value = value.substring(0, position) + text + value.substring(position);

    // Set the cursor position after the inserted text
    const newPosition = position + text.length;
    field.selectionStart = newPosition;
    field.selectionEnd = newPosition;

    // Return the new position
    return newPosition;
  },

  /**
   * Replaces the selected text in a field with the specified text
   * @param {HTMLInputElement|HTMLTextAreaElement} field - The input or textarea element
   * @param {string} text - The text to replace the selection with
   * @returns {number} - The new cursor position
   */
  replace: function(field, text) {
    const start = field.selectionStart;
    const end = field.selectionEnd;
    const value = field.value;

    field.value = value.substring(0, start) + text + value.substring(end);

    // Set the cursor position after the inserted text
    const newPosition = start + text.length;
    field.selectionStart = newPosition;
    field.selectionEnd = newPosition;

    return newPosition;
  },

  /**
   * Removes the selected text in a field
   * @param {HTMLInputElement|HTMLTextAreaElement} field - The input or textarea element
   * @returns {number} - The new cursor position
   */
  delete: function(field) {
    return this.replace(field, '');
  }
};

// Export for CommonJS / browser global
if (typeof module === 'object' && module.exports) {
  module.exports = textFieldEdit;
} else {
  window.textFieldEdit = textFieldEdit;
}