import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

interface ErrorBoundaryState {
  error: Error | null;
}

class AppErrorBoundary extends React.Component<
  { children: React.ReactNode },
  ErrorBoundaryState
> {
  state: ErrorBoundaryState = { error: null };

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { error };
  }

  handleReset = () => {
    try {
      window.localStorage.removeItem('pdm_player_avatar_v4');
      window.localStorage.removeItem('pdm_player_note_v4');
    } catch {
      // ignore storage errors
    }
    window.location.reload();
  };

  render() {
    if (this.state.error) {
      return (
        <div className="min-h-screen bg-[#090B10] text-[#E6E9F0] flex items-center justify-center p-6">
          <div className="max-w-md w-full bg-[#101520] border border-white/15 rounded-2xl p-6 space-y-4">
            <h1 className="font-display text-xl font-semibold text-white">
              Something glitched behind the glass
            </h1>
            <p className="text-sm text-slate-300 leading-relaxed">
              The studio hit a client error while loading. Resetting local session state usually
              fixes it immediately.
            </p>
            <p className="text-xs font-mono text-rose-300 bg-[#090B10] border border-white/10 rounded-lg p-3 break-words">
              {this.state.error.message}
            </p>
            <button
              type="button"
              onClick={this.handleReset}
              className="w-full py-3 px-4 rounded-xl bg-emerald-500 hover:bg-emerald-400 text-slate-950 text-sm font-semibold cursor-pointer"
            >
              Reset &amp; Reload Studio
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

const rootEl = document.getElementById('root');
if (rootEl) {
  createRoot(rootEl).render(
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  );
}
