import { useEffect, createPortal } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/** Close icon — matches the line-icon set used across the gift wrap UI. */
function CloseIcon() {
	return (
		<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
			<path fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" d="M6 6l12 12M18 6 6 18" />
		</svg>
	);
}

/**
 * A small, self-contained modal dialog — no `@wordpress/components`
 * dependency. Portals to `document.body`, closes on Escape or an overlay
 * click, and locks page scroll while open. The close control is an
 * `<a role="button">` (see .rtgw-modal-close) rather than the
 * `components-button is-compact has-icon` markup `@wordpress/components`
 * would render, so every clickable control in the gift wrap UI shares one
 * semantic and one visual language.
 */
export default function RtgwModal( { title, onRequestClose, className = '', style, children } ) {
	useEffect( () => {
		const onKeyDown = ( e ) => {
			if ( e.key === 'Escape' ) {
				onRequestClose();
			}
		};
		document.addEventListener( 'keydown', onKeyDown );

		const prevOverflow = document.body.style.overflow;
		document.body.style.overflow = 'hidden';

		return () => {
			document.removeEventListener( 'keydown', onKeyDown );
			document.body.style.overflow = prevOverflow;
		};
	}, [ onRequestClose ] );

	return createPortal(
		<div className="rtgw-modal-overlay" onMouseDown={ ( e ) => {
			if ( e.target === e.currentTarget ) {
				onRequestClose();
			}
		} }>
			<div className={ `rtgw-modal-frame ${ className }`.trim() } style={ style } role="dialog" aria-modal="true" aria-label={ title }>
				<div className="rtgw-modal-header">
					<h2 className="rtgw-modal-title">{ title }</h2>
					<a
						href="#rtgw-modal-close"
						role="button"
						className="rtgw-modal-close"
						aria-label={ __( 'Close', 'rt-gift-wrap-for-woocommerce' ) }
						onClick={ ( e ) => {
							e.preventDefault();
							onRequestClose();
						} }
					>
						<CloseIcon />
					</a>
				</div>
				<div className="rtgw-modal-content">
					{ children }
				</div>
			</div>
		</div>,
		document.body
	);
}
