(function ($) {
    'use strict';

    const SifencyTOC = function ($scope, $) {
        const $wrapper = $scope.find('.sifency-toc-wrapper');
        const $nav = $wrapper.find('.sifency-toc-nav');
        const $spinner = $wrapper.find('.sifency-toc-spinner');
        const $toggle = $wrapper.find('.sifency-toc-toggle');
        const $body = $wrapper.find('.sifency-toc-body');

        let settings = { headings: 'h2,h3,h4', container: '', exclude: '', marker: 'numbers', icon: '' };
        try {
            const raw = $wrapper.data('toc-settings');
            if (raw) $.extend(settings, raw);
        } catch (e) {}

        const containerSelector = settings.container ? settings.container : '.elementor-page';
        const $container = $(containerSelector).first();
        
        if (!$container.length) {
            $spinner.hide();
            $nav.html('<p>Content not found.</p>');
            return;
        }

        let selector = settings.headings;
        
        const $headings = $container.find(selector).filter(function() {
            if (settings.exclude && $(this).is(settings.exclude)) return false;
            if ($(this).offset().top === 0) return false;
            return true;
        });

        if (!$headings.length) {
            $spinner.hide();
            return;
        }

        let html = '<ul class="sifency-toc-list">';
        let itemIndex = 0;

        $headings.each(function(index) {
            const $h = $(this);
            let id = $h.attr('id');
            const title = $h.text();
            const tag = $h.prop('tagName').toLowerCase();

            if (!id) {
                id = 'toc-' + title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') + '-' + index;
                $h.attr('id', id);
            }

            let markerHTML = '';
            if (settings.marker === 'numbers') {
                itemIndex++;
                markerHTML = `<span class="sifency-toc-marker">${itemIndex}.</span>`;
            } else if (settings.marker === 'bullets') {
                markerHTML = `<span class="sifency-toc-marker">•</span>`;
            } else if (settings.marker === 'icon') {
                markerHTML = `<span class="sifency-toc-marker">${settings.icon}</span>`;
            }

            html += `<li class="sifency-toc-list-item sifency-toc-level-${tag}">
                        <a href="#${id}" class="sifency-toc-link" data-target="${id}">
                            ${markerHTML}
                            <span class="sifency-toc-text">${title}</span>
                        </a>
                     </li>`;
        });

        html += '</ul>';
        $nav.html(html);
        $spinner.hide();

        if ($toggle.length) {
            $toggle.on('click', function() {
                $body.slideToggle();
                $wrapper.toggleClass('collapsed');
                const icon = $(this).find('i');
                if ($wrapper.hasClass('collapsed')) {
                    icon.removeClass('eicon-plus').addClass('eicon-plus');
                } else {
                    icon.removeClass('eicon-plus').addClass('eicon-plus');
                }
            });
        }

        const observerOptions = {
            root: null,
            rootMargin: '-100px 0px -60% 0px',
            threshold: 0
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const id = entry.target.getAttribute('id');
                    $nav.find('.sifency-toc-link').removeClass('is-active');
                    const $activeLink = $nav.find(`.sifency-toc-link[data-target="${id}"]`);
                    $activeLink.addClass('is-active');
                }
            });
        }, observerOptions);

        $headings.each(function() {
            observer.observe(this);
        });

        $nav.on('click', 'a', function(e) {
            e.preventDefault();
            const targetId = $(this).attr('href');
            const $target = $(targetId);
            
            if ($target.length) {
                const offsetTop = $target.offset().top - 100;
                
                $('html, body').animate({
                    scrollTop: offsetTop
                }, 500);
            }
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-table-of-contents.default', SifencyTOC);
    });

})(jQuery);