import { StrictMode, Component, type ErrorInfo, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import 'folds/dist/style.css';
import { configClass, varsClass } from 'folds';
import { App } from './App';
import './styles.css';

document.body.classList.add(configClass, varsClass);

// Playground shares the Cinny origin — drop any SW/caches so stale shims cannot stick.
if ('serviceWorker' in navigator) {
  void navigator.serviceWorker.getRegistrations().then((regs) => {
    for (const reg of regs) void reg.unregister();
  });
}
if (typeof caches !== 'undefined') {
  void caches.keys().then((keys) => Promise.all(keys.map((k) => caches.delete(k))));
}

class BootErrorBoundary extends Component<{ children: ReactNode }, { error: string | null }> {
  state = { error: null as string | null };

  static getDerivedStateFromError(error: Error) {
    return { error: error.message };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('[playground boot]', error, info);
  }

  render() {
    if (this.state.error) {
      return (
        <pre style={{ padding: 24, color: '#ffb4b4', whiteSpace: 'pre-wrap' }}>
          {this.state.error}
        </pre>
      );
    }
    return this.props.children;
  }
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <BootErrorBoundary>
      <App />
    </BootErrorBoundary>
  </StrictMode>
);
