(function($) {
    const handleToggleDesing = (form) => {
        form.find('.elementor-toggle-switch-wrapper').each(function () {
            const wrapper = $(this);
            const input = wrapper.find('input[type="checkbox"]');
            const onText = input.attr('data-on-text') || '';
            const offText = input.attr('data-off-text') || '';
            // Set initial value
            input[0].value = input[0].checked ? onText : offText;

            wrapper.attr('input-check', input.is(':checked') ? 'true' : 'false');
            
            input.on('change', function () {
                const isChecked = $(this).is(':checked');
                wrapper.attr('input-check', isChecked ? 'true' : 'false');
                $(this).val(isChecked ? onText : offText);
            });
        });
    };

    const handleRepeatorField = (form) => {
        form.find('.elementor-toggle-switch-wrapper').each(function () {
            const wrapper = $(this);
            const classList = wrapper.attr('class')?.split(' ') || [];

            const uniqueClass = classList.find(cls => cls.startsWith('cfefuniqueId_'));
            const uniqueId = uniqueClass ? uniqueClass.replace('cfefuniqueId_', '') : null;

            if (uniqueId) {
                let fieldWrapper = wrapper.closest('.is-field-type-toggle')
                fieldWrapper.addClass(`elementor-repeater-item-${uniqueId}`);
            }
        });
    };

    function handleToggleStatus(forms) {
        forms.find('.elementor-toggle-switch-wrapper').each(function () {
            const $wrapper = $(this);
            const $input = $wrapper.find('input[type="checkbox"]');
            const $label = $wrapper.find('.cfkef-switch-label');
            const toggleSpan = $label.find('.toggle-span')[0];

            if (!$input.length || !$label.length || !toggleSpan) return;

            const onText = $input.attr('data-on-text') || '';
            const offText = $input.attr('data-off-text') || '';
            const position = $wrapper.data('toggle-text-position') || 'before_after';

            // Find text nodes before and after the .toggle-span
            const nodes = Array.from($label[0].childNodes);
            const toggleIndex = nodes.indexOf(toggleSpan);
            const beforeNode = nodes[toggleIndex - 1];
            const afterNode = nodes[toggleIndex + 1];

            function updateText(isChecked) {
                if (position === 'before_only' && beforeNode?.nodeType === 3) {
                    beforeNode.nodeValue = isChecked ? onText : offText;
                }
                else if (position === 'after_only' && afterNode?.nodeType === 3) {
                    afterNode.nodeValue = isChecked ? onText : offText;
                }
                else if (position === 'before_after') {
                    if (beforeNode?.nodeType === 3) beforeNode.nodeValue = offText;
                    if (afterNode?.nodeType === 3) afterNode.nodeValue = onText;
                }
            }

            // Initial update
            updateText($input.is(':checked'));

            $input.off('change.toggleText').on('change.toggleText', function () {
                updateText(this.checked);
                $(this).val(this.checked ? onText : offText);
            });
        });
    }
    
    const validateToggleFields = (event, $form) => {        
        let isValid = true;

        $form.find('.elementor-toggle-switch-wrapper').each(function () {
            const $wrapper = $(this);
            const $input = $wrapper.find('input[type="checkbox"]');
            const isRequired = $input.prop('required');
            const offText = $input.attr('data-off-text') || '';
            const onText = $input.attr('data-on-text') || '';
            const currentValue = $input.val();

            // Remove old errors
            $wrapper.find('.elementor-error, .cfkef-error-message').remove();

            if (isRequired && currentValue === offText) {
                isValid = false;

                // Add custom error message like Elementor
                const errorMessage = $('<div style="width:100%;" class="elementor-message elementor-message-danger cfkef-error-message">This field is required.</div>');
                $wrapper.append(errorMessage);
            }
        });

        if (!isValid) {
            event.preventDefault(); // Prevent form submission
            event.stopImmediatePropagation(); // Stop further processing
        }
    };



    const addHandler = ($element) => {
        const forms = $element.find('.cool-form');
        handleToggleDesing(forms);
        handleRepeatorField(forms);
        handleToggleStatus(forms);

        $(document).on('submit_success', '.cool-form', function (e) {
            const $form = $(this);
            setTimeout(() => {
                handleToggleDesing($form)
                handleToggleStatus($form); 
            }, 100); 
        });

        let submitButton = forms.find('button[type="submit"].is-type-button')
        submitButton.on('click',function(event){
            validateToggleFields(event, forms);
        })

    };

    // For frontend
    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/cool-form.default', addHandler);
    });

})(jQuery);
