/**
 * Field Mapper - maps content fields to schema properties.
 *
 * @package Schema_AI
 */

import { useState } from '@wordpress/element';
import { SelectControl, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

const SOURCE_OPTIONS = [
	{ label: __( 'Auto', 'schema-ai' ), value: 'auto' },
	{ label: __( 'Post Title', 'schema-ai' ), value: 'post_title' },
	{ label: __( 'Post Content', 'schema-ai' ), value: 'post_content' },
	{ label: __( 'Post Excerpt', 'schema-ai' ), value: 'post_excerpt' },
	{ label: __( 'Featured Image', 'schema-ai' ), value: 'featured_image' },
	{ label: __( 'Custom Field', 'schema-ai' ), value: 'custom_field' },
	{ label: __( 'Manual', 'schema-ai' ), value: 'manual' },
];

function FieldMapper( { schemaType, fields, onMappingChange } ) {
	const [ mapping, setMapping ] = useState( {} );

	const handleChange = ( fieldKey, source ) => {
		const updated = { ...mapping, [ fieldKey ]: source };
		setMapping( updated );
		if ( onMappingChange ) onMappingChange( updated );
	};

	const schemaFields = fields || [];

	return (
		<div className="schema-ai-field-mapper">
			<h3>{ __( 'Field Mapping', 'schema-ai' ) }</h3>
			<p>{ __( 'Map your content fields to schema properties.', 'schema-ai' ) }</p>
			<table className="widefat">
				<thead>
					<tr>
						<th>{ __( 'Schema Field', 'schema-ai' ) }</th>
						<th>{ __( 'Source', 'schema-ai' ) }</th>
					</tr>
				</thead>
				<tbody>
					{ schemaFields.map( ( field ) => (
						<tr key={ field.key }>
							<td>
								{ field.label }
								{ field.required && <span className="schema-ai-required">*</span> }
							</td>
							<td>
								<SelectControl
									value={ mapping[ field.key ] || 'auto' }
									options={ SOURCE_OPTIONS }
									onChange={ ( v ) => handleChange( field.key, v ) }
								/>
							</td>
						</tr>
					) ) }
				</tbody>
			</table>
			<Button variant="primary" onClick={ () => onMappingChange && onMappingChange( mapping ) }>
				{ __( 'Save Mapping', 'schema-ai' ) }
			</Button>
		</div>
	);
}

export default FieldMapper;
