'use client';

import * as Sentry from '@sentry/nextjs';
import { Component, ReactNode } from 'react';

type Props = {
  children: ReactNode;
};

type State = {
  hasError: boolean;
};

export default class AppErrorBoundary extends Component<Props, State> {
  state: State = {
    hasError: false,
  };

  static getDerivedStateFromError(): State {
    return { hasError: true };
  }

  componentDidCatch(error: Error) {
    Sentry.captureException(error);
  }

  private handleRetry = () => {
    this.setState({ hasError: false });
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center px-4">
          <div className="max-w-md w-full rounded-2xl border border-text-secondary/15 bg-bg-secondary/70 p-6 text-center">
            <h2 className="text-xl font-semibold text-text-primary mb-2">Что-то пошло не так</h2>
            <p className="text-text-secondary mb-5">Ошибка уже отправлена в систему мониторинга.</p>
            <button
              type="button"
              onClick={this.handleRetry}
              className="btn-primary w-full"
            >
              Перезагрузить страницу
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
