import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import ErrorImage from '../src/Images/Error.png'; // Adjust if path differs

const subDirectory = import.meta.env.BASE_URL;

const GlobalErrorHandler = ({ children }) => {
  const navigate = useNavigate();
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    const handleError = (event) => {
      const error = event?.reason || event?.message;

      // Skip known harmless errors (like cancellation or validation)
      if (
        error?.errorFields ||
        error?.name === 'CanceledError' || // Axios cancel error
        error?.message?.includes('canceled') || // string version
        error?.message?.includes('Request failed with status code 499') || // some systems use this
        error?.message?.includes('Network request cancelled') ||
        (typeof error === 'string' &&
          (error.includes('validation') ||
            error.includes('canceled') ||
            error.includes('aborted')))
      ) {
        return;
      }

      console.error('Global Error:', error);
      setHasError(true);
    };

    window.onerror = handleError;
    window.onunhandledrejection = handleError;

    return () => {
      window.onerror = null;
      window.onunhandledrejection = null;
    };
  }, []);

  const goHome = () => {
    setHasError(false); // ✅ Reset error so we can see the app again
    navigate(`${subDirectory}app-page/home`);
  };

  if (hasError) {
    return (
      <div style={styles.container}>
        <img src={ErrorImage} alt="Error occurred" style={styles.image} />
        <h1 style={styles.heading}>Oops! Something went wrong.</h1>
        <p style={styles.message}>
          An unexpected error occurred. Please try again later or{' '}
          <span onClick={goHome} style={styles.link}>
            Home
          </span>
          .
        </p>
      </div>
    );
  }

  return children;
};

const styles = {
  container: {
    textAlign: 'center',
    padding: '50px',
    fontFamily: 'Arial, sans-serif',
  },
  image: {
    width: '150px',
    maxWidth: '90%',
    marginBottom: '30px',
  },
  heading: {
    fontSize: '2rem',
    color: '#333',
  },
  message: {
    fontSize: '1rem',
    color: '#666',
  },
  link: {
    color: '#1292ee',
    textDecoration: 'underline',
    cursor: 'pointer',
  },
};

export default GlobalErrorHandler;
