/* global mbsBisacData */
/**
 * assets/js/adminjs/mbs-admin-bisac.js
 *
 * BISAC subject code search-ahead (AJAX from mbs_classification_codes DB),
 * chip UI, and age/grade range conditional display for the Categorization
 * metabox BISAC tab.
 *
 * Reads mbsBisacData.ajaxUrl (string: admin-ajax.php URL)
 *       mbsBisacData.nonce   (string: mbs_classification_nonce value)
 *       mbsBisacData.isFree  (bool:   true = FREE tier, max 1 code)
 *
 * @package My_Book_Showroom
 * @since   1.1.0
 */
( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {

		var searchInput = document.getElementById( 'mbs-cat-bisac-search' );
		var chipWrap    = document.getElementById( 'mbs-cat-bisac-chips' );
		var resultsList = document.getElementById( 'mbs-cat-bisac-results' );
		var ageWrap     = document.getElementById( 'mbs-cat-bisac-age-wrap' );

		if ( ! searchInput || ! chipWrap || ! resultsList ) {
			return;
		}

		var AJAX_URL      = ( mbsBisacData && mbsBisacData.ajaxUrl ) ? mbsBisacData.ajaxUrl : '';
		var NONCE         = ( mbsBisacData && mbsBisacData.nonce   ) ? mbsBisacData.nonce   : '';
		var isFree        = ( mbsBisacData && mbsBisacData.isFree  ) ? mbsBisacData.isFree  : false;
		var debounceTimer = null;
		var requestId     = 0;

		/** Return array of currently selected code strings. */
		function getSelected() {
			var selected = [];
			chipWrap.querySelectorAll( '.mbs-bisac-chip' ).forEach( function ( chip ) {
				selected.push( chip.dataset.code );
			} );
			return selected;
		}

		/** Update age/grade range visibility based on whether any JUV/JNF code is selected. */
		function updateAgeWrap() {
			if ( ! ageWrap ) { return; }
			var selected = getSelected();
			var hasJuv = selected.some( function ( c ) {
				return c.indexOf( 'JUV' ) === 0 || c.indexOf( 'JNF' ) === 0;
			} );
			ageWrap.style.display = hasJuv ? '' : 'none';
		}

		/** Add a chip for the given code + label. */
		function addChip( code, label ) {
			var selected = getSelected();
			if ( selected.indexOf( code ) >= 0 ) { return; }
			if ( isFree && selected.length >= 1 ) { return; }

			var chip = document.createElement( 'span' );
			chip.className    = 'mbs-bisac-chip';
			chip.dataset.code = code;

			var hidden = document.createElement( 'input' );
			hidden.type  = 'hidden';
			hidden.name  = 'mbs_bisac_codes[]';
			hidden.value = code;

			var lbl = document.createElement( 'span' );
			lbl.className   = 'mbs-bisac-chip-label';
			lbl.textContent = code + ' \u2014 ' + label;

			var btn = document.createElement( 'button' );
			btn.type      = 'button';
			btn.className = 'mbs-bisac-chip-remove';
			btn.setAttribute( 'aria-label', 'Remove' );
			btn.textContent = '\u00d7';
			btn.addEventListener( 'click', function () {
				chip.remove();
				updateAgeWrap();
			} );

			chip.appendChild( hidden );
			chip.appendChild( lbl );
			chip.appendChild( btn );
			chipWrap.appendChild( chip );
			updateAgeWrap();
		}

		/** Render items returned by the AJAX search. */
		function renderResultItems( items ) {
			resultsList.innerHTML = '';
			var selected = getSelected();
			var visible  = items.filter( function ( item ) {
				return selected.indexOf( item.code ) < 0;
			} ).slice( 0, 30 );

			if ( visible.length === 0 ) {
				resultsList.style.display = 'none';
				return;
			}
			visible.forEach( function ( item ) {
				var li = document.createElement( 'li' );
				li.className     = 'mbs-bisac-result-item';
				li.textContent   = item.code + ' \u2014 ' + item.description;
				li.dataset.code  = item.code;
				li.dataset.label = item.description;
				li.addEventListener( 'click', function () {
					addChip( item.code, item.description );
					searchInput.value         = '';
					resultsList.style.display = 'none';
					resultsList.innerHTML     = '';
				} );
				resultsList.appendChild( li );
			} );
			resultsList.style.display = 'block';
		}

		/**
		 * Fetch BISAC search results from mbs_classify_search (AJAX).
		 * Debounced 250 ms; stale responses discarded via requestId.
		 */
		function fetchResults( query ) {
			resultsList.innerHTML = '';
			if ( query.length < 2 ) {
				resultsList.style.display = 'none';
				return;
			}

			clearTimeout( debounceTimer );
			var myId = ++requestId;

			debounceTimer = setTimeout( function () {
				var body = new URLSearchParams( {
					action : 'mbs_classify_search',
					nonce  : NONCE,
					scheme : 'bisac',
					query  : query,
				} );
				fetch( AJAX_URL, { method: 'POST', body: body } )
					.then( function ( r ) { return r.json(); } )
					.then( function ( json ) {
						if ( myId !== requestId ) { return; }
						if ( json.success && Array.isArray( json.data ) ) {
							renderResultItems( json.data );
						}
					} )
					.catch( function () {
						if ( myId === requestId ) {
							resultsList.style.display = 'none';
						}
					} );
			}, 250 );
		}

		searchInput.addEventListener( 'input', function () {
			fetchResults( this.value.trim() );
		} );

		searchInput.addEventListener( 'keydown', function ( e ) {
			if ( e.key === 'Escape' ) {
				resultsList.style.display = 'none';
				resultsList.innerHTML     = '';
			}
		} );

		document.addEventListener( 'click', function ( e ) {
			if ( ! resultsList.contains( e.target ) && e.target !== searchInput ) {
				resultsList.style.display = 'none';
			}
		} );

		// Chip remove — delegated for server-rendered chips.
		chipWrap.addEventListener( 'click', function ( e ) {
			var btn = e.target.closest( '.mbs-bisac-chip-remove' );
			if ( btn ) {
				btn.closest( '.mbs-bisac-chip' ).remove();
				updateAgeWrap();
			}
		} );

		// Inline styles (keeps asset footprint small).
		var style = document.createElement( 'style' );
		style.textContent = (
			'.mbs-bisac-search-wrap { margin-bottom:6px; }' +
			'.mbs-bisac-search { width:100%; box-sizing:border-box; }' +
			'.mbs-bisac-results { list-style:none; margin:0; padding:0; border:1px solid #ddd;' +
			'  max-height:150px; overflow-y:auto; background:#fff; z-index:9999; position:relative; }' +
			'.mbs-bisac-result-item { padding:5px 8px; font-size:12px; cursor:pointer; }' +
			'.mbs-bisac-result-item:hover { background:#f0f0f0; }' +
			'.mbs-bisac-chips { display:flex; flex-wrap:wrap; gap:4px; margin-bottom:6px; min-height:10px; }' +
			'.mbs-bisac-chip { display:flex; align-items:center; gap:4px; background:#e0ecff; border-radius:3px;' +
			'  padding:2px 6px; font-size:12px; }' +
			'.mbs-bisac-chip-remove { background:none; border:none; cursor:pointer; color:#666;' +
			'  font-size:14px; padding:0 2px; line-height:1; }' +
			'.mbs-bisac-chip-remove:hover { color:#d00; }' +
			'.mbs-bisac-tier-note { color:#888; font-size:11px; font-style:italic; margin:4px 0; }' +
			'.mbs-bisac-age-wrap { margin-top:6px; }'
		);
		document.head.appendChild( style );

		// Initialize age-wrap visibility from already-selected chips.
		updateAgeWrap();

	} );
} )();
