import { useState } from '@wordpress/element';
import GiftWrapFields from '../shared/components/GiftWrapFields';

function triggerCheckoutUpdate() {
	if ( window.jQuery ) {
		window.jQuery( document.body ).trigger( 'update_checkout' );
	}
}

/**
 * Classic-checkout wiring around the shared GiftWrapFields UI: owns state
 * and mirrors it into hidden form fields (`rtgw_gift_wrap`,
 * `rtgw_gift_wrap_style`, `rtgw_gift_message`) using the same field names
 * the classic controller's $_POST handling already expects, then triggers
 * WooCommerce's `update_checkout` so the fee recalculates live — same UI,
 * same classnames/styling as the block checkout (see
 * src/shared/components/GiftWrapFields.jsx), only the persistence method
 * differs.
 */
export default function GiftWrapBox( { settings } ) {
	const [ isOpen, setIsOpen ] = useState( false );
	const [ styleIndex, setStyleIndex ] = useState( '0' );
	const [ message, setMessage ] = useState( '' );

	if ( ! settings ) {
		return null;
	}

	return (
		<div className="rtgw-classic-box">
			<GiftWrapFields
				settings={ settings }
				layout={ settings.layout || 'popup' }
				isOpen={ isOpen }
				styleIndex={ styleIndex }
				message={ message }
				onConfirm={ ( { styleIndex: nextStyle, message: nextMessage } ) => {
					setIsOpen( true );
					setStyleIndex( nextStyle );
					setMessage( nextMessage );
					triggerCheckoutUpdate();
				} }
				onRemove={ () => {
					setIsOpen( false );
					triggerCheckoutUpdate();
				} }
			/>

			{ /* Hidden classic-checkout fields — same names the PHP $_POST handling already expects. */ }
			<input type="checkbox" name="rtgw_gift_wrap" value="1" checked={ isOpen } readOnly hidden />
			<input type="hidden" name="rtgw_gift_wrap_style" value={ styleIndex } />
			{ settings.allow_message && <input type="hidden" name="rtgw_gift_message" value={ message } /> }
		</div>
	);
}
