( function ( $ ) {
	'use strict';

	// =========================================================================
	// UTILITIES
	// =========================================================================

	/** Safe CSS.escape polyfill */
	var cssEscape = ( typeof CSS !== 'undefined' && CSS.escape )
		? function ( s ) { return CSS.escape( s ); }
		: function ( s ) { return s.replace( /([^\w-])/g, '\\$1' ); };

	/**
	 * Autoplay factory — returns { start, stop }.
	 * Works for both tabs and accordions via a callback.
	 */
	function createAutoplay( $wrapper, interval, pauseOnHover, onTick ) {
		var timer = null;

		function start() {
			if ( timer ) return;
			timer = setInterval( onTick, interval );
		}

		function stop() {
			clearInterval( timer );
			timer = null;
		}

		if ( pauseOnHover ) {
			$wrapper.on( 'mouseenter.sitselAutoplay', stop );
			$wrapper.on( 'mouseleave.sitselAutoplay', start );
		}

		return { start: start, stop: stop };
	}

	// =========================================================================
	// ACCORDION HELPERS  (shared between real accordion + bp-accordion)
	// =========================================================================

	function openItem( $item ) {
		var $content = $item.find( '> .sitsel-accordion-content' );
		$content.off( 'transitionend.sitselAccOpen' );
		$item.addClass( 'sitsel-active' );
		$item.find( '> .sitsel-accordion-btn' ).attr( 'aria-expanded', 'true' );
		$content[ 0 ].style.maxHeight = $content[ 0 ].scrollHeight + 'px';
		$content.one( 'transitionend.sitselAccOpen', function () {
			if ( $item.hasClass( 'sitsel-active' ) ) {
				$content[ 0 ].style.maxHeight = 'none';
			}
		} );
	}

	function closeItem( $item ) {
		var $content = $item.find( '> .sitsel-accordion-content' );
		$content.off( 'transitionend.sitselAccOpen' );
		if ( 'none' === $content[ 0 ].style.maxHeight || '' === $content[ 0 ].style.maxHeight ) {
			$content[ 0 ].style.maxHeight = $content[ 0 ].scrollHeight + 'px';
			// eslint-disable-next-line no-unused-expressions
			$content[ 0 ].offsetHeight; // force reflow
		}
		$item.removeClass( 'sitsel-active' );
		$item.find( '> .sitsel-accordion-btn' ).attr( 'aria-expanded', 'false' );
		$content[ 0 ].style.maxHeight = '0';
	}

	function initAccordionItems( $wrapper, $items, allowMultiple ) {
		// Set initial heights
		$items.each( function () {
			var $item    = $( this );
			var $content = $item.find( '> .sitsel-accordion-content' );
			$content[ 0 ].style.maxHeight = $item.hasClass( 'sitsel-active' ) ? 'none' : '0';
			$item.find( '> .sitsel-accordion-btn' ).attr(
				'aria-expanded', $item.hasClass( 'sitsel-active' ) ? 'true' : 'false'
			);
		} );

		$items.each( function () {
			var $item = $( this );
			var $btn  = $item.find( '> .sitsel-accordion-btn' );

			$btn.on( 'click.sitselAccordion', function ( e ) {
				e.preventDefault();
				var isOpen = $item.hasClass( 'sitsel-active' );

				if ( ! allowMultiple ) {
					$items.filter( '.sitsel-active' ).not( $item ).each( function () {
						closeItem( $( this ) );
					} );
				}

				isOpen ? closeItem( $item ) : openItem( $item );
				$wrapper.trigger( 'sitsel:accordion:changed', [ $item, ! isOpen ] );
			} );

			$btn.on( 'keydown.sitselAccordion', function ( e ) {
				var key = e.key;
				var idx = $items.index( $item );
				var next;

				if      ( 'ArrowDown' === key ) { next = ( idx + 1 ) % $items.length; }
				else if ( 'ArrowUp'   === key ) { next = ( idx - 1 + $items.length ) % $items.length; }
				else if ( 'Home'      === key ) { next = 0; }
				else if ( 'End'       === key ) { next = $items.length - 1; }
				else { return; }

				e.preventDefault();
				$items.eq( next ).find( '> .sitsel-accordion-btn' ).trigger( 'focus' );
			} );
		} );
	}

	// =========================================================================
	// BREAKPOINT — mobile behaviour for tabs
	// =========================================================================

	function initBreakpoint( $wrapper ) {
		var bp   = parseInt( $wrapper.data( 'breakpoint' ), 10 );
		var mode = $wrapper.data( 'breakpoint-behavior' ) || 'scroll'; // 'scroll' | 'collapse' | 'accordion'

		if ( ! bp || isNaN( bp ) ) return;

		var $dynAcc = null;

		// ── Build a lightweight accordion from the current tab data ───────────
		function buildBpAccordion() {
    if ( $dynAcc ) return;

    // Save original markup for desktop restore
    $wrapper.data( 'sitsel-original-html', $wrapper.html() );

    var items = [];
    $wrapper.find( '.sitsel-tabs-nav .sitsel-tab-btn' ).each( function () {
        var $btn     = $( this );
        var targetId = $btn.data( 'tab' );
        var $panel   = $wrapper.find( '#' + cssEscape( targetId ) );
        var isActive = $btn.hasClass( 'sitsel-active' );
        var $tabIcon    = $btn.find( '.sitsel-tab-icon' );
        var tabIconHtml = $tabIcon.length ? '<span class="sitsel-accordion-tab-icon" aria-hidden="true">' + $tabIcon.html() + '</span>' : '';

        items.push(
            '<div class="sitsel-accordion-item' + ( isActive ? ' sitsel-active' : '' ) + '">' +
                '<button class="sitsel-accordion-btn sitsel-acc-icon-pos-right" aria-expanded="' + ( isActive ? 'true' : 'false' ) + '">' +
                    tabIconHtml +
                    '<span class="sitsel-accordion-label">' + $btn.find( '.sitsel-tab-label' ).text() + '</span>' +
                    '<span class="sitsel-accordion-icon sitsel-acc-icon-plus-minus" aria-hidden="true"></span>' +
                '</button>' +
                '<div class="sitsel-accordion-content"><div class="sitsel-accordion-content-inner">' +
                    $panel.html() +
                '</div></div>' +
            '</div>'
        );
    } );

    // Replace wrapper contents in-place
    $wrapper.empty().html( items.join( '' ) );
    $wrapper.addClass( 'sitsel-accordion-wrapper sitsel-bp-accordion' );

    var $bpItems = $wrapper.find( '> .sitsel-accordion-item' );
    initAccordionItems( $wrapper, $bpItems, false );

    $dynAcc = $wrapper; // same element, no second DOM node
}

		// ── Apply / remove breakpoint state ───────────────────────────────────
		function applyBreakpoint() {
			var isMobile = ( $( window ).width() <= bp );

			if ( isMobile ) {
				if ( 'accordion' === mode ) {
					buildBpAccordion();
					
				} else if ( 'scroll' === mode ) {
                    if ( $wrapper.hasClass( 'sitsel-layout-vertical' ) ) {
                        // vertical + scroll breakpoint → collapse to wrapped horizontal
                        $wrapper.addClass( 'sitsel-collapsed' ).removeClass( 'sitsel-scroll sitsel-bp-hidden' );
                    } else {
                        $wrapper.addClass( 'sitsel-scroll' ).removeClass( 'sitsel-collapsed sitsel-bp-hidden' );
                    }
                    if ( $dynAcc ) $dynAcc.hide();
				} else {
					// collapse (wrap)
					$wrapper.addClass( 'sitsel-collapsed' ).removeClass( 'sitsel-scroll sitsel-bp-hidden' );
					if ( $dynAcc ) $dynAcc.hide();
				}
			} else {
				if ( $dynAcc ) {
					// Restore original tabs HTML
					var original = $wrapper.data( 'sitsel-original-html' );
					if ( original ) {
						$wrapper.html( original );
						$wrapper.removeData( 'sitsel-original-html' );
					}
					$wrapper.removeClass( 'sitsel-accordion-wrapper sitsel-bp-accordion' );
					$dynAcc = null;
				}
				$wrapper.removeClass( 'sitsel-collapsed sitsel-bp-hidden sitsel-scroll' );
			}
		}

		applyBreakpoint();

		var resizeTimer;
		$( window ).on( 'resize.sitselBreakpoint', function () {
			clearTimeout( resizeTimer );
			resizeTimer = setTimeout( applyBreakpoint, 100 );
		} );
	}

	// =========================================================================
	// TABS
	// =========================================================================

	function initSitselTabs( $scope ) {
		$scope.find( '.sitsel-tabs-wrapper' ).each( function () {
			var $wrapper = $( this );

			if ( $wrapper.data( 'sitsel-tabs-init' ) ) return;
			$wrapper.data( 'sitsel-tabs-init', true );

			var $nav     = $wrapper.find( '.sitsel-tabs-nav' );
			var $buttons = $nav.find( '.sitsel-tab-btn' );
			var $panels  = $wrapper.find( '.sitsel-tabs-content-wrap .sitsel-tab-content' );

			if ( ! $buttons.length || ! $panels.length ) return;

			// ── Activate a tab ─────────────────────────────────────────────────
			function activateTab( $btn, userInitiated ) {
				var targetId = String( $btn.data( 'tab' ) || '' );
				if ( ! targetId || ! /^[\w-]+$/.test( targetId ) ) return;

				$buttons.removeClass( 'sitsel-active' ).attr( { 'aria-selected': 'false', tabindex: '-1' } );
				$btn.addClass( 'sitsel-active' ).attr( { 'aria-selected': 'true', tabindex: '0' } );

				$panels.removeClass( 'sitsel-active' ).attr( 'hidden', '' );
				var $target = $wrapper.find( '#' + cssEscape( targetId ) );
				if ( $target.length ) {
					$target.addClass( 'sitsel-active' ).removeAttr( 'hidden' );
				}

				// Scroll active tab into view
				var nav = $nav[ 0 ];
				var btn = $btn[ 0 ];
				if ( nav && btn ) {
					if ( nav.scrollWidth > nav.clientWidth ) {
						nav.scrollTo( {
							left     : btn.offsetLeft - ( nav.clientWidth / 2 ) + ( btn.offsetWidth / 2 ),
							behavior : 'smooth',
						} );
					} else if ( nav.scrollHeight > nav.clientHeight ) {
						nav.scrollTo( {
							top      : btn.offsetTop - ( nav.clientHeight / 2 ) + ( btn.offsetHeight / 2 ),
							behavior : 'smooth',
						} );
					} else if ( userInitiated ) {
						btn.scrollIntoView( { behavior: 'smooth', block: 'nearest', inline: 'nearest' } );
					}
				}

				$wrapper.trigger( 'sitsel:tab:changed', [ $btn, $target ] );
			}

			// ── Click ──────────────────────────────────────────────────────────
			$buttons.on( 'click.sitselTabs', function ( e ) {
				e.preventDefault();
				activateTab( $( this ), true );
			} );

			// ── Keyboard (WAI-ARIA tabs pattern) ──────────────────────────────
			$buttons.on( 'keydown.sitselTabs', function ( e ) {
				var key        = e.key;
				var isVertical = $wrapper.hasClass( 'sitsel-layout-vertical' ) || $wrapper.hasClass( 'sitsel-collapsed' );
				var idx        = $buttons.index( $( this ) );
				var next;

				if      ( ( ! isVertical && 'ArrowRight' === key ) || ( isVertical && 'ArrowDown'  === key ) ) { next = ( idx + 1 ) % $buttons.length; }
				else if ( ( ! isVertical && 'ArrowLeft'  === key ) || ( isVertical && 'ArrowUp'    === key ) ) { next = ( idx - 1 + $buttons.length ) % $buttons.length; }
				else if ( 'Home' === key ) { next = 0; }
				else if ( 'End'  === key ) { next = $buttons.length - 1; }
				else { return; }

				e.preventDefault();
				var $next = $buttons.eq( next );
				$next.trigger( 'focus' );
				activateTab( $next, true );
			} );

			// ── Initial hidden state ───────────────────────────────────────────
			$panels.not( '.sitsel-active' ).attr( 'hidden', '' );
			$panels.filter( '.sitsel-active' ).removeAttr( 'hidden' );

			// ── Autoplay ───────────────────────────────────────────────────────
			if ( 'yes' === $wrapper.data( 'autoplay' ) ) {
				var interval     = parseInt( $wrapper.data( 'autoplay-interval' ), 10 ) || 4000;
				var pauseOnHover = 'no' !== String( $wrapper.data( 'autoplay-pause' ) );

                var ap = createAutoplay( $wrapper, interval, pauseOnHover, function () {
                    // If bp-accordion is active, cycle its items instead
                    var $bpAcc = $wrapper.next( '.sitsel-bp-accordion' );
                    if ( $wrapper.hasClass( 'sitsel-bp-hidden' ) && $bpAcc.length ) {
                        var $bpItems = $bpAcc.find( '> .sitsel-accordion-item' );
                        var $active  = $bpItems.filter( '.sitsel-active' ).first();
                        var currIdx  = $bpItems.index( $active );
                        var nextIdx  = ( currIdx + 1 ) % $bpItems.length;
                        if ( $active.length ) closeItem( $active );
                        openItem( $bpItems.eq( nextIdx ) );
                    } else {
                        var $active  = $buttons.filter( '.sitsel-active' );
                        var currIdx  = $buttons.index( $active );
                        activateTab( $buttons.eq( ( currIdx + 1 ) % $buttons.length ) );
                    }
                } );

				ap.start();

				$buttons.on( 'click.sitselAutoplay keydown.sitselAutoplay', function () {
					ap.stop();
					if ( pauseOnHover ) {
						$wrapper.one( 'mouseleave.sitselAutoplayResume', ap.start );
					}
				} );
			}

			// ── Responsive breakpoint ─────────────────────────────────────────
			initBreakpoint( $wrapper );
		} );
	}

	// =========================================================================
	// ACCORDION
	// =========================================================================

	function initSitselAccordion( $scope ) {
		$scope.find( '.sitsel-accordion-wrapper:not(.sitsel-bp-accordion)' ).each( function () {
			var $wrapper = $( this );

			if ( $wrapper.data( 'sitsel-acc-init' ) ) return;
			$wrapper.data( 'sitsel-acc-init', true );

			var allowMultiple = ( 'yes' === String( $wrapper.data( 'multiple' ) ) );
			var $items        = $wrapper.find( '> .sitsel-accordion-item' );

			if ( ! $items.length ) return;

			initAccordionItems( $wrapper, $items, allowMultiple );

			// ── Autoplay ───────────────────────────────────────────────────────
			if ( 'yes' === String( $wrapper.data( 'autoplay' ) ) ) {
				var interval     = parseInt( $wrapper.data( 'autoplay-interval' ), 10 ) || 4000;
				var pauseOnHover = 'no' !== String( $wrapper.data( 'autoplay-pause' ) );

				var ap = createAutoplay( $wrapper, interval, pauseOnHover, function () {
					var $active = $items.filter( '.sitsel-active' ).first();
					var currIdx = $items.index( $active );
					var nextIdx = ( currIdx + 1 ) % $items.length;

					if ( ! allowMultiple && $active.length ) {
						closeItem( $active );
					}
					openItem( $items.eq( nextIdx ) );
				} );

				ap.start();

				$items.find( '> .sitsel-accordion-btn' ).on( 'click.sitselAccAutoplay keydown.sitselAccAutoplay', function () {
					ap.stop();
					if ( pauseOnHover ) {
						$wrapper.one( 'mouseleave.sitselAccAutoplayResume', ap.start );
					}
				} );
			}
		} );
	}

	// =========================================================================
	// ENTRY POINT
	// =========================================================================

	function initSitselWidget( $scope ) {
		initSitselTabs( $scope );
		initSitselAccordion( $scope );
	}

	// =========================================================================
	// ELEMENTOR HOOKS
	// =========================================================================

	$( window ).on( 'elementor/frontend/init', function () {

		elementorFrontend.hooks.addAction( 'frontend/element_ready/sitsel_tabs.default', function ( $scope ) {
			initSitselWidget( $scope );
		} );

		// Editor live-preview: observe DOM mutations
		if ( 'undefined' !== typeof elementor ) {
			elementor.on( 'preview:loaded', function () {
				var $previewBody = elementor.$preview.contents().find( 'body' );
				if ( ! $previewBody.length ) return;

				var observer = new MutationObserver( function ( mutations ) {
					mutations.forEach( function ( mutation ) {
						mutation.addedNodes.forEach( function ( node ) {
							if ( node.nodeType !== 1 ) return;
							var $node = $( node );

							if ( $node.hasClass( 'elementor-widget-sitsel_tabs' ) ) {
								// Re-init: clear cached init flags so controls re-apply
								$node.find( '.sitsel-tabs-wrapper' ).removeData( 'sitsel-tabs-init' );
								$node.find( '.sitsel-accordion-wrapper' ).removeData( 'sitsel-acc-init' );
								initSitselWidget( $node );
							} else {
								$node.find( '.elementor-widget-sitsel_tabs' ).each( function () {
									var $w = $( this );
									$w.find( '.sitsel-tabs-wrapper' ).removeData( 'sitsel-tabs-init' );
									$w.find( '.sitsel-accordion-wrapper' ).removeData( 'sitsel-acc-init' );
									initSitselWidget( $w );
								} );
							}
						} );
					} );
				} );

				observer.observe( $previewBody[ 0 ], { childList: true, subtree: true } );
			} );
		}
	} );

	// ── Plain page-load fallback ───────────────────────────────────────────────
	$( document ).ready( function () {
		if ( 'undefined' === typeof elementorFrontend ) {
			initSitselWidget( $( 'body' ) );
		}
	} );

} )( jQuery );