(function ($) {
    'use strict';

    var refreshTimer = null;
    var domObserver = null;
    var editorWindow = (window.parent && window.parent !== window) ? window.parent : window;
    var editor$ = editorWindow.jQuery || $;

    function getEditorDocument() {
        return editorWindow.document || document;
    }

    function findInEditor(selector) {
        return editor$(getEditorDocument()).find(selector);
    }

    function getControlValue(setting) {
        var $control = findInEditor('.elementor-control[data-setting="' + setting + '"]');
        var $switch = $control.find('.elementor-switch-input, input[type="checkbox"]').first();
        var $field = $control.find('select, textarea, input[type="number"], input[type="text"], input[type="hidden"]').first();

        if ($switch.length) {
            return $switch.is(':checked') ? 'yes' : '';
        }

        return $field.length ? String($field.val() || '') : '';
    }

    function normalizePerPageValue(rawValue, fallbackValue) {
        var parsed = parseInt(rawValue, 10);
        var fallback = (typeof fallbackValue === 'number' && !isNaN(fallbackValue)) ? fallbackValue : 6;

        if (isNaN(parsed)) {
            return fallback;
        }

        if (parsed === -1) {
            return -1;
        }

        return parsed < 1 ? fallback : parsed;
    }

    function setFieldValue(setting, value) {
        var normalized = String(value == null ? '' : value);
        var $field = findInEditor('.elementor-control[data-setting="' + setting + '"] select, .elementor-control[data-setting="' + setting + '"] input[type="number"], .elementor-control[data-setting="' + setting + '"] input[type="text"]').first();

        if ($field.length && String($field.val() || '') !== normalized) {
            $field.val(normalized).trigger('input').trigger('change');
        }
    }

    function syncRepeaterLinkControls() {
        var source = getControlValue('source');
        var clickMode = getControlValue('on_image_click');
        var shouldShow = source === 'static' && clickMode === 'custom-link';

        findInEditor('.elementor-repeater-fields-wrapper .elementor-control[data-setting="link"], .elementor-repeater-fields-wrapper .elementor-control[data-setting="link_target"]')
            .toggle(shouldShow);
    }

    function syncDynamicPaginationControls() {
        var source = getControlValue('source');
        var showAllItems = getControlValue('limited_items') === 'yes';
        var currentPaginationType = getControlValue('pagination_type');
        var isDynamicSource = source === 'dynamic';
        var effectivePaginationType = currentPaginationType || 'none';
        var $showAllItemsControl = findInEditor('.elementor-control[data-setting="limited_items"]');
        var $imagesPerPageControl = findInEditor('.elementor-control[data-setting="images_per_page"]');
        var $imagesPerPageInput = $imagesPerPageControl.find('input[type="number"]').first();
        var $paginationTypeControl = findInEditor('.elementor-control[data-setting="pagination_type"]');
        var $loadMoreTextControl = findInEditor('.elementor-control[data-setting="load_more_text"]');

        if (!isDynamicSource && showAllItems) {
            setFieldValue('pagination_type', 'none');
            effectivePaginationType = 'none';
        }

        if (!isDynamicSource && !showAllItems && $imagesPerPageInput.length) {
            var currentItemsPerPage = parseInt($imagesPerPageInput.val(), 10);

            if (!currentItemsPerPage || currentItemsPerPage < 1) {
                setFieldValue('images_per_page', '10');
            }
        }

        if ($imagesPerPageInput.length) {
            $imagesPerPageInput.prop('readonly', false);
            $imagesPerPageControl.toggleClass('sitsel-is-synced-control', false);
        }

        $showAllItemsControl.toggle(!isDynamicSource);
        $imagesPerPageControl.toggle(!isDynamicSource && !showAllItems);
        $paginationTypeControl.toggle(isDynamicSource || !showAllItems);
        $loadMoreTextControl.toggle((isDynamicSource || !showAllItems) && effectivePaginationType === 'load-more');
    }

    function getGalleryRepeaterRows() {
        var $rows = findInEditor('.elementor-control[data-setting="gallery_items"] .elementor-repeater-row');

        if ($rows.length) {
            return $rows;
        }

        $rows = findInEditor('.elementor-control-gallery_items .elementor-repeater-row');
        if ($rows.length) {
            return $rows;
        }

        return findInEditor('.elementor-repeater-fields-wrapper .elementor-repeater-row');
    }

    function getRepeaterFieldInput($context, setting) {
        if (!$context || !$context.length) {
            return editor$();
        }

        return $context
            .find(
                '.elementor-control[data-setting="' + setting + '"] input[type="text"], ' +
                '.elementor-control[data-setting="' + setting + '"] textarea, ' +
                'input[data-setting="' + setting + '"], textarea[data-setting="' + setting + '"]'
            )
            .first();
    }

    function getActiveRepeaterFields() {
        var $fields = findInEditor('.elementor-control[data-setting="gallery_items"] .elementor-repeater-fields-wrapper:visible').last();

        if ($fields.length) {
            return $fields;
        }

        $fields = findInEditor('.elementor-repeater-fields-wrapper:visible').last();
        if ($fields.length) {
            return $fields;
        }

        return editor$();
    }

    function normalizeStaticRepeaterRow($row, index, attempt) {
        var itemNumber = index + 1;
        var titleValue = 'Gallery Item ' + itemNumber;
        var categoryValue = 'Category ' + itemNumber;
        var titlePattern = /^gallery item(?:\s+\d+)?$/i;
        var categoryPattern = /^category(?:[-\s]?\d+)?$/i;
        var genericItemPattern = /^item\s*#?\s*\d+$/i;
        var plainTitlePattern = /^gallery item$/i;
        var plainCategoryPattern = /^category$/i;
        var retryCount = attempt || 0;
        var $titleInput = getRepeaterFieldInput($row, 'title');
        var $categoryInput = getRepeaterFieldInput($row, 'category');
        var $rowLabel = $row.find('.elementor-repeater-row-item-title').first();
        var $activeFields;
        var titleCurrent;
        var categoryCurrent;
        var $rowToggle;

        if ((!$titleInput.length || !$categoryInput.length) && retryCount < 3) {
            $rowToggle = $row.children('.elementor-repeater-row-item-title').first();

            if (!$rowToggle.length) {
                $rowToggle = $row.find('.elementor-repeater-row-item-title').first();
            }

            if ($rowToggle.length) {
                $rowToggle.trigger('click');
            }

            window.setTimeout(function () {
                normalizeStaticRepeaterRow($row, index, retryCount + 1);
            }, 120);

            return;
        }

        if (!$titleInput.length || !$categoryInput.length) {
            $activeFields = getActiveRepeaterFields();

            if (!$titleInput.length) {
                $titleInput = getRepeaterFieldInput($activeFields, 'title');
            }

            if (!$categoryInput.length) {
                $categoryInput = getRepeaterFieldInput($activeFields, 'category');
            }
        }

        titleCurrent = String($titleInput.val() || '').trim();
        categoryCurrent = String($categoryInput.val() || '').trim();

        if (
            $titleInput.length &&
            (
                titleCurrent === '' ||
                titlePattern.test(titleCurrent) ||
                genericItemPattern.test(titleCurrent) ||
                plainTitlePattern.test(titleCurrent)
            )
        ) {
            $titleInput.val(titleValue).trigger('input').trigger('change');
            titleCurrent = titleValue;
        }

        if (
            $categoryInput.length &&
            (
                categoryCurrent === '' ||
                categoryPattern.test(categoryCurrent) ||
                titlePattern.test(categoryCurrent) ||
                genericItemPattern.test(categoryCurrent) ||
                plainCategoryPattern.test(categoryCurrent) ||
                plainTitlePattern.test(categoryCurrent)
            )
        ) {
            $categoryInput.val(categoryValue).trigger('input').trigger('change');
            categoryCurrent = categoryValue;
        }

        if (
            $rowLabel.length &&
            (titleCurrent === '' || titlePattern.test(titleCurrent) || genericItemPattern.test(titleCurrent))
        ) {
            $rowLabel.text(titleValue);
            return;
        }

        if ($rowLabel.length) {
            $rowLabel.text(titleCurrent || titleValue);
        }
    }

    function normalizeLatestAddedRow(attempt) {
        var retryCount = attempt || 0;
        var $rows;
        var $row;
        var $editTool;

        $rows = getGalleryRepeaterRows();

        if (!$rows.length) {
            return;
        }

        $row = $rows.last();
        $editTool = $row.find('.elementor-repeater-tool-edit').first();

        if ($editTool.length) {
            $editTool.trigger('click');
        }

        normalizeStaticRepeaterRow($row, $rows.length - 1, 0);

        if (retryCount < 4) {
            window.setTimeout(function () {
                normalizeLatestAddedRow(retryCount + 1);
            }, 140);
        }
    }

    function syncStaticRepeaterDefaults() {
        var $rows;

        $rows = getGalleryRepeaterRows();

        if (!$rows.length) {
            return;
        }

        $rows.each(function(index) {
            normalizeStaticRepeaterRow(editor$(this), index, 0);
        });
    }

    function triggerQueryControlsRefresh() {
        // Trigger select2 controls in the query section to populate
        var $querySection = findInEditor('#elementor-controls [data-setting="manual_posts"], #elementor-controls [data-setting="categories"], #elementor-controls [data-setting="exclude_categories"], #elementor-controls [data-setting="manual_tags"]');
        
        $querySection.each(function() {
            var $select = editor$(this).find('select.select2-hidden-accessible');
            if ($select.length && $select.data('select2')) {
                // Trigger select2 to refresh and load options
                $select.trigger('change.select2');
            }
        });
    }

    function onTabChange() {
        var $activeTab = findInEditor('.elementor-panel-navigation-tab.elementor-active');
        var tabName = $activeTab.attr('data-tab') || '';
        
        // When switching to content tab and source is dynamic, trigger query controls
        if (tabName === 'content') {
            var source = getControlValue('source');
            if (source === 'dynamic') {
                window.setTimeout(function() {
                    triggerQueryControlsRefresh();
                }, 150);
            }
        }
    }

    function refreshGalleryPreview(forceRebind) {
        syncRepeaterLinkControls();
        syncDynamicPaginationControls();
        syncStaticRepeaterDefaults();

        if (!window.SitselFilterableGallery || typeof window.SitselFilterableGallery.refreshAll !== 'function') {
            return;
        }

        window.SitselFilterableGallery.refreshAll(!!forceRebind);
    }

    function scheduleRefresh(delay, forceRebind) {
        window.clearTimeout(refreshTimer);
        refreshTimer = window.setTimeout(function () {
            refreshGalleryPreview(forceRebind);
        }, delay || 120);
    }

    function queueRefreshBurst(forceRebind) {
        scheduleRefresh(120, forceRebind);
        window.setTimeout(function () {
            refreshGalleryPreview(forceRebind);
        }, 350);
        window.setTimeout(function () {
            refreshGalleryPreview(forceRebind);
        }, 800);
        window.setTimeout(function () {
            refreshGalleryPreview(forceRebind);
        }, 1400);
    }

    function observePreviewMutations() {
        if (domObserver || !window.MutationObserver || !document.body) {
            return;
        }

        domObserver = new MutationObserver(function (mutations) {
            var shouldRefresh = false;

            mutations.forEach(function (mutation) {
                if (shouldRefresh) {
                    return;
                }

                Array.prototype.forEach.call(mutation.addedNodes || [], function (node) {
                    if (shouldRefresh || !node || node.nodeType !== 1) {
                        return;
                    }

                    var $node = $(node);

                    if ($node.is('.sitsel-filterable-gallery-wrapper, .elementor-widget-sitsel_filterable_gallery') || $node.find('.sitsel-filterable-gallery-wrapper').length) {
                        shouldRefresh = true;
                    }
                });
            });

            if (shouldRefresh) {
                queueRefreshBurst(true);
            }
        });

        domObserver.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    $(function () {
        observePreviewMutations();
        queueRefreshBurst(true);
    });

    $(window).on('elementor/frontend/init', function () {
        observePreviewMutations();
        queueRefreshBurst(true);
    });

    if (editorWindow.elementor && typeof editorWindow.elementor.on === 'function') {
        editorWindow.elementor.on('preview:loaded', function () {
            observePreviewMutations();
            queueRefreshBurst(true);
        });
    }

    if (editorWindow.elementor && editorWindow.elementor.channels && editorWindow.elementor.channels.editor) {
        editorWindow.elementor.channels.editor.on('change', function () {
            queueRefreshBurst(true);
        });
    }

    editor$(getEditorDocument()).on('click input change keyup mouseup select2:select select2:clear', '.elementor-panel-navigation-tab, .elementor-control-input-wrapper input, .elementor-control-input-wrapper select, .elementor-control-input-wrapper textarea, .elementor-repeater-fields-wrapper input, .elementor-repeater-fields-wrapper select, .elementor-repeater-fields-wrapper textarea, .elementor-repeater-row-item-title, .elementor-repeater-add, .select2-selection', function () {
        queueRefreshBurst(true);
    });

    // Listen for tab changes
    editor$(getEditorDocument()).on('click', '.elementor-panel-navigation-tab', function() {
        window.setTimeout(function() {
            onTabChange();
        }, 100);
    });

    // Trigger query controls when source changes to dynamic
    editor$(getEditorDocument()).on('change', '.elementor-control[data-setting="source"] select', function() {
        var value = editor$(this).val();

        queueRefreshBurst(true);

        if (value === 'dynamic') {
            window.setTimeout(function() {
                triggerQueryControlsRefresh();
                queueRefreshBurst(true);
            }, 200);
        }
    });

    editor$(getEditorDocument()).on('click', '.elementor-control[data-setting="gallery_items"] .elementor-repeater-add', function () {
        normalizeLatestAddedRow(0);
        window.setTimeout(syncStaticRepeaterDefaults, 120);
        window.setTimeout(syncStaticRepeaterDefaults, 320);
        window.setTimeout(syncStaticRepeaterDefaults, 700);
        window.setTimeout(syncStaticRepeaterDefaults, 1200);
        window.setTimeout(function () { normalizeLatestAddedRow(1); }, 160);
        window.setTimeout(function () { normalizeLatestAddedRow(2); }, 420);
        window.setTimeout(function () { normalizeLatestAddedRow(3); }, 860);
    });

    editor$(getEditorDocument()).on('click', '.elementor-control[data-setting="gallery_items"] .elementor-repeater-row-item-title', function () {
        window.setTimeout(syncStaticRepeaterDefaults, 120);
        window.setTimeout(syncStaticRepeaterDefaults, 280);
        window.setTimeout(syncStaticRepeaterDefaults, 560);
    });

    editor$(getEditorDocument()).on(
        'change input select2:select select2:clear',
        '.elementor-control[data-setting="post_type"] select, .elementor-control[data-setting="selection"] select, .elementor-control[data-setting="manual_posts"] select, .elementor-control[data-setting="categories"] select, .elementor-control[data-setting="exclude_categories"] select, .elementor-control[data-setting="manual_tags"] select, .elementor-control[data-setting="orderby"] select, .elementor-control[data-setting="order"] select, .elementor-control[data-setting="offset"] input, .elementor-control[data-setting="posts_per_page"] input, .elementor-control[data-setting="pagination_type"] select',
        function () {
            if (getControlValue('source') !== 'dynamic') {
                return;
            }

            window.setTimeout(function () {
                triggerQueryControlsRefresh();
                queueRefreshBurst(true);
            }, 180);
        }
    );
})(jQuery);
