'use client';

import React, { Component, ReactNode } from "react";
import { logErrorToBackend } from "@/lib/logger";

interface Props {
  children?: ReactNode;
  fallback?: ReactNode;
  userId?: string;
}

interface State {
  hasError: boolean;
}

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

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

  public componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    const route = typeof window !== "undefined" ? window.location.pathname : "unknown";
    logErrorToBackend(error, route, this.props.userId);
  }

  public render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <div style={{ padding: "20px", textAlign: "center", color: "red" }}>
          <h2>Something went wrong.</h2>
          <p>We have been notified and are looking into it.</p>
        </div>
      );
    }
    return this.props.children;
  }
}
 