// VERSION: 0.1.0
// =============================================================================
// BROWSER COMATIBILITY FUNCTIONS
// =============================================================================
/**
 * Handle auto-resizing of textarea elements that have the `autoexpand` or
 * `seamless` class.
 * 
 * These CSS classes make use of the `field-sizing: content` property to
 * auto expand the height to always fit the contents. HOWEVER, as of 
 * 2026-04-09, this CSS property is not universally supported on all 
 * browsers, specifically, Firefox does not support it yet.
 * 
 * So, this function adds an event listener to all textarea elements that 
 * have the desired classes, and adjusts the height of the text area
 * dynamically with every change that is made.
 * 
 * REVISIT: Revisit whether this function is still needed in 2026-09-01.
 * 
 * USING: 
 * - Call this function in a webpage, after page is loaded and ready, 
 *   by wrapping it in a `DOMContentLoaded` event listener.
 *   
 *   document.addEventListener('DOMContentLoaded', () => {
 *     // ... other code ...
 *     handleAutoResizeTextAreaElements();
 *   });
 */
export function handleAutoResizeTextAreaElements() {
  const seamlessTextAreas = document.querySelectorAll('textarea.seamless, textarea.autoexpand');
  const resizeTextAreaToContents = (textareaElement) => {
    // console.log(`> textarea input event for: ${textareaElement?.name || 'unknown'}`);
    // 1. Reset height to shrink if text was deleted
    // 2. Set height to match the internal scrollable content
    textareaElement.style.height = 'auto';
    // Add an extra little bit for padding and avaoid scroll bars showing up.
    textareaElement.style.height = (textareaElement.scrollHeight + 10) + 'px';
  }
  seamlessTextAreas.forEach(textareaElement => {
    // Check if the browser supports 'field-sizing'
    // If browser does not support `field-sizing`, then add event listener
    // to enable autoresizing of the textarea.
    // NOTE: As of 2026-04-09, this is JS is required for firefox.
    if (!('fieldSizing' in document.documentElement.style)){
      console.log(`Browser does not support 'field-sizing', falling back to JS event listener to handle auto-resizing textarea element: ${textareaElement?.name || 'unknown'}`);
      textareaElement.addEventListener('input', function () {
        resizeTextAreaToContents(this);
      });
    }
  })
}