/**
 * FansPaysite Fullpage Archive Mode
 *
 * Handles keyboard navigation, indicator dots, adjacent-post
 * preloading, and auto-pagination for fullpage archive display.
 *
 * @package FansPaysite
 * @since   2.3
 */

/**
 * Show loading indicator
 */
function showLoadingIndicator( message ) {
	var indicator = document.createElement( 'div' );
	indicator.className = 'fps-loading-indicator';
	indicator.textContent = message || 'Loading...';
	indicator.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);'
		+ 'background:rgba(0,0,0,0.8);color:#fff;padding:20px 40px;border-radius:8px;'
		+ 'z-index:9999;font-size:16px;font-weight:500;';
	document.body.appendChild( indicator );
}

document.addEventListener( 'DOMContentLoaded', function () {
	var container = document.getElementById( 'fps-fullpage' );
	
	if ( ! container ) {
		// Handle auto-pagination for non-fullpage modes
		handleAutoPagination();
		return;
	}
	
	var slides = container.querySelectorAll( '.fps-fullpage-slide' );
	if ( slides.length === 0 ) {
		return;
	}

	var currentIndex = 0;
	var isNavigating = false;
	var isSafari = /^((?!chrome|android).)*safari/i.test( navigator.userAgent );

	// --- Navigation Dots ---
	var dotsContainer = document.createElement( 'nav' );
	dotsContainer.className = 'fps-fullpage-dots';
	dotsContainer.setAttribute( 'aria-label', 'Post navigation' );

	slides.forEach( function ( slide, i ) {
		var dot = document.createElement( 'button' );
		dot.className = 'fps-fullpage-dot' + ( i === 0 ? ' active' : '' );
		dot.setAttribute( 'aria-label', 'Go to post ' + ( i + 1 ) );
		dot.addEventListener( 'click', function () {
			scrollToSlide( i );
		} );
		dotsContainer.appendChild( dot );
	} );

	document.body.appendChild( dotsContainer );

	// --- Scroll to slide ---
	function scrollToSlide( index, behavior ) {
		if ( index < 0 || index >= slides.length ) {
			return;
		}
		var scrollBehavior = behavior || 'smooth';
		slides[ index ].scrollIntoView( { behavior: scrollBehavior, block: 'start' } );
		currentIndex = index;
		updateDots();
		preloadAdjacent( index );
	}

	// --- Update active dot ---
	function updateDots() {
		var dots = dotsContainer.querySelectorAll( '.fps-fullpage-dot' );
		dots.forEach( function ( dot, i ) {
			dot.classList.toggle( 'active', i === currentIndex );
		} );
	}

	// --- Detect current slide on scroll ---
	if ( 'IntersectionObserver' in window ) {
		var observer = new IntersectionObserver(
			function ( entries ) {
				entries.forEach( function ( entry ) {
					if ( entry.isIntersecting && entry.intersectionRatio > 0.5 ) {
						var idx = parseInt( entry.target.getAttribute( 'data-post-index' ), 10 );
						if ( ! isNaN( idx ) && idx !== currentIndex ) {
							currentIndex = idx;
							updateDots();
							preloadAdjacent( idx );
						}
					}
				} );
			},
			{
				root: null, // Use viewport as root since container doesn't scroll
				threshold: 0.5,
			}
		);

		slides.forEach( function ( slide ) {
			observer.observe( slide );
		} );
	}

	// --- Auto-pagination on scroll attempt ---
	var scrollAttempts = 0;
	var scrollAttemptTimeout = null;
	var scrollTarget = document.querySelector('.site-content') || window;
	var lastScrollTop = scrollTarget === window ? window.pageYOffset : scrollTarget.scrollTop;
	var wheelLocked = false;
	var footerScrollAttempts = 0;
	var footerScrollTimeout = null;
	var footerVisibleAt = null;

	if ( scrollTarget !== window ) {
		scrollTarget.setAttribute( 'tabindex', '-1' );
	}
	container.setAttribute( 'tabindex', '-1' );

	function lockWheel() {
		wheelLocked = true;
		setTimeout( function () {
			wheelLocked = false;
		}, 900 );
	}

	function releaseNavigateLock() {
		setTimeout( function () {
			isNavigating = false;
		}, 700 );
	}

	function handleWheel( e ) {
		if ( wheelLocked || isNavigating ) {
			return;
		}

		var delta = e.deltaY;
		if ( delta === 0 || Math.abs( delta ) < 15 ) {
			return;
		}

		var atLastSlide = currentIndex >= slides.length - 1;
		var atFirstSlide = currentIndex === 0;

		if ( atLastSlide && delta > 0 ) {
			var footer = document.querySelector( '.site-footer' );
			var footerVisible = true;
			if ( footer ) {
				var footerRect = footer.getBoundingClientRect();
				footerVisible = footerRect.top < window.innerHeight && footerRect.bottom <= window.innerHeight + 8;
			}

			if ( footerVisible ) {
				if ( footerVisibleAt === null ) {
					footerVisibleAt = Date.now();
				}
			} else {
				footerVisibleAt = null;
				footerScrollAttempts = 0;
			}

			if ( footerVisible && footerVisibleAt && Date.now() - footerVisibleAt >= 1000 ) {
				footerScrollAttempts++;
				clearTimeout( footerScrollTimeout );
				footerScrollTimeout = setTimeout( function () {
					footerScrollAttempts = 0;
				}, 1200 );

				if ( footerScrollAttempts >= 2 ) {
					var nextLink = document.querySelector( '.nav-links .nav-previous a' );
					if ( nextLink ) {
						showLoadingIndicator( 'Loading next page...' );
						window.location.href = nextLink.href;
					}
				}
			}
		}

		if ( isSafari ) {
			return;
		}

		if ( delta > 0 && ! atLastSlide ) {
			e.preventDefault();
			isNavigating = true;
			lockWheel();
			scrollToSlide( currentIndex + 1, 'auto' );
			releaseNavigateLock();
		} else if ( delta < 0 && ! atFirstSlide ) {
			e.preventDefault();
			isNavigating = true;
			lockWheel();
			scrollToSlide( currentIndex - 1, 'auto' );
			releaseNavigateLock();
		}
	}

	function handleScroll() {
		var scrollTop = scrollTarget === window ? window.pageYOffset : scrollTarget.scrollTop;
		var scrollHeight = scrollTarget === window ? document.documentElement.scrollHeight : scrollTarget.scrollHeight;
		var clientHeight = scrollTarget === window ? window.innerHeight : scrollTarget.clientHeight;
		var nearBottom = scrollTop + clientHeight >= scrollHeight - 150;
		var nearTop = scrollTop <= 150;

		// Check if at last slide
		var atLastSlide = currentIndex >= slides.length - 1;
		var atFirstSlide = currentIndex === 0;

		// Check for scroll beyond bottom (next page)
		if ( nearBottom && scrollTop > lastScrollTop && atLastSlide ) {
			var footer = document.querySelector( '.site-footer' );
			var footerVisible = true;
			if ( footer ) {
				var footerRect = footer.getBoundingClientRect();
				footerVisible = footerRect.top < window.innerHeight && footerRect.bottom <= window.innerHeight + 8;
			}

			if ( footerVisible ) {
				if ( footerVisibleAt === null ) {
					footerVisibleAt = Date.now();
				}
			} else {
				footerVisibleAt = null;
				scrollAttempts = 0;
			}

			if ( ! footerVisible ) {
				lastScrollTop = scrollTop;
				return;
			}

			if ( ! footerVisibleAt || Date.now() - footerVisibleAt < 1000 ) {
				lastScrollTop = scrollTop;
				return;
			}

			scrollAttempts++;
			clearTimeout( scrollAttemptTimeout );
			scrollAttemptTimeout = setTimeout( function () {
				scrollAttempts = 0;
			}, 1200 );

			if ( scrollAttempts >= 2 ) {
				var nextLink = document.querySelector( '.nav-links .nav-previous a' );
				if ( nextLink ) {
					showLoadingIndicator( 'Loading next page...' );
					window.location.href = nextLink.href;
				}
			}
		}
		// Check for scroll beyond top (previous page)
		else if ( nearTop && scrollTop < lastScrollTop && atFirstSlide ) {
			scrollAttempts++;
			clearTimeout( scrollAttemptTimeout );
			scrollAttemptTimeout = setTimeout( function () {
				scrollAttempts = 0;
			}, 1200 );

			if ( scrollAttempts >= 2 ) {
				var prevLink = document.querySelector( '.nav-links .nav-next a' );
				if ( prevLink ) {
					showLoadingIndicator( 'Loading previous page...' );
					window.location.href = prevLink.href;
				}
			}
		} else {
			scrollAttempts = 0;
		}

		lastScrollTop = scrollTop;
	}

	scrollTarget.addEventListener( 'scroll', handleScroll );
	if ( scrollTarget !== window ) {
		scrollTarget.addEventListener( 'wheel', handleWheel, { passive: false } );
	}
	window.addEventListener( 'wheel', handleWheel, { passive: false } );

	// --- Keyboard navigation ---
	function handleKeydown( e ) {
		if ( isNavigating ) {
			return;
		}

		var target = e.target;
		if ( target && ( target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT' || target.isContentEditable ) ) {
			return;
		}

		var rect = container.getBoundingClientRect();
		if ( rect.bottom < 0 || rect.top > window.innerHeight ) {
			return;
		}

		if ( e.key === 'ArrowDown' || e.key === 'PageDown' ) {
			e.preventDefault();
			if ( currentIndex >= slides.length - 1 ) {
				// At last slide, try to go to next page
				var nextLink = document.querySelector( '.nav-links .nav-previous a' );
				if ( nextLink ) {
					window.location.href = nextLink.href;
				}
			} else {
				scrollToSlide( currentIndex + 1 );
			}
		} else if ( e.key === 'ArrowUp' || e.key === 'PageUp' ) {
			e.preventDefault();
			if ( currentIndex === 0 ) {
				// At first slide, try to go to previous page
				var prevLink = document.querySelector( '.nav-links .nav-next a' );
				if ( prevLink ) {
					window.location.href = prevLink.href;
				}
			} else {
				scrollToSlide( currentIndex - 1 );
			}
		} else if ( e.key === 'Home' ) {
			e.preventDefault();
			scrollToSlide( 0 );
		} else if ( e.key === 'End' ) {
			e.preventDefault();
			scrollToSlide( slides.length - 1 );
		}
	}

	document.addEventListener( 'keydown', handleKeydown );
	if ( scrollTarget !== window ) {
		scrollTarget.addEventListener( 'keydown', handleKeydown );
	}
	container.addEventListener( 'keydown', handleKeydown );

	// --- Preload adjacent slides ---
	function preloadAdjacent( index ) {
		[ -1, 0, 1, 2 ].forEach( function ( offset ) {
			var target = index + offset;
			if ( target < 0 || target >= slides.length ) {
				return;
			}
			var slide = slides[ target ];
			if ( slide.dataset.preloaded ) {
				return;
			}

			// Switch lazy images to eager.
			slide.querySelectorAll( 'img[loading="lazy"]' ).forEach( function ( img ) {
				img.loading = 'eager';
				if ( ! img.complete ) {
					var src = img.src;
					img.src = '';
					img.src = src;
				}
			} );

			// Load deferred iframes.
			slide.querySelectorAll( 'iframe[data-src]' ).forEach( function ( iframe ) {
				iframe.src = iframe.dataset.src;
			} );

			slide.dataset.preloaded = 'true';
		} );
	}

	// Initial preload for first slides.
	preloadAdjacent( 0 );
} );

/**
 * Handle auto-pagination for classic and boxes modes
 */
function handleAutoPagination() {
	var scrollTarget = document.querySelector( '.site-content' );
	if ( ! scrollTarget ) {
		return;
	}

	var scrollAttempts = 0;
	var scrollAttemptTimeout = null;
	var lastScrollTop = scrollTarget.scrollTop;
	var wheelAttempts = 0;
	var wheelTimeout = null;
	var footerVisibleAt = null;

	scrollTarget.addEventListener( 'scroll', function () {
		var scrollTop = scrollTarget.scrollTop;
		var scrollHeight = scrollTarget.scrollHeight;
		var clientHeight = scrollTarget.clientHeight;
		var nearBottom = scrollTop + clientHeight >= scrollHeight - 50;
		var nearTop = scrollTop <= 50;

		// Check for scroll beyond bottom (next page)
		if ( nearBottom && scrollTop > lastScrollTop ) {
			var footer = document.querySelector( '.site-footer' );
			var footerVisible = false;
			if ( footer ) {
				var footerRect = footer.getBoundingClientRect();
				footerVisible = footerRect.top < window.innerHeight;
			}

			if ( footerVisible ) {
				if ( footerVisibleAt === null ) {
					footerVisibleAt = Date.now();
				}
			} else {
				footerVisibleAt = null;
				scrollAttempts = 0;
				lastScrollTop = scrollTop;
				return;
			}

			if ( footerVisibleAt && Date.now() - footerVisibleAt < 1000 ) {
				lastScrollTop = scrollTop;
				return;
			}

			scrollAttempts++;
			clearTimeout( scrollAttemptTimeout );
			scrollAttemptTimeout = setTimeout( function () {
				scrollAttempts = 0;
			}, 1200 );

			if ( scrollAttempts >= 2 ) {
				var nextLink = document.querySelector( '.nav-links .nav-previous a' );
				if ( nextLink ) {
					showLoadingIndicator( 'Loading next page...' );
					window.location.href = nextLink.href;
				}
			}
		}
		// Check for scroll beyond top (previous page)
		else if ( nearTop && scrollTop < lastScrollTop ) {
			scrollAttempts++;
			clearTimeout( scrollAttemptTimeout );
			scrollAttemptTimeout = setTimeout( function () {
				scrollAttempts = 0;
			}, 1200 );

			if ( scrollAttempts >= 2 ) {
				var prevLink = document.querySelector( '.nav-links .nav-next a' );
				if ( prevLink ) {
					showLoadingIndicator( 'Loading previous page...' );
					window.location.href = prevLink.href;
				}
			}
		} else {
			scrollAttempts = 0;
		}

		lastScrollTop = scrollTop;
	} );

	// Wheel detection when at boundaries or when no scroll available
	scrollTarget.addEventListener( 'wheel', function ( e ) {
		var scrollTop = scrollTarget.scrollTop;
		var scrollHeight = scrollTarget.scrollHeight;
		var clientHeight = scrollTarget.clientHeight;
		var hasScroll = scrollHeight > clientHeight + 5;
		var atBottom = scrollTop + clientHeight >= scrollHeight - 10;
		var atTop = scrollTop <= 10;

		// If no scroll available, detect direction from wheel
		if ( ! hasScroll || ( atBottom && e.deltaY > 0 ) || ( atTop && e.deltaY < 0 ) ) {
			// For bottom pagination, check footer visibility timing
			if ( ! hasScroll && e.deltaY > 0 || ( atBottom && e.deltaY > 0 ) ) {
				var footer = document.querySelector( '.site-footer' );
				var footerVisible = false;
				if ( footer ) {
					var footerRect = footer.getBoundingClientRect();
					footerVisible = footerRect.top < window.innerHeight;
				}

				if ( footerVisible ) {
					if ( footerVisibleAt === null ) {
						footerVisibleAt = Date.now();
					}
				} else {
					footerVisibleAt = null;
					wheelAttempts = 0;
					return;
				}

				if ( footerVisibleAt && Date.now() - footerVisibleAt < 1000 ) {
					return;
				}
			}

			wheelAttempts++;
			clearTimeout( wheelTimeout );
			wheelTimeout = setTimeout( function () {
				wheelAttempts = 0;
			}, 1200 );

			if ( wheelAttempts >= 3 ) {
				if ( ! hasScroll && e.deltaY < 0 || ( atTop && e.deltaY < 0 ) ) {
					var prevLink = document.querySelector( '.nav-links .nav-next a' );
					if ( prevLink ) {
						showLoadingIndicator( 'Loading previous page...' );
						window.location.href = prevLink.href;
					}
				} else if ( ! hasScroll && e.deltaY > 0 || ( atBottom && e.deltaY > 0 ) ) {
					var nextLink = document.querySelector( '.nav-links .nav-previous a' );
					if ( nextLink ) {
						showLoadingIndicator( 'Loading next page...' );
						window.location.href = nextLink.href;
					}
				}
			}
		} else {
			wheelAttempts = 0;
		}
	}, { passive: true } );
}
