/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define(['jquery'], function ($) {
    'use strict';

    return function (targetWidget) {
        $.validator.addMethod(
            'wtai-unique',
            function (value, element, options) {
                var unique = options[0],
                    selector = options[1],
                    fields = $(selector, element.form),
                    result = true;

                if ($('#wtaiCustomOpenGraph').is(':not(:checked)')) {
                    selector = selector + ':not([name="open_graph"])';
                    fields = $(selector, element.form);
                }
                
                fields.each(function () {
                    var field = $(this);
                    if (
                        field.val().trim() !== '' &&
                        value.trim() !== '' &&
                        field.attr('id') !== $(element).attr('id') &&
                        field.val() === value
                    ) {
                        result = false;
                        return false;
                    }
                });

                return result === unique;
            },
            $.mage.__('Please select different values.')
        );

        $.validator.addMethod(
            'wtai-numeric',
            function (value) {
                return /^\d+$/.test(value);
            },
            $.mage.__('Please enter a valid number.')
        );

        return targetWidget;
    };
});
