const React = require("react");
const { ScreenErrorBoundary } = require("../common");
const { enhanceError, logError } = require("../../utils/errorHandler");

/**
 * Higher-order component that wraps screens with error boundaries
 * Requirements: 4.5, 16.1
 */
function withErrorBoundary(
	WrappedComponent,
	screenName,
	screenSpecificTips = []
) {
	const WrappedScreenComponent = (props) => {
		const handleError = (error, errorInfo) => {
			// Log the error with screen context
			logError(error, {
				screen: screenName,
				errorInfo,
				props: Object.keys(props),
			});
		};

		const handleRetry = (retryCount) => {
			console.info(`Retrying ${screenName}, attempt ${retryCount}`);
		};

		const handleReset = () => {
			console.info(`Resetting ${screenName} after error`);
		};

		const handleExit = () => {
			// Navigate back to main menu
			if (props.navigateBack) {
				props.navigateBack();
			} else if (props.onExit) {
				props.onExit();
			}
		};

		return React.createElement(
			ScreenErrorBoundary,
			{
				screenName,
				screenSpecificTips,
				onError: handleError,
				onRetry: handleRetry,
				onReset: handleReset,
				onExit: handleExit,
				maxRetries: 3,
			},
			React.createElement(WrappedComponent, props)
		);
	};

	// Set display name for debugging
	WrappedScreenComponent.displayName = `withErrorBoundary(${screenName})`;

	return WrappedScreenComponent;
}

module.exports = withErrorBoundary;
