import { Component, type ErrorInfo, type ReactNode } from 'react';

interface Props {
	children: ReactNode;
}

interface State {
	hasError: boolean;
}

/**
 * Catches render-time errors thrown inside the editor island and shows a
 * recovery message instead of letting the throw blank the whole `client:only`
 * island. Restores the fallback the previous `@automattic/isolated-block-editor`
 * rendered via its `onError` prop, which the direct `@wordpress/block-editor`
 * composition no longer provides (Decision 0021).
 */
export default class EditorErrorBoundary extends Component< Props, State > {
	state: State = { hasError: false };

	static getDerivedStateFromError(): State {
		return { hasError: true };
	}

	componentDidCatch( error: Error, info: ErrorInfo ): void {
		// Surface the failure for debugging; the UI already shows the fallback.
		// eslint-disable-next-line no-console
		console.error( 'SkyEditor crashed:', error, info );
	}

	render(): ReactNode {
		if ( this.state.hasError ) {
			return (
				<p role="alert" className="skypress-editor__error">
					The editor hit an error. Reload to try again.
				</p>
			);
		}
		return this.props.children;
	}
}
