/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable jsx-a11y/anchor-has-content */

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

export const PremiumModal = ( { modalData, closeModal } ) => {
	const { open, title, upgradeUrl, id, previewImage } = modalData;
	const modalRef = useRef( null );

	useEffect( () => {
		const handleClickOutside = ( event ) => {
			if (
				modalRef.current &&
				! modalRef.current.contains( event.target )
			) {
				closeModal();
			}
		};

		const handleEscKey = ( event ) => {
			if ( event.key === 'Escape' ) {
				closeModal();
			}
		};

		if ( open ) {
			document.addEventListener( 'mousedown', handleClickOutside );
			document.addEventListener( 'keydown', handleEscKey );
		}

		// Cleanup listener when component unmounts or modal closes
		return () => {
			document.removeEventListener( 'mousedown', handleClickOutside );
			document.removeEventListener( 'keydown', handleEscKey );
		};
	}, [ open, closeModal ] );

	if ( open ) {
		return (
			<section className="tasty-framework-modal tasty-open" id={ id }>
				<div
					className="tasty-framework-modal-container"
					ref={ modalRef }
				>
					<a
						href="#"
						className="tasty-hide-modal tasty-framework-close-modal tasty-framework-modal-x"
						onClick={ closeModal }
					></a>
					<div className="tasty-framework-modal-header">
						<h2>{ title }</h2>
					</div>

					{ previewImage && (
						<div className="tasty-framework-modal-preview">
							<img src={ previewImage } alt={ title } />
						</div>
					) }

					<div className="tasty-framework-modal-body">
						{ __(
							'This is a premium feature. Consider upgrading to a paid plan to get this and more great features.',
							'tasty'
						) }

						<div className="tasty-framework-spacer"></div>

						<a
							href={ upgradeUrl }
							target="_blank"
							rel="noopener noreferrer"
							className="tasty-button tasty-button-pink tasty-button-large tasty-button-full"
						>
							{ __( 'Upgrade Now', 'tasty' ) }
						</a>
					</div>
				</div>
			</section>
		);
	}

	return null;
};
