/**
 * Automation Settings component.
 *
 * @package Schema_AI
 */

import { ToggleControl, CheckboxControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

function Automation( { settings, onChange } ) {
	const autoPublish = settings?.enable_auto_apply || false;
	const autoUpdate = settings?.auto_generate_on_update || false;
	const postTypes = settings?.auto_generate_post_types || [ 'post', 'page' ];

	const handleChange = ( key, value ) => {
		onChange( { ...settings, [ key ]: value } );
	};

	const togglePostType = ( type ) => {
		const current = [ ...postTypes ];
		const index = current.indexOf( type );
		if ( index > -1 ) {
			current.splice( index, 1 );
		} else {
			current.push( type );
		}
		handleChange( 'auto_generate_post_types', current );
	};

	return (
		<div className="schema-ai-settings-section">
			<h2>{ __( 'Automation', 'schema-ai' ) }</h2>
			<ToggleControl
				label={ __( 'Auto-generate on publish', 'schema-ai' ) }
				help={ __( 'Automatically generate schema markup when a post is published.', 'schema-ai' ) }
				checked={ autoPublish }
				onChange={ ( v ) => handleChange( 'enable_auto_apply', v ) }
			/>
			<ToggleControl
				label={ __( 'Auto-generate on update', 'schema-ai' ) }
				help={ __( 'Regenerate schema when post content is significantly updated.', 'schema-ai' ) }
				checked={ autoUpdate }
				onChange={ ( v ) => handleChange( 'auto_generate_on_update', v ) }
			/>
			<fieldset>
				<legend>{ __( 'Post Types for Auto-Generation', 'schema-ai' ) }</legend>
				{ [ 'post', 'page', 'product' ].map( ( type ) => (
					<CheckboxControl key={ type } label={ type.charAt( 0 ).toUpperCase() + type.slice( 1 ) } checked={ postTypes.includes( type ) } onChange={ () => togglePostType( type ) } />
				) ) }
			</fieldset>
		</div>
	);
}

export default Automation;
