import { useState, useCallback } from 'react';

export const useErrorBoundary = () => {
  const [error, setError] = useState(null);

  const handleError = useCallback((error) => {
    console.error('Context Error:', error);
    setError(error);
  }, []);

  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    error,
    handleError,
    clearError,
    hasError: error !== null
  };
};

export const withErrorBoundary = (WrappedComponent) => {
  return function WithErrorBoundary(props) {
    const { error, handleError, clearError, hasError } = useErrorBoundary();

    if (hasError) {
      return (
        <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
          <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
            <h2 className="text-xl font-bold mb-2">Произошла ошибка</h2>
            <p>{error?.message || 'Неизвестная ошибка'}</p>
            <button
              onClick={clearError}
              className="mt-4 px-4 py-2 bg-campfire-amber text-campfire-dark rounded-lg hover:bg-campfire-amber/80 transition-colors"
            >
              Попробовать снова
            </button>
          </div>
        </div>
      );
    }

    return (
      <WrappedComponent
        {...props}
        error={error}
        handleError={handleError}
        clearError={clearError}
      />
    );
  };
}; 