export function isVisible(item, data) {
    let currency = data.cartTotals.currency_code;
    let cartTotal = parseInt(data.cartTotals.total_price,10) / 100;
    let billingAddress = data.billingAddress;
    let shippingAddress = data.shippingAddress;

    if ( ! item.is_enabled ) {
        return false;
    }

    // Check is hidden
    if ( item.is_hidden ) {
        return false;
    }


    function isPaymentAvailableByCartAmount( cartAmount, minAllowed, maxAllowed ) {
        if ( 0 < cartAmount
            && 0 < maxAllowed
            && maxAllowed < cartAmount
            || minAllowed >= 0
            && minAllowed > cartAmount
        ) {
            return false;
        }

        return true;
    }

    /**
     * Checks if a payment is available based on the given options.
     *
     * @param value The payment value to check.
     * @param options The available payment options.
     * @returns {boolean} Returns true if the payment is available, false otherwise.
     */
    function isPaymentAvailableByOptions( value, options ) {
        if ( ! options.includes( value ) && ! options.includes( 'any' ) ) {
            return false;
        }

        return true;
    }

    /**
     * Checks if the billing and shipping addresses are different based on specified fields.
     *
     * @param billingAddress The billing address
     * @param shippingAddress The shipping address
     * @returns {boolean} Returns true if the addresses are different, false otherwise
     */
    function isAddressDifferent( billingAddress, shippingAddress ) {
        const checkFields = [
            'country',
            'postcode',
            'state',
            'city',
            'address_1',
            'address_2',
            'first_name',
            'last_name',
        ];

        let isDifferent = false;
        checkFields.forEach( function ( field, index ) {
            let shippingVal = shippingAddress[field];
            let billingVal  = billingAddress[field];

            if ( 'postcode' === field ) {
                shippingVal = shippingVal.replace(/\s/g, '');
                billingVal = billingVal.replace(/\s/g, '');
            }

            if ( shippingVal && billingVal && billingVal !== shippingVal ) {
                isDifferent = true;
            }
        } );

        return isDifferent;
    }

    // Validate payment rules
    if ( ! isPaymentAvailableByCartAmount( cartTotal, item.min_amount, item.max_amount ) ) {
        return false;
    }

    if ( ! isPaymentAvailableByOptions( currency, item.currencies ) ) {
        return false;
    }

    if ( ! isPaymentAvailableByOptions( billingAddress.country, item.countries ) ) {
        return false;
    }

    if ( ! isPaymentAvailableByOptions( shippingAddress.country, item.countries ) ) {
        return false;
    }

    if ( item.is_diff_address && isAddressDifferent( billingAddress, shippingAddress ) ) {
        return false;
    }

    return true;
}
