"use client";

import { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
}

export default class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false,
  };

  public static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // Ignore browser extension errors
    if (error.message?.includes('tron') || 
        error.message?.includes('chrome-extension') ||
        error.stack?.includes('chrome-extension')) {
      console.warn('Browser extension error ignored:', error.message);
      // Reset error state to continue rendering
      this.setState({ hasError: false });
      return;
    }
    
    console.error("Uncaught error:", error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      // Check if it's an extension error
      if (this.state.error?.message?.includes('tron') ||
          this.state.error?.stack?.includes('chrome-extension')) {
        // Silently recover and render children
        return this.props.children;
      }
      
      return (
        <div className="min-h-screen flex items-center justify-center p-4">
          <div className="text-center">
            <h2 className="text-2xl font-serif mb-4">Something went wrong</h2>
            <button
              onClick={() => this.setState({ hasError: false })}
              className="px-6 py-3 bg-foreground text-white"
            >
              Try again
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
