(function (window, document, $) {
    'use strict';

    class SifencyStickyElement {
        constructor(el) {
            this.el = el;
            this.parent = el.closest('.elementor-widget-wrap, .elementor-container, .e-con, .e-container, .elementor-section') || el.parentElement;
            this.offset = Number(el.dataset.sifencyStickyOffset || 0);
            this.active = false;
            this.state = 'normal'; // 'normal', 'fixed', 'absolute'
            const rawDevices = el.dataset.sifencyStickyOn || 'desktop,tablet,mobile';
            this.devices = rawDevices.split(',').map(d => d.trim()).filter(Boolean);

            this.update = this.update.bind(this);
            this.debouncedResize = this.debounce(() => this.update(), 100);

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

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

            // Ensure parent has relative positioning for absolute placement at bottom
            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;

            // Skip if element taller than parent (can't stick)
            if (elHeight >= parentRect.height) {
                if (this.state !== 'normal') this.reset();
                return;
            }

            if (scrollTop + this.offset > parentTop && scrollTop + this.offset + elHeight < parentBottom) {
                if (this.state !== 'fixed') {
                    const currentWidth = this.el.offsetWidth;
                    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 (Hit bottom of parent)
                if (this.state !== 'absolute') {
                    this.el.style.position = 'absolute';
                    this.el.style.top = 'auto';
                    this.el.style.bottom = '0';
                    this.el.style.width = '';
                    this.el.style.zIndex = '99';
                    this.state = 'absolute';
                }
            } else {
                // State: Normal flow
                if (this.state !== 'normal') {
                    this.reset();
                }
            }
        }

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

    function initAllSifencySticky(context = document) {
        const elements = context.querySelectorAll('[data-sifency-sticky="true"]');
        elements.forEach(el => {
            if (!el.sifencyStickyInstance) {
                el.sifencyStickyInstance = new SifencyStickyElement(el);
            }
        });
    }

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

})(window, document, jQuery);
