/*
Auto-wraps ".wikitable" elements in a wrapper with helper elements to guarantee 100% width and indicate scrollability
See detailed documentation in Dev/mediawiki
deferrable:YES -- The user will not need (or see) this info immediately anyways
*/

(function () {
	
	const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
	
	$('table.wikitable').each( function() {
		let table = $(this);
		let wrapper = $('<div class="wikitable-auto-wrapper"><div class="before"></div><div class="table-content"></div><div class="after"></div>');
		
		let originalTableHeight = table.height();
		
		function enrich() {
			wrapper.css( {
				height: originalTableHeight,
				margin: window.getComputedStyle( table[0] ).getPropertyValue('margin'),
			});
			
			let tableContentDiv = wrapper.find('.table-content');
			wrapper.insertBefore( table );
			tableContentDiv.append( table );
			
			if( isMobile && tableContentDiv.width() < tableContentDiv.prop('scrollWidth') ) {
				wrapper.addClass('scroll-overflow-mobile');
				wrapper.css( 'top', - wrapper.children('.before').height() );
			}
		}
		
		// Normal case
		if( originalTableHeight > 0 ) {
			enrich();
		}
		// In cases where the table is hidden, for example in mw-collapsible
		else {
			if( IntersectionObserver ) {
				new IntersectionObserver((entries, observer) => {
					entries.forEach(entry => {
						if(entry.intersectionRatio > 0) {
							originalTableHeight = table.height();
							enrich();
							// So it just happens once
							observer.disconnect();
						}
					});
				}).observe(table[0]);
			}
		}
	});

})();

/*
[[Category:MultiWiki]]
*/