/**
 * 4.5
 */

define(['jquery'], function($) {
    function isItalian(lang) {
        return lang && lang.substring(0, 2) === 'it';
    }

    function parseToNumber(str, lang) {
        if (!str) return NaN;
        str = String(str).trim();
        if (str === '') return NaN;

        if (isItalian(lang)) {
            if (str.indexOf(',') !== -1) {
                // IT: '1.234,56' -> '1234.56'
                str = str.replace(/\./g, '').replace(',', '.');
            } else {
                // Niente virgola:
                // - se i punti sembrano migliaia (gruppi da 3), li togliamo: '12.345' -> '12345'
                // - altrimenti lasciamo il punto (caso EN-friendly '1234.56')
                if (/\.\d{3}(\.|$)/.test(str)) {
                    str = str.replace(/\./g, '');
                }
                str = str.replace(/\s/g, '');
            }
        } else {
            str = str.replace(/,/g, '');
        }


        var n = parseFloat(str);
        return isNaN(n) ? NaN : n;
    }

    function formatNumber(n, lang, fractionDigits) {
        if (isNaN(n)) return '';
        var locale = isItalian(lang) ? 'it-IT' : 'en-US';

        try {
            return new Intl.NumberFormat(locale, {
                minimumFractionDigits: fractionDigits,
                maximumFractionDigits: fractionDigits,
                useGrouping: true
            }).format(n);
        } catch (e) {
            // Fallback minimale
            var fixed = (fractionDigits > 0) ? n.toFixed(fractionDigits) : String(Math.round(n));
            if (fractionDigits === 0) {
                // Solo migliaia
                return isItalian(lang)
                    ? fixed.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
                    : fixed.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            }
            var parts = fixed.split('.');
            var intPart = parts[0];
            var decPart = parts[1] || '';
            intPart = isItalian(lang)
                ? intPart.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
                : intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            return isItalian(lang) ? (intPart + ',' + decPart) : (intPart + '.' + decPart);
        }
    }

    function stripGrouping(str, lang) {
        if (!str) return '';
        str = String(str);
        return isItalian(lang) ? str.replace(/\./g, '') : str.replace(/,/g, '');
    }

    function hasAnyFraction($inputs, lang) {
        var found = false;
        $inputs.each(function() {
            var n = parseToNumber($(this).val(), lang);
            if (!isNaN(n)) {
                // tolleranza per floating
                var frac = Math.abs(n % 1);
                if (frac > 0.0000001) {
                    found = true;
                    return false; // break
                }
            }
        });
        return found;
    }

    function attach(selector, lang, bdecimali, options) {
        options = options || {};
        var $inputs = $(selector);

        function currentFractionDigits() {
            if (parseInt(bdecimali, 10) === 1) return 2;
            // bdecimali=2: 2 decimali solo se esistono frazioni
            return hasAnyFraction($inputs, lang) ? 2 : 0;
        }

        function formatAll() {
            var fd = currentFractionDigits();
            $inputs.each(function() {
                var raw = $(this).val();
                var n = parseToNumber(raw, lang);
                if (isNaN(n)) return;
                $(this).val(formatNumber(n, lang, fd));
            });
        }

        // iniziale
        formatAll();

        // focus: togli solo separatore migliaia
        $inputs.on('focus', function() {
            $(this).val(stripGrouping($(this).val(), lang));
        });

        // blur: riformatta e, se con bdecimali=2 è comparsa una frazione, passa a 2 decimali ovunque
        $inputs.on('blur', function() {
            formatAll();
        });

        // Se vuoi: su change input ricalcoli “live”
        $inputs.on('change', function() {
            formatAll();
        });
    }

    return {
        attach: attach,
        parseToNumber: parseToNumber,
        formatNumber: formatNumber
    };
});
