jQuery(document).ready(function ($) {
    'use strict';

    /**
     * ==============================================
     * 1. CONFIGURATION & STATE
     * ==============================================
     */
    const CONFIG = {
        needsAjaxSet: new Set([
            'post', 'page', 'in_category', 'category', 'tag', 'author',
            'product', 'service', 'portfolio', 'team', 'event', 'career',
            'doc', 'download', 'digital',

            'product_in_category', 'product_in_tag',
            'portfolio_in_category', 'portfolio_in_tag',
            'service_in_category', 'service_in_tag',
            'team_in_category', 'event_in_category',
            'doc_in_category', 'digital_in_category'
        ]),
        conditionOptions: {
            general: {
                'Entire Site': 'entire_site',
                'Front Page': 'front_page',
                'Search Results': 'search_results',
                '404 Page': 'error_404'
            },
            singular: {
                'All Singular': 'all',
                'All Posts': 'post_type-post',
                'All Pages': 'post_type-page',
                'All Products': 'post_type-product',
                'All Services': 'post_type-service',
                'All Portfolios': 'post_type-portfolio',
                'All Team Members': 'post_type-team',
                'All Events': 'post_type-event',
                'All Careers': 'post_type-career',
                'All Docs': 'post_type-doc',
                'All Digital Goods': 'post_type-digital',
                'All Downloads (EDD)': 'post_type-download',
                'Specific Post...': 'post',
                'Specific Page...': 'page',
                'Specific Product...': 'product',
                'Specific Service...': 'service',
                'Specific Portfolio...': 'portfolio',
                'Specific Team Member...': 'team',
                'Specific Event...': 'event',
                'Specific Career...': 'career',
                'Specific Doc...': 'doc',
                'Specific Digital Good...': 'digital',
                'Specific Download (EDD)...': 'download',
                'Posts in Category...': 'in_category',
                'Posts with Tag...': 'in_tag',

                'Products in Category...': 'product_in_category',
                'Products with Tag...': 'product_in_tag',
                'Portfolios in Category...': 'portfolio_in_category',
                'Portfolios with Tag...': 'portfolio_in_tag',
                'Services in Category...': 'service_in_category',
                'Services with Tag...': 'service_in_tag',
                'Team in Category...': 'team_in_category',
                'Events in Category...': 'event_in_category',
                'Docs in Category...': 'doc_in_category',
                'Digital Goods in Category...': 'digital_in_category'
            },
            archive: {
                'All Archives': 'all',
                'Post Archive': 'post_type_archive-post',
                'Page Archive': 'post_type_archive-page',
                'Product Archive (Shop)': 'post_type_archive-product',
                'Service Archive': 'post_type_archive-service',
                'Portfolio Archive': 'post_type_archive-portfolio',
                'Team Archive': 'post_type_archive-team',
                'Event Archive': 'post_type_archive-event',
                'Career Archive': 'post_type_archive-career',
                'Doc Archive': 'post_type_archive-doc',
                'Digital Goods Archive': 'post_type_archive-digital',
                'Download Archive (EDD)': 'post_type_archive-download',
                'Category Archive...': 'category',
                'Tag Archive...': 'tag',
                'Author Archive...': 'author',
                'Date Archive': 'date'
            }
        },
        i18n: sifency_tb_admin.i18n || { loading: 'Loading...', error: 'An error occurred' },
        allowedOptionsMap: {
            'error_404': {
                general: ['error_404'],
                singular: [],
                archive: []
            },
            'post': {
                general: [],
                singular: ['all', 'post_type-post', 'post', 'in_category', 'in_tag'],
                archive: []
            },
            'product': {
                general: [],
                singular: ['all', 'post_type-product', 'product', 'product_in_category', 'product_in_tag'],
                archive: []
            },
            'service': {
                general: [],
                singular: ['all', 'post_type-service', 'service', 'service_in_category', 'service_in_tag'],
                archive: []
            },
            'team': {
                general: [],
                singular: ['all', 'post_type-team', 'team', 'team_in_category'],
                archive: []
            },
            'portfolio': {
                general: [],
                singular: ['all', 'post_type-portfolio', 'portfolio', 'portfolio_in_category', 'portfolio_in_tag'],
                archive: []
            },
            'event': {
                general: [],
                singular: ['all', 'post_type-event', 'event', 'event_in_category'],
                archive: []
            },
            'career': {
                general: [],
                singular: ['all', 'post_type-career', 'career'],
                archive: []
            },
            'documentation': {
                general: [],
                singular: ['all', 'post_type-doc', 'doc', 'doc_in_category'],
                archive: []
            },
            'digital': {
                general: [],
                singular: ['all', 'post_type-digital', 'digital', 'digital_in_category'],
                archive: []
            },
            'edd': {
                general: [],
                singular: ['all', 'post_type-download', 'download'],
                archive: []
            },
            'post-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-post', 'category', 'tag', 'author', 'date']
            },
            'shop': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-product']
            },
            'service-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-service']
            },
            'team-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-team']
            },
            'portfolio-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-portfolio']
            },
            'event-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-event']
            },
            'career-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-career']
            },
            'doc-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-doc']
            },
            'digital-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-digital']
            },
            'edd-archive': {
                general: [],
                singular: [],
                archive: ['all', 'post_type_archive-download']
            }
        }
    };

    const STATE = {
        currentTemplateId: 0,
        currentTemplateType: ''
    };

    /**
     * ==============================================
     * 2. DOM ELEMENT CACHE
     * ==============================================
     */
    const DOM = {
        adminPage: $('.sifency-admin-page'),
        conditionsModal: $('#sifency-conditions-modal'),
        conditionsModalBody: $('#sifency-conditions-modal').find('.sifency-modal-body'),
        saveConditionsBtn: $('#sifency-save-conditions-btn'),
        newTemplateModal: $('#sifency-new-template-modal'),
        createButtons: $('#sifency-create-and-edit, #sifency-create-and-save'),
    };


    /**
     * ==============================================
     * 3. UTILITY METHODS
     * ==============================================
     */
    const Utils = {
        // DRY AJAX handler returning a promise for cleaner async flows
        ajax: (data) => {
            return $.ajax({
                url: sifency_tb_admin.ajax_url,
                type: 'POST',
                dataType: 'json',
                data: { ...data, nonce: sifency_tb_admin.nonce }
            });
        },

        openModal: ($modal) => {
            $modal.css('display', 'flex');
            requestAnimationFrame(() => $modal.addClass('is-visible'));
        },

        closeModal: ($modal) => {
            $modal.removeClass('is-visible');
            setTimeout(() => {
                if (!$modal.hasClass('is-visible')) {
                    $modal.css('display', 'none');
                }
            }, 350);
        },

        toggleButtonState: ($btn, isLoading) => {
            $btn.toggleClass('disabled', isLoading);
            $btn.find('.spinner').toggleClass('is-active', isLoading);
        }
    };

    /**
     * ==============================================
     * 4. CONDITIONS LOGIC (SELECT2 & DOM)
     * ==============================================
     */
    const ConditionsManager = {
        initAllRows: ($context) => {
            $context.find('.sifency-condition-row').each(function () {
                ConditionsManager.initSingleRow($(this));
            });

            // Init sortable on lists
            $context.find('.sifency-conditions-list').each(function () {
                ConditionsManager.initSortable($(this));
            });
        },

        initSortable: ($list) => {
            if (!$list.length || typeof $.fn.sortable === 'undefined') return;

            $list.sortable({
                handle: '.sifency-condition-drag',
                items: '.sifency-condition-row',
                placeholder: 'ui-sortable-placeholder',
                axis: 'y',
                revert: 200,
                opacity: 0.8,
                tolerance: 'pointer',
                start: function (e, ui) {
                    ui.placeholder.height(ui.helper.outerHeight());
                }
            });
        },

        initSingleRow: ($row) => {
            const templateType = STATE.currentTemplateType;
            if (templateType && CONFIG.allowedOptionsMap[templateType]) {
                const map = CONFIG.allowedOptionsMap[templateType];
                const $typeSelect = $row.find('.sifency-condition-type');
                if (!map.general || map.general.length === 0) {
                    $typeSelect.find('option[value="general"]').hide().prop('disabled', true);
                }
                if (!map.singular || map.singular.length === 0) {
                    $typeSelect.find('option[value="singular"]').hide().prop('disabled', true);
                }
                if (!map.archive || map.archive.length === 0) {
                    $typeSelect.find('option[value="archive"]').hide().prop('disabled', true);
                }
                const currentVal = $typeSelect.val();
                if ($typeSelect.find(`option[value="${currentVal}"]`).prop('disabled')) {
                    const firstEnabled = $typeSelect.find('option:not(:disabled)').first().val();
                    if (firstEnabled) {
                        $typeSelect.val(firstEnabled);
                    }
                }
            }
            ConditionsManager.updateSubtypeDropdown($row, $row.data('subtype'));
        },

        updateSubtypeDropdown: ($row, selectedSubtype = null) => {
            const type = $row.find('.sifency-condition-type').val();
            const $subtypeSelect = $row.find('.sifency-condition-subtype');
            let options = CONFIG.conditionOptions[type] || {};

            const templateType = STATE.currentTemplateType;
            if (templateType && CONFIG.allowedOptionsMap[templateType]) {
                const map = CONFIG.allowedOptionsMap[templateType];
                if (map[type]) {
                    const filtered = {};
                    const allowedList = map[type];
                    Object.entries(options).forEach(([label, value]) => {
                        if (allowedList.includes(value)) {
                            filtered[label] = value;
                        }
                    });
                    options = filtered;
                }
            }

            // Performant string building instead of continuous DOM appending
            const optionsHtml = Object.entries(options)
                .map(([label, value]) => `<option value="${value}">${label}</option>`)
                .join('');

            $subtypeSelect.html(optionsHtml);
            if (selectedSubtype) $subtypeSelect.val(selectedSubtype);
            $subtypeSelect.trigger('change');

            ConditionsManager.checkDuplication($row);
        },

        updateValueDropdown: ($row) => {
            const subtype = $row.find('.sifency-condition-subtype').val() || '';
            const $valueSelect = $row.find('.sifency-condition-value');
            const isInitialized = $valueSelect.hasClass('select2-hidden-accessible');

            // Determine base search type
            const searchType = (subtype.startsWith('post_type-') || subtype.startsWith('post_type_archive-'))
                ? ''
                : subtype;

            if (CONFIG.needsAjaxSet.has(searchType)) {
                if (!isInitialized) {
                    $valueSelect.show().select2({
                        width: 'style',
                        dropdownParent: DOM.conditionsModal,
                        ajax: {
                            url: sifency_tb_admin.ajax_url,
                            dataType: 'json',
                            delay: 250,
                            cache: true,
                            data: params => ({
                                action: 'sifency_search_posts_terms',
                                nonce: sifency_tb_admin.nonce,
                                template_id: STATE.currentTemplateId,
                                search_type: searchType,
                                q: params.term
                            }),
                            processResults: data => {
                                const currentSubtype = $row.find('.sifency-condition-subtype').val();
                                const selectedIds = new Set();

                                $row.closest('.sifency-conditions-list').find('.sifency-condition-row').not($row).each(function () {
                                    const other = ConditionsManager.serializeRow($(this));
                                    if (other.subtype === currentSubtype && other.value) {
                                        selectedIds.add(String(other.value));
                                    }
                                });

                                return {
                                    results: data.data.map(item => ({
                                        ...item,
                                        disabled: !!item.disabled || selectedIds.has(String(item.id))
                                    }))
                                };
                            }
                        }
                    }).on('change', function () {
                        ConditionsManager.checkDuplication($row);
                    });
                } else {
                    $valueSelect.show();
                }
            } else {
                if (isInitialized) $valueSelect.select2('destroy');
                $valueSelect.hide().val(''); // Ensure hidden values don't pass stale data
            }

            ConditionsManager.checkDuplication($row);
        },

        checkDuplication: ($row) => {
            const current = ConditionsManager.serializeRow($row);
            const $list = $row.closest('.sifency-conditions-list');
            let isDuplicate = false;

            if (!current.type) return false;

            $list.find('.sifency-condition-row').not($row).each(function () {
                const other = ConditionsManager.serializeRow($(this));
                if (current.type === other.type && current.subtype === other.subtype && current.value == other.value) {
                    isDuplicate = true;
                    return false;
                }
            });

            $row.toggleClass('is-duplicate', isDuplicate);
            return isDuplicate;
        },

        updateSaveButtonState: () => {
            const hasDuplicates = DOM.conditionsModal.find('.is-duplicate').length > 0;
            if (hasDuplicates) {
                DOM.saveConditionsBtn.attr('title', 'Please resolve duplicate conditions before saving.');
            } else {
                DOM.saveConditionsBtn.removeAttr('title');
            }
        },

        serializeRow: ($row) => {
            let subtype = $row.find('.sifency-condition-subtype').val() || '';
            let value = $row.find('.sifency-condition-value').val() || '';

            if (subtype.startsWith('post_type-')) {
                value = subtype.substring(10);
                subtype = 'post_type';
            } else if (subtype.startsWith('post_type_archive-')) {
                value = subtype.substring(18);
                subtype = 'post_type_archive';
            }

            return {
                type: $row.find('.sifency-condition-type').val(),
                subtype: subtype,
                value: value,
            };
        },

        gatherRules: (selector) => {
            return DOM.conditionsModal.find(selector).map(function () {
                return ConditionsManager.serializeRow($(this));
            }).get();
        }
    };


    /**
     * ==============================================
     * 5. EVENT LISTENERS
     * ==============================================
     */

    // Toggle Template Status
    DOM.adminPage.on('change', '.sifency-status-toggle', function () {
        const $checkbox = $(this);
        const isActive = $checkbox.is(':checked');

        $checkbox.closest('td').find('.status-label').text(isActive ? 'Active' : 'Inactive');

        Utils.ajax({
            action: 'sifency_toggle_template_status',
            template_id: $checkbox.data('template-id'),
            is_active: isActive
        });
    });

    // Open Edit Conditions Modal
    DOM.adminPage.on('click', '.sifency-edit-conditions-btn', function (e) {
        e.preventDefault();
        STATE.currentTemplateId = $(this).data('template-id');

        DOM.conditionsModalBody.html(`<p>${CONFIG.i18n.loading}</p>`);
        Utils.openModal(DOM.conditionsModal);

        Utils.ajax({
            action: 'sifency_get_display_conditions',
            template_id: STATE.currentTemplateId
        }).done(response => {
            if (response.success) {
                STATE.currentTemplateType = response.data.template_type || '';
                DOM.conditionsModalBody.html(response.data.html);
                ConditionsManager.initAllRows(DOM.conditionsModalBody);
            } else {
                DOM.conditionsModalBody.html(`<p>${CONFIG.i18n.error}</p>`);
            }
        });
    });

    // Close Modals Handling (Event Delegation)
    const closeModalHandler = function (e) {
        if ($(e.target).is('.sifency-modal-overlay, .sifency-modal-close')) {
            e.preventDefault();
            Utils.closeModal($(e.currentTarget));
        }
    };

    DOM.conditionsModal.on('click', closeModalHandler);
    DOM.newTemplateModal.on('click', closeModalHandler);

    // Open New Template Modal
    DOM.adminPage.on('click', '#sifency-open-new-template-modal', function (e) {
        e.preventDefault();
        Utils.openModal(DOM.newTemplateModal);
    });

    // Add Condition Row
    DOM.conditionsModal.on('click', '.sifency-add-condition', function (e) {
        e.preventDefault();
        const group = $(this).data('group');
        const $list = DOM.conditionsModal.find(`#sifency-${group}-rules`);
        const templateHtml = DOM.conditionsModal.find('#sifency-condition-row-template').html();

        $list.find('.sifency-no-rules-message').remove();
        const $newRow = $(templateHtml);

        $list.append($newRow);
        ConditionsManager.initSingleRow($newRow);
        $list.sortable('refresh');
    });

    // Remove Condition Row
    DOM.conditionsModal.on('click', '.sifency-remove-condition', function (e) {
        e.preventDefault();
        const $row = $(this).closest('.sifency-condition-row');
        const $select = $row.find('.sifency-condition-value');

        // Prevent memory leaks
        if ($select.hasClass('select2-hidden-accessible')) {
            $select.select2('destroy');
        }

        const $list = $row.closest('.sifency-conditions-list');
        $row.remove();

        // Re-check duplicates for remaining rows
        $list.find('.sifency-condition-row').each(function () {
            ConditionsManager.checkDuplication($(this));
        });

        ConditionsManager.updateSaveButtonState();
    });

    // Duplicate Condition Row
    DOM.conditionsModal.on('click', '.sifency-duplicate-condition', function (e) {
        e.preventDefault();
        const $row = $(this).closest('.sifency-condition-row');

        // Clone the row WITHOUT data/events to avoid Select2 conflicts
        const $newRow = $row.clone();

        // Remove Select2 components if they exist in the clone
        $newRow.find('.select2-container').remove();
        $newRow.find('select').removeClass('select2-hidden-accessible').removeAttr('data-select2-id').find('option').removeAttr('data-select2-id');

        // Append after current row
        $row.after($newRow);

        // Sync values manually (clone doesn't always preserve current select values)
        const currentType = $row.find('.sifency-condition-type').val();
        const currentSubtype = $row.find('.sifency-condition-subtype').val();

        $newRow.find('.sifency-condition-type').val(currentType);

        // Re-init the subtype dropdown
        ConditionsManager.updateSubtypeDropdown($newRow, currentSubtype);

        // Copy the value dropdown content and value
        const $originalValueSelect = $row.find('.sifency-condition-value');
        const $newValueSelect = $newRow.find('.sifency-condition-value');

        if ($originalValueSelect.val()) {
            $newValueSelect.html($originalValueSelect.html());
            $newValueSelect.val($originalValueSelect.val());
        }

        // Re-init the value dropdown (Select2 etc)
        ConditionsManager.updateValueDropdown($newRow);

        $row.closest('.sifency-conditions-list').sortable('refresh');
        ConditionsManager.updateSaveButtonState();
    });
    // Handle Subtype / Value dependencies
    DOM.conditionsModal.on('change', '.sifency-condition-type', function () {
        const $row = $(this).closest('.sifency-condition-row');
        ConditionsManager.updateSubtypeDropdown($row);
        ConditionsManager.updateSaveButtonState();
    });

    DOM.conditionsModal.on('change', '.sifency-condition-subtype', function () {
        const $row = $(this).closest('.sifency-condition-row');
        ConditionsManager.updateValueDropdown($row);
        ConditionsManager.updateSaveButtonState();
    });

    // Save Display Conditions
    DOM.saveConditionsBtn.on('click', function (e) {
        e.preventDefault();

        // Check for duplicates before saving
        if (DOM.conditionsModal.find('.is-duplicate').length > 0) {
            alert('This condition logic already exists in this group. Please resolve duplicates before saving.');
            return;
        }

        const $btn = $(this);
        if ($btn.hasClass('disabled')) return;

        Utils.toggleButtonState($btn, true);

        const conditions = {
            include: ConditionsManager.gatherRules('#sifency-include-rules .sifency-condition-row'),
            exclude: ConditionsManager.gatherRules('#sifency-exclude-rules .sifency-condition-row')
        };

        Utils.ajax({
            action: 'sifency_save_display_conditions',
            template_id: STATE.currentTemplateId,
            conditions: JSON.stringify(conditions)
        }).done(response => {
            if (response.success) {
                // Update UI Summary directly
                $(`.sifency-edit-conditions-btn[data-template-id="${STATE.currentTemplateId}"]`)
                    .closest('tr')
                    .find('.sifency-conditions-summary')
                    .text(response.data.summary);
                Utils.closeModal(DOM.conditionsModal);
            } else {
                alert(response.data.message || CONFIG.i18n.error);
            }
        }).always(() => {
            Utils.toggleButtonState($btn, false);
        });
    });

    // Create & Edit / Create & Save New Template
    DOM.createButtons.on('click', function (e) {
        e.preventDefault();
        const $button = $(this);
        if ($button.hasClass('disabled')) return;

        const shouldEdit = $button.is('#sifency-create-and-edit');
        const $titleInput = $('#sifency-template-title');
        const title = $titleInput.val().trim();
        const type = $('#sifency-template-type').val();

        if (!title) {
            alert('Please enter a template name.');
            $titleInput.focus();
            return;
        }

        Utils.toggleButtonState(DOM.createButtons, true);

        Utils.ajax({
            action: 'sifency_create_new_template',
            title: title,
            type: type
        }).done(res => {
            if (res.success) {
                if (shouldEdit && res.data.edit_url) {
                    window.location.href = res.data.edit_url;
                } else {
                    location.reload();
                }
            } else {
                alert('Error: ' + (res.data.message || 'An unknown error occurred.'));
                Utils.toggleButtonState(DOM.createButtons, false); // Only toggle false if it failed, page replaces if success
            }
        }).fail(() => {
            alert('An error occurred during the request. Please try again.');
            Utils.toggleButtonState(DOM.createButtons, false);
        });
    });

    /**
     * ==============================================
     * 6. SIDEBAR TOGGLE & ACCESSIBILITY LOGIC
     * ==============================================
     */
    const initSidebarToggle = () => {
        const $sidebar = $('.sifency-dashboard-nav');
        const $toggleBtn = $('.sifency-sidebar-toggle');
        if (!$sidebar.length || !$toggleBtn.length) return;

        // Set initial ARIA state on load based on width
        const updateAriaState = () => {
            const isMobile = window.innerWidth <= 991;
            if (isMobile) {
                const isExpanded = $sidebar.hasClass('is-expanded');
                $toggleBtn.attr('aria-expanded', isExpanded ? 'true' : 'false');
            } else {
                const isCollapsed = $sidebar.hasClass('is-collapsed');
                $toggleBtn.attr('aria-expanded', isCollapsed ? 'false' : 'true');
            }
        };

        // Initialize state
        updateAriaState();
        // Handle click event on toggle button
        $toggleBtn.on('click', function (e) {
            e.preventDefault();
            const isMobile = window.innerWidth <= 991;

            if (isMobile) {
                $sidebar.toggleClass('is-expanded');
            } else {
                $sidebar.toggleClass('is-collapsed');
            }
            updateAriaState();
        });

        // Expand sidebar when clicking on any item or group header when collapsed
        $sidebar.on('click', '.sifency-accordion-summary, .sifency-nav-item', function (e) {
            const isMobile = window.innerWidth <= 991;
            const isCollapsed = isMobile ? !$sidebar.hasClass('is-expanded') : $sidebar.hasClass('is-collapsed');

            if (isCollapsed) {
                // If it is a toggle button click itself, do nothing here (already handled)
                if ($(e.target).closest('.sifency-sidebar-toggle').length) return;

                if (isMobile) {
                    $sidebar.addClass('is-expanded');
                } else {
                    $sidebar.removeClass('is-collapsed');
                }
                updateAriaState();

                // Recalculate and transition details content height
                const $details = $(this).closest('details');
                if ($details.length) {
                    setTimeout(() => {
                        const content = $details.find('.sifency-accordion-content')[0];
                        if (content) {
                            content.style.maxHeight = content.scrollHeight + 'px';
                        }
                    }, 150); // Give CSS transition time to start and remove !important
                }
            }
        });

        // Handle window resize dynamically to sync states
        let resizeTimeout;
        $(window).on('resize', function () {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(updateAriaState, 150);
        });
    };

    initSidebarToggle();

    class SifencyAddonsStickyElement {
        constructor(el) {
            this.el = el;
            // Find parent container to restrict sticky movement (Elementor container, section, column, or parent)
            this.parent = el.closest('.elementor-widget-wrap, .elementor-column, .elementor-container, .e-con, .e-container, .elementor-section') || el.parentElement;

            // Get settings from data attributes with fallback defaults
            this.offset = Number(el.dataset.axistStickyOffset || 0);
            this.active = false;
            this.state = 'normal'; // States: 'normal', 'fixed', 'absolute'

            const rawDevices = el.dataset.axistStickyOn || 'desktop,tablet,mobile';
            this.devices = rawDevices.split(',').map(d => d.trim()).filter(Boolean);

            this.update = this.update.bind(this);
            this.debouncedResize = this.debounce(() => {
                this.reset(); // Reset layout variables on window resize to ensure correct width calculations
                this.update();
            }, 100);

            this.init();
            window.addEventListener('scroll', this.update, { passive: true });
            window.addEventListener('resize', this.debouncedResize);
        }

        init() {
            if (!this.parent) return;

            // Parent must have relative positioning so absolute positioning behaves properly at bottom boundary
            const parentStyle = window.getComputedStyle(this.parent);
            if (parentStyle.position === 'static') {
                this.parent.style.position = 'relative';
            }

            this.reset();
            this.update();
        }

        reset() {
            this.el.style.position = '';
            this.el.style.top = '';
            this.el.style.bottom = '';
            this.el.style.width = '';
            this.el.style.zIndex = '';
            this.state = 'normal';
        }

        isDeviceEnabled() {
            const width = window.innerWidth;
            let currentDevice = 'desktop';
            if (width < 768) {
                currentDevice = 'mobile';
            } else if (width < 1025) {
                currentDevice = 'tablet';
            }
            return this.devices.includes(currentDevice);
        }

        update() {
            if (!this.isDeviceEnabled()) {
                if (this.state !== 'normal') this.reset();
                return;
            }

            const parentRect = this.parent.getBoundingClientRect();
            const elRect = this.el.getBoundingClientRect();
            const scrollTop = window.scrollY || window.pageYOffset;
            const parentTop = scrollTop + parentRect.top;
            const parentBottom = scrollTop + parentRect.bottom;
            const elHeight = elRect.height;

            // If sticky element is taller than or equal to its container, do not trigger sticky behavior
            if (elHeight >= parentRect.height) {
                if (this.state !== 'normal') this.reset();
                return;
            }

            if (scrollTop + this.offset > parentTop && scrollTop + this.offset + elHeight < parentBottom) {
                // State: Fixed (scrolling within parent bounds)
                if (this.state !== 'fixed') {
                    // Calculate exact inner width of the parent container to keep the width consistent
                    const parentPaddingLeft = parseFloat(window.getComputedStyle(this.parent).paddingLeft) || 0;
                    const parentPaddingRight = parseFloat(window.getComputedStyle(this.parent).paddingRight) || 0;
                    const currentWidth = this.parent.clientWidth - (parentPaddingLeft + parentPaddingRight);

                    this.el.style.position = 'fixed';
                    this.el.style.top = this.offset + 'px';
                    this.el.style.bottom = '';
                    this.el.style.width = currentWidth + 'px';
                    this.el.style.zIndex = '99';
                    this.state = 'fixed';
                }
            } else if (scrollTop + this.offset + elHeight >= parentBottom) {
                // State: Absolute (pushed to the very bottom of the parent container)
                if (this.state !== 'absolute') {
                    this.el.style.position = 'absolute';
                    this.el.style.top = 'auto';
                    this.el.style.bottom = '0';
                    this.el.style.width = '100%';
                    this.el.style.zIndex = '99';
                    this.state = 'absolute';
                }
            } else {
                // State: Normal
                if (this.state !== 'normal') {
                    this.reset();
                }
            }
        }

        debounce(func, wait) {
            let timeout;
            return (...args) => {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), wait);
            };
        }
    }

    function initAllSifencyAddonsSticky(context = document) {
        // Target elements matching the .sa-sticky class OR data-sa-sticky="true" attribute
        const elements = context.querySelectorAll('[data-sa-sticky="true"], .sa-sticky');
        elements.forEach(el => {
            if (!el.axistStickyInstance) {
                el.axistStickyInstance = new SifencyAddonsStickyElement(el);
            }
        });
    }

    $(window).on('load', () => initAllSifencyAddonsSticky());
    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', (scope) => {
            const context = scope[0];
            initAllSifencyAddonsSticky(context);
        });
    });

});