/**
 * Use this file for JavaScript code that you want to run in the front-end
 * on posts/pages that contain this block.
 */

document.addEventListener( 'DOMContentLoaded', function() {
	const timeline = document.querySelector( '.wp-block-telex-company-timeline' );
	
	if ( ! timeline ) {
		return;
	}

	const sidebar = timeline.querySelector( '.timeline-sidebar' );
	const yearLinks = timeline.querySelectorAll( '.year-link' );
	const entries = timeline.querySelectorAll( '.timeline-entry' );

	if ( ! sidebar || yearLinks.length === 0 || entries.length === 0 ) {
		return;
	}

	// Smooth scroll to year when clicking sidebar link
	yearLinks.forEach( link => {
		link.addEventListener( 'click', function( e ) {
			e.preventDefault();
			const year = this.getAttribute( 'data-year' ) || this.getAttribute( 'href' ).replace( '#year-', '' );
			const targetEntry = timeline.querySelector( `[data-year="${ year }"]` );
			
			if ( targetEntry ) {
				targetEntry.scrollIntoView( { 
					behavior: 'smooth',
					block: 'start'
				} );
			}
		} );
	} );

	// Update active year on scroll
	const observerOptions = {
		root: null,
		rootMargin: '-20% 0px -70% 0px',
		threshold: 0
	};

	const observerCallback = ( entries ) => {
		entries.forEach( entry => {
			if ( entry.isIntersecting ) {
				const year = entry.target.getAttribute( 'data-year' );
				
				// Remove active class from all links
				yearLinks.forEach( link => link.classList.remove( 'active' ) );
				
				// Add active class to current year
				const activeLink = timeline.querySelector( `.year-link[data-year="${ year }"]` );
				if ( activeLink ) {
					activeLink.classList.add( 'active' );
				}
			}
		} );
	};

	const observer = new IntersectionObserver( observerCallback, observerOptions );

	// Observe all timeline entries
	entries.forEach( entry => {
		observer.observe( entry );
	} );
} );
