import { Component, type ReactNode } from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';

// Not wrapped in React.StrictMode: the app's load/seed/save-migration effect in
// App.tsx is not idempotent-safe against StrictMode's dev-only double-invoke.

const rootEl = document.getElementById('root')!;

const showFatalError = (err: unknown, hint: string) => {
  rootEl.innerHTML = `
    <div style="max-width:480px;margin:15vh auto;padding:24px;font-family:sans-serif;color:#4A4670;background:#FDFBF7;border-radius:16px;box-shadow:0 2px 10px rgba(74,70,112,0.15);">
      <h1 style="font-size:18px;margin:0 0 8px;">Concordia hit an error</h1>
      <p style="font-size:14px;color:#6B6478;margin:0 0 12px;word-break:break-word;">${String(err && (err as any).message ? (err as any).message : err)}</p>
      <p style="font-size:12px;color:#6B6478;margin:0;">${hint}</p>
    </div>
  `;
  console.error('App error:', err);
};

// Catches render-time crashes anywhere in the tree *after* the app has
// mounted, so a broken component shows this same friendly card instead of a
// blank page — without tearing down the rest of a working session, which a
// blanket window 'error'/'unhandledrejection' listener used to do here for
// *any* uncaught error anywhere (a flaky network call, even a harmless
// browser quirk like a ResizeObserver warning), wiping out whatever the
// user was doing and always blaming missing Supabase env vars regardless
// of the real cause. Startup failures (below) are the one case where that
// guess is actually likely correct, since they happen before anything's
// had a chance to render at all.
class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean }> {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(err: unknown) {
    console.error('App error:', err);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ maxWidth: 480, margin: '15vh auto', padding: 24, fontFamily: 'sans-serif', color: '#4A4670', background: '#FDFBF7', borderRadius: 16, boxShadow: '0 2px 10px rgba(74,70,112,0.15)' }}>
          <h1 style={{ fontSize: 18, margin: '0 0 8px' }}>Concordia hit an error</h1>
          <p style={{ fontSize: 14, color: '#6B6478', margin: 0 }}>
            Something went wrong loading part of the app. Try reloading the page.
          </p>
        </div>
      );
    }
    return this.props.children;
  }
}

// AuthGate is loaded dynamically (rather than a static top-level import) so
// that a startup failure — most likely lib/supabase/client.ts throwing
// because VITE_SUPABASE_URL/VITE_SUPABASE_ANON_KEY are missing at build
// time — surfaces as a visible message instead of a silent blank page. A
// static import throwing during module evaluation happens before any of
// this file's own code runs, so a plain try/catch here couldn't catch it;
// a rejected dynamic import can.
import('./AuthGate')
  .then(({ default: AuthGate }) => {
    ReactDOM.createRoot(rootEl).render(
      <ErrorBoundary>
        <AuthGate />
      </ErrorBoundary>
    );
  })
  .catch((err) => showFatalError(err, "This usually means VITE_SUPABASE_URL / VITE_SUPABASE_ANON_KEY weren't set when this site was built."));
