/**
 * StaticTokenSelect — a token (chip) multi-select over a fixed {value,label} list.
 *
 * Same look & feel as the async product/variation pickers (FormTokenField), but
 * the options are a known, localized list (subscription statuses, user roles) so
 * there is no REST round-trip. The attribute stores slugs; the field works in
 * label space and maps back. Free-typed text that isn't a known option is
 * rejected, and suggestions expand on focus (no need to type first).
 */
import { useMemo } from '@wordpress/element';
import { FormTokenField } from '@wordpress/components';

export default function StaticTokenSelect( { label, options = [], values = [], onChange } ) {
	const valueToLabel = useMemo( () => {
		const out = {};
		options.forEach( ( o ) => {
			out[ String( o.value ) ] = o.label;
		} );
		return out;
	}, [ options ] );

	const labelToValue = useMemo( () => {
		const out = {};
		options.forEach( ( o ) => {
			out[ o.label ] = String( o.value );
		} );
		return out;
	}, [ options ] );

	// Stored slugs -> visible labels (fall back to the raw slug if unknown).
	const tokens = useMemo(
		() => values.map( ( v ) => valueToLabel[ String( v ) ] || String( v ) ),
		[ values, valueToLabel ]
	);

	const suggestions = useMemo( () => options.map( ( o ) => o.label ), [ options ] );

	const handleChange = ( selected ) => {
		const next = selected
			.map( ( token ) => {
				const raw = token && typeof token === 'object' ? token.value : token;
				return labelToValue[ raw ] !== undefined ? labelToValue[ raw ] : raw;
			} )
			// Keep only known option values (drops any stray free text).
			.filter( ( v ) => valueToLabel[ String( v ) ] !== undefined );

		onChange( [ ...new Set( next ) ] );
	};

	return (
		<FormTokenField
			__next40pxDefaultSize
			__experimentalExpandOnFocus
			__experimentalShowHowTo={ false }
			__experimentalValidateInput={ ( input ) =>
				labelToValue[ input ] !== undefined
			}
			label={ label }
			value={ tokens }
			suggestions={ suggestions }
			onChange={ handleChange }
		/>
	);
}
