/**
 * Documentation Viewer JavaScript
 *
 * Handles smooth scrolling to anchor links in documentation pages.
 *
 * @package Card_Oracle/Admin/JS
 * @since   1.2.1
 */

(function( $ ) {
	'use strict';

	$( document ).ready( function() {
		// Only run on documentation viewer pages.
		if ( $( '.co-doc-content' ).length ) {

			// Generate IDs for headings that don't have them (for anchor links).
			$( '.co-doc-content h1, .co-doc-content h2, .co-doc-content h3, .co-doc-content h4, .co-doc-content h5, .co-doc-content h6' ).each( function() {
				const $heading = $( this );
				if ( ! $heading.attr( 'id' ) ) {
					// Generate ID from heading text: lowercase, replace spaces with hyphens, remove special chars.
					const text = $heading.text();
					const id = text
						.toLowerCase()
						.trim()
						.replace( /[^\w\s-]/g, '' ) // Remove special characters
						.replace( /\s+/g, '-' )      // Replace spaces with hyphens
						.replace( /-+/g, '-' );      // Replace multiple hyphens with single
					$heading.attr( 'id', id );
				}
			});

			// Scroll to anchor on page load if hash is present.
			// Use jQuery animate for cross-browser compatibility.
			function scrollToHash() {
				if ( window.location.hash ) {
					const $target = $( window.location.hash );
					if ( $target.length ) {
						$( 'html, body' ).stop().animate({
							scrollTop: $target.offset().top - 100
						}, 500 );
					}
				}
			}

			// Try immediate scroll, and retry after delays for slow-loading content.
			setTimeout( scrollToHash, 100 );
			setTimeout( scrollToHash, 300 );
			setTimeout( scrollToHash, 600 );

			// Smooth scroll for in-page anchor links.
			// Use event delegation to ensure handler works for all links.
			$( document ).on( 'click', '.co-doc-content a[href^="#"]', function( e ) {
				const href = $( this ).attr( 'href' );

				// Only handle non-empty hashes.
				if ( ! href || href === '#' ) {
					return;
				}

				e.preventDefault();

				const $target = $( href );

				if ( $target.length ) {
					// Use jQuery animate for cross-browser compatibility.
					$( 'html, body' ).stop().animate({
						scrollTop: $target.offset().top - 100
					}, 500 );

					// Update URL hash.
					if ( history.pushState ) {
						history.pushState( null, null, href );
					} else {
						window.location.hash = href;
					}
				}
			});
		}
	});

})( jQuery );
