import React, { lazy, Suspense } from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Route, Routes } from "react-router-dom";
// CheckoutPage is static — it's the critical path, no lazy loading gap
import CheckoutPage from "./pages/CheckoutPage";
// Everything else lazy loaded
const EmbedKachyngNext = lazy(() => import("./pages/EmbedKachyngNext"));
const EmbedKachyng = lazy(() => import("./pages/EmbedKachyng"));
// Dev and component-test pages exist only in a dev build. /dev/checkout carries a
// made-up person, so production must not route or bundle it (#170).
// Dev-build sentinel: a production bundle containing this name was built with
// import.meta.env.DEV true. scripts/check-dist-no-dev.mjs fails the build on it.
if (import.meta.env.DEV) (window as unknown as Record<string, unknown>).__KACHYNG_DEV_BUILD__ = true;

const devPage = (load: () => Promise<{ default: React.ComponentType }>) => (import.meta.env.DEV ? lazy(load) : null);
const DevCheckout = devPage(() => import("./pages/DevCheckout"));
const TestCardVariants = devPage(() => import("./pages/TestCardVariants"));
const TestVariantSelector = devPage(() => import("./pages/TestVariantSelector"));
const TestCollapsibleSection = devPage(() => import("./pages/TestCollapsibleSection"));
const TestQuantityEditor = devPage(() => import("./pages/TestQuantityEditor"));
const TestCardSdkDecomposed = devPage(() => import("./pages/TestCardSdkDecomposed"));
const ApprovalLinkPage = lazy(() => import("./pages/ApprovalLinkPage"));

class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { error: Error | null }
> {
  state: { error: Error | null } = { error: null };
  static getDerivedStateFromError(error: Error) { return { error }; }
  render() {
    const { error } = this.state;
    if (!error) return this.props.children;
    return (
      <div style={{
        padding: '32px', fontFamily: 'monospace', background: '#0a0a0a',
        color: '#f87171', minHeight: '100vh', whiteSpace: 'pre-wrap', wordBreak: 'break-word',
      }}>
        <div style={{ fontSize: '16px', fontWeight: 700, marginBottom: '16px' }}>
          ⚠ React crash — check the message below and fix the code
        </div>
        <div style={{ fontSize: '13px', color: '#fca5a5', marginBottom: '12px' }}>
          {error.message}
        </div>
        <div style={{ fontSize: '11px', color: '#6b7280', lineHeight: 1.6 }}>
          {error.stack}
        </div>
      </div>
    );
  }
}

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <ErrorBoundary>
      <BrowserRouter>
        <Routes>
          {/* #113: root is the real consumer wallet setup/login (KachyngWalletApp via
              EmbedKachyngNext), NOT a redirect to the frozen /embed/kachyng demo. */}
          <Route path="/" element={<Suspense fallback={null}><EmbedKachyngNext /></Suspense>} />
          <Route path="/embed/kachyng" element={<Suspense fallback={null}><EmbedKachyng /></Suspense>} />
          <Route path="/embed/kachyng-next" element={<Suspense fallback={null}><EmbedKachyngNext /></Suspense>} />
          {import.meta.env.DEV && DevCheckout && TestCardVariants && TestVariantSelector && TestCollapsibleSection && TestQuantityEditor && TestCardSdkDecomposed && (
            <>
              <Route path="/dev/checkout" element={<Suspense fallback={null}><DevCheckout /></Suspense>} />
              <Route path="/test/card-variants" element={<Suspense fallback={null}><TestCardVariants /></Suspense>} />
              <Route path="/test/variant-selector" element={<Suspense fallback={null}><TestVariantSelector /></Suspense>} />
              <Route path="/test/collapsible-section" element={<Suspense fallback={null}><TestCollapsibleSection /></Suspense>} />
              <Route path="/test/quantity-editor" element={<Suspense fallback={null}><TestQuantityEditor /></Suspense>} />
              <Route path="/test/card-sdk-decomposed" element={<Suspense fallback={null}><TestCardSdkDecomposed /></Suspense>} />
            </>
          )}
          {/* No-wallet approval: the link IDX texts the person (checkout-g3-service GET /approval/:shortcode). */}
          <Route path="/approval/:shortcode" element={<Suspense fallback={null}><ApprovalLinkPage /></Suspense>} />
          {/* Clean checkout URL: {merchant}.checkout.kachyng.com/{shortcode} — loads ONLY checkout, no wallet */}
          <Route path="/:shortcode" element={<CheckoutPage />} />
        </Routes>
      </BrowserRouter>
    </ErrorBoundary>
  </React.StrictMode>
);
