"use client";

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

/* Last-resort guard around risky widgets (e.g. the camera scanner): a
   library throwing from an effect cleanup otherwise whitescreens the whole
   Next.js app. Renders a friendly inline error with a Retry instead. */

interface Props {
  children: ReactNode;
  message: string;
  retryLabel: string;
}

interface State {
  error: unknown;
}

export default class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: unknown): State {
    return { error };
  }

  render() {
    if (this.state.error !== null) {
      return (
        <div className="alert alert-danger mb-0" role="alert">
          <b>{this.props.message}</b>
          <p className="ems-fs-12 mb-2 mt-1 text-muted">
            {String(this.state.error instanceof Error ? this.state.error.message : this.state.error)}
          </p>
          <button
            type="button"
            className="btn btn-sm btn-primary"
            onClick={() => this.setState({ error: null })}
          >
            {this.props.retryLabel}
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
