(function ($) {
    // Function to initialize the accordion
    function initializeAccordion($scope) {
        // Handle click event for accordion titles
        $scope.find('.tx-accordion .tx-accordion-tab-title').on('click', function () {
            const $this = $(this);
            const $content = $this.next('.tx-accordion-tab-content');

            // Toggle the current accordion content
            if ($this.hasClass('tx-accordion-active')) {
                $this.removeClass('tx-accordion-active');
                $content.slideUp(400);
            } else {
                // Close other open accordion items
                $this.closest('.tx-accordion').find('.tx-accordion-tab-title.tx-accordion-active').removeClass('tx-accordion-active');
                $this.closest('.tx-accordion').find('.tx-accordion-tab-content').slideUp(400);

                // Open the clicked accordion item
                $this.addClass('tx-accordion-active');
                $content.slideDown(400);
            }
        });

        // Open the first accordion item by default
        const $firstTabTitle = $scope.find('.tx-accordion .tx-accordion-tab-title').first();
        const $firstTabContent = $scope.find('.tx-accordion .tx-accordion-tab-content').first();

        if (!$firstTabTitle.hasClass('tx-accordion-active')) {
            $firstTabTitle.addClass('tx-accordion-active');
            $firstTabContent.slideDown(400);
        }
    }

    // Check if running inside Elementor editor
    $(window).on('elementor/frontend/init', function () {
        // Initialize the accordion for both frontend and editor modes
        elementorFrontend.hooks.addAction('frontend/element_ready/avas-accordion.default', initializeAccordion);
    });
})(jQuery);
