/**
 * Global Number Formatter for Turkish Locale
 * Formats numbers as: 10.000,00
 */

// Format number with thousands separator
function formatNumber(value, decimals = 0) {
    if (!value && value !== 0) return '';

    // Remove all non-digit characters except comma and dot
    let numStr = value.toString().replace(/[^\d.,]/g, '');

    // Replace comma with dot for parsing
    numStr = numStr.replace(',', '.');

    // Parse to float
    let num = parseFloat(numStr);

    if (isNaN(num)) return '';

    // Format with Turkish locale
    return num.toLocaleString('tr-TR', {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals
    });
}

// Format input field as user types
function formatNumberInput(input, decimals = 0) {
    let value = input.value.replace(/[^\d]/g, '');
    if (value) {
        input.value = parseInt(value).toLocaleString('tr-TR');
    }
}

// Get numeric value from formatted string
function parseFormattedNumber(formattedValue) {
    if (!formattedValue) return 0;
    return parseFloat(formattedValue.toString().replace(/\./g, '').replace(',', '.')) || 0;
}

// Initialize number formatting on page load
function initNumberFormatting() {
    // Auto-format all inputs with class 'number-input'
    document.querySelectorAll('.number-input').forEach(function(input) {
        input.addEventListener('input', function() {
            formatNumberInput(this, 0);
        });
    });

    // Auto-format all inputs with class 'currency-input'
    document.querySelectorAll('.currency-input').forEach(function(input) {
        input.addEventListener('input', function() {
            formatNumberInput(this, 2);
        });
    });

    // Format all elements with class 'formatted-number'
    document.querySelectorAll('.formatted-number').forEach(function(element) {
        let value = element.textContent || element.innerText;
        let decimals = element.dataset.decimals || 0;
        element.textContent = formatNumber(value, parseInt(decimals));
    });
}

// jQuery plugin for easy integration
if (typeof jQuery !== 'undefined') {
    (function($) {
        $.fn.formatNumber = function(decimals = 0) {
            return this.each(function() {
                if (this.tagName === 'INPUT') {
                    $(this).on('input', function() {
                        formatNumberInput(this, decimals);
                    });
                } else {
                    let value = $(this).text();
                    $(this).text(formatNumber(value, decimals));
                }
            });
        };

        $.fn.getNumericValue = function() {
            return parseFormattedNumber($(this).val() || $(this).text());
        };
    })(jQuery);
}

// Initialize on document ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initNumberFormatting);
} else {
    initNumberFormatting();
}
