(function ($) {
    'use strict';

    const SifencyFlipBox = function ($scope, $) {
        const $wrapper = $scope.find('.sifency-fb-wrapper');
        
        // Ensure that these selectors are only applied if the elements actually exist
        const $triggerBtn = $wrapper.find('.sifency-fb-overlay-trigger');
        const $closeBtn = $wrapper.find('.sifency-fb-overlay-close');

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

        let settings = {};
        try {
            const raw = $wrapper.data('fb-settings');
            if (raw) {
                settings = raw;
            }
        } catch (e) {
            console.error('Error parsing flipbox settings:', e);
            return;
        }

        if (settings.mode === 'click') {
            // Toggle 'sifency-active' class on the entire wrapper for box click
            $wrapper.on('click', function() {
                $(this).toggleClass('sifency-active');
            });
        }

        if (settings.mode === 'overlay') {
            // Specific handling for overlay mode with separate trigger/close icons
            if ($triggerBtn.length) {
                $triggerBtn.on('click', function(e) {
                    e.preventDefault(); // Prevent default link behavior if any
                    e.stopPropagation(); // Stop propagation to prevent parent wrapper click
                    $wrapper.addClass('sifency-active');
                });
            }

            if ($closeBtn.length) {
                $closeBtn.on('click', function(e) {
                    e.preventDefault(); // Prevent default link behavior if any
                    e.stopPropagation(); // Stop propagation to prevent parent wrapper click
                    $wrapper.removeClass('sifency-active');
                });
            }
            
            // Optional: Close overlay if clicking outside the back content area
            // $wrapper.on('click', function(e) {
            //     if ($(this).hasClass('sifency-active') && !$(e.target).closest('.sifency-fb-back .sifency-fb-content').length && !$(e.target).closest('.sifency-fb-overlay-trigger').length) {
            //         $(this).removeClass('sifency-active');
            //     }
            // });
        }
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-flip-box.default', SifencyFlipBox);
    });

})(jQuery);