/* global document */
( function () {
	'use strict';

	var search = document.getElementById( 'kramar-module-search' );
	if ( ! search ) { return; }

	/* Empty-state message — inserted once, toggled by the search handler. */
	var content = document.querySelector( '.kramar-modules-content' );
	var emptyMsg = null;
	if ( content ) {
		emptyMsg = document.createElement( 'p' );
		emptyMsg.className = 'kramar-modules-empty';
		emptyMsg.style.cssText = 'display:none;text-align:center;padding:40px 20px;color:#787c82;font-size:14px;';
		emptyMsg.textContent = 'No modules match your search.';
		content.appendChild( emptyMsg );
	}

	search.addEventListener( 'input', function () {
		var q = this.value.toLowerCase().trim();
		var totalVisible = 0;

		document.querySelectorAll( '.kramar-module' ).forEach( function ( card ) {
			if ( ! q ) { card.style.display = ''; totalVisible++; return; }
			var text =
				( card.querySelector( '.kramar-module__name' )
					? card.querySelector( '.kramar-module__name' ).textContent
					: '' ) +
				' ' +
				( card.querySelector( '.kramar-module__description' )
					? card.querySelector( '.kramar-module__description' ).textContent
					: '' );
			var match = text.toLowerCase().includes( q );
			card.style.display = match ? '' : 'none';
			if ( match ) { totalVisible++; }
		} );
		document.querySelectorAll( '.kramar-modules-section' ).forEach( function ( sec ) {
			var visible = sec.querySelectorAll( '.kramar-module:not([style*="display: none"])' ).length;
			sec.style.display = ( ! q || visible > 0 ) ? '' : 'none';
		} );

		if ( emptyMsg ) {
			emptyMsg.style.display = ( q && totalVisible === 0 ) ? '' : 'none';
		}
	} );

	// Smooth scroll for nav links.
	document.querySelectorAll( '.kramar-modules-nav__link' ).forEach( function ( link ) {
		link.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			var target = document.querySelector( this.getAttribute( 'href' ) );
			if ( target ) { target.scrollIntoView( { behavior: 'smooth', block: 'start' } ); }
		} );
	} );
} )();
