$(document).ready(function () {
  let $inputs = $('input[data-input-type="currency"]');
  
  // Initialize inputs
  $inputs.each(function() {
    const $input = $(this);
    $input.attr('type', 'text');
    
    // Format initial value if present
    const initialValue = $input.val();
    if (initialValue) {
      const sanitized = sanitizeValue(initialValue);
      if (sanitized) {
        const formatted = formatDisplay(formatWithTwoDecimals(sanitized));
        $input.val(formatted);
        updateAriaLabel($input, sanitized);
      }
    }
  });

  // Keydown event handler
  $inputs.on('keydown', function(event) {
    const allowedKeys = [
      'Backspace', 'Tab', 'ArrowLeft', 'ArrowRight', 
      'Delete', 'Home', 'End'
    ];

    if (allowedKeys.includes(event.key)) return;

    // Check if character is allowed (only numbers, comma and dot)
    if (!/^[0-9,.]$/.test(event.key)) {
      event.preventDefault();
      announceInvalidCharacter();
      return;
    }

    const value = sanitizeValue($(this).val());
    
    // Handle comma and dot (both converted internally to dot)
    if ((event.key === "," || event.key === ".") && value.includes(".")) {
      event.preventDefault();
      announceInvalidCharacter();
      return;
    }

    // Check that no more than 2 decimals are entered
    const parts = value.split(".");
    if (parts[1] && parts[1].length >= 2 && /^[0-9]$/.test(event.key)) {
      event.preventDefault();
      announceInvalidCharacter();
    }
  });

  // Input event handler
  $inputs.on('input', function(event) {
    const $target = $(event.target);
    const value = $target.val();
    
    // Keep only valid characters (numbers, comma and dot)
    const sanitized = value.replace(/[^0-9,.]/g, '');
    
    // Check that there's only one decimal separator (comma or dot)
    const separatorCount = (sanitized.match(/[,.]/g) || []).length;
    if (separatorCount > 1) {
      // Keep only the first separator
      const firstSeparatorMatch = sanitized.match(/[,.]/);
      if (firstSeparatorMatch) {
        const firstSeparatorIndex = sanitized.indexOf(firstSeparatorMatch[0]);
        const beforeSeparator = sanitized.substring(0, firstSeparatorIndex + 1);
        const afterSeparator = sanitized.substring(firstSeparatorIndex + 1).replace(/[,.]/g, '');
        $target.val(beforeSeparator + afterSeparator);
      }
    } else if (sanitized !== value) {
      $target.val(sanitized);
      announceInvalidCharacter();
    }
  });

  // Blur event handler
  $inputs.on('blur', function() {
    const $input = $(this);
    // Convert any dots to commas before processing
    const valueWithComma = String($input.val()).replace(/\./g, ',');
    const sanitized = sanitizeValue(valueWithComma);
    const numericValue = formatWithTwoDecimals(sanitized);
    const displayValue = formatDisplay(numericValue);
    $input.val(displayValue);
    updateAriaLabel($input, sanitized);
  });

  // Focus event handler
  $inputs.on('focus', function() {
    const $input = $(this);
    // Convert any dots to commas before processing
    const valueWithComma = String($input.val()).replace(/\./g, ',');
    const sanitized = sanitizeValue(valueWithComma);
    const numericValue = formatWithTwoDecimals(sanitized);
    // Keep text type even during focus and show with comma
    $input.val(numericValue.replace(".", ","));
    $input.removeAttr("aria-label");
  });

  // Helper functions
  function sanitizeValue(value) {
    // Convert both comma and dot to dot for internal calculations
    return value != null ? String(value).replace(/[,.]/g, ".") : "";
  }

  function formatWithTwoDecimals(value) {
    const num = parseFloat(value);
    return isNaN(num) ? "" : num.toFixed(2);
  }

  function formatDisplay(value) {
    return value.replace(".", ",");
  }

  function updateAriaLabel($input, value) {
    const num = parseFloat(value.replace(",", "."));
    if (!isNaN(num)) {
      const formatted = num.toFixed(2).replace(".", ",");
      $input.attr("aria-label", formatted + " euro");
    }
  }

  function announceInvalidCharacter() {
    // Use the aria-live attribute of the element itself if available
    let liveRegion = document.getElementById('currency-live-region');
    if (!liveRegion) {
      liveRegion = createLiveRegion();
    }
    
    // Clear content and then add message
    liveRegion.textContent = '';
    setTimeout(() => {
      liveRegion.textContent = 'carattere non consentito';
    }, 10);
    
    // Clear message after 2 seconds
    setTimeout(() => {
      liveRegion.textContent = '';
    }, 2000);
  }

  function createLiveRegion() {
    const liveRegion = document.createElement('div');
    liveRegion.id = 'currency-live-region';
    liveRegion.setAttribute('aria-live', 'polite');
    liveRegion.setAttribute('aria-atomic', 'true');
    liveRegion.style.position = 'absolute';
    liveRegion.style.left = '-10000px';
    liveRegion.style.width = '1px';
    liveRegion.style.height = '1px';
    liveRegion.style.overflow = 'hidden';
    liveRegion.style.clipPath = 'inset(50%)';
    
    document.body.appendChild(liveRegion);
    return liveRegion;
  }
});