import React from "react";
import ReactDOM from "react-dom/client";
import { MotionConfig } from "motion/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import { V4Root } from "./app/V4Root";
import { ThemeProvider } from "./hooks/useThemeEngine";
import { FloatingDesignDock } from "./components/UI/FloatingDesignDock";
import { reportRuntimeError } from "./lib/crashReporting";
import { motionConfig } from "./lib/motion/config";
import { registerServiceWorker } from "./lib/pwa";
import { useV4Router } from "./shared/data/featureFlags";
import { initPracticeToCommandBridge } from "./features/practices/bridge/practiceToCommandBridge";
import { MatryxAppProvider } from "./app/context/MatryxAppProvider";
import "./styles/tokens.css";
import "./components/UI/ui.css";
import "./styles.css";
import "./styles/app-refresh.css";
const queryClient = new QueryClient();
/** Legacy App.jsx is the default bootstrap path (opt in via VITE_USE_V4_ROUTER=true or matryx:use-v4-router). */
const enableV4Router = useV4Router();

function shouldShowDesignDock() {
  if (import.meta.env.DEV || import.meta.env.VITE_ENABLE_DESIGN_DOCK === "true") {
    return true;
  }

  if (typeof window === "undefined") {
    return false;
  }

  const params = new URLSearchParams(window.location.search);
  return params.get("qa") === "design" || params.get("design") === "true";
}

const showDesignDock = true; // Always available as the small in-product design widget for users to choose theme/style (previously dev/qa only; now user-facing for customization)

class RuntimeErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error) {
    // Keep the stack visible in console for debugging.
    console.error("Runtime render error:", error);
    reportRuntimeError(error, "react_error_boundary");
  }

  handleReset = () => {
    try {
      window.localStorage.removeItem("matryx-web-state");
      window.localStorage.removeItem("matryx-analytics-events");
      window.localStorage.removeItem("matryx-command-state");
      // Best-effort clear the Command Dexie DB (local-first lab notebook) without extra deps in boundary
      if (typeof indexedDB !== 'undefined' && indexedDB.deleteDatabase) {
        indexedDB.deleteDatabase('matryx_command');
      }
    } catch {
      // Ignore storage permission issues.
    }
    window.location.reload();
  };

  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div style={{ padding: 24, fontFamily: "Arial, sans-serif", color: "#1f2d2b" }}>
        <h1>Matryx hit a runtime error</h1>
        <p>The app failed while rendering. Use reset to clear local app data and reload safely. For persistent issues, contact support.</p>
        <pre style={{ whiteSpace: "pre-wrap", background: "#f4f3f0", padding: 12, borderRadius: 8 }}>
          {String(this.state.error?.message ?? this.state.error)}
        </pre>
        <button type="button" onClick={this.handleReset} style={{ marginTop: 12, padding: "10px 14px" }}>
          Reset Local Data And Reload
        </button>
        <p style={{ marginTop: 12 }}>
          Support: <a href="mailto:matryxoffice@gmail.com?subject=Matryx%20Runtime%20Error" style={{ color: '#348174' }}>matryxoffice@gmail.com</a> (include the error text above + steps)
        </p>
        <p style={{ fontSize: '0.9em' }}>AI Coach (in-app) and Community circles also provide immediate self-support options.</p>
      </div>
    );
  }
}

window.addEventListener("error", (event) => {
  console.error("Window error:", event.error ?? event.message);
  reportRuntimeError(event.error ?? event.message, "window_error");
});
window.addEventListener("unhandledrejection", (event) => {
  console.error("Unhandled promise rejection:", event.reason);
  reportRuntimeError(event.reason, "unhandled_rejection");
});

registerServiceWorker();
initPracticeToCommandBridge();

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <MatryxAppProvider>
      {enableV4Router ? (
        <V4Root />
      ) : (
        <QueryClientProvider client={queryClient}>
          <ThemeProvider>
            <MotionConfig {...motionConfig}>
              <RuntimeErrorBoundary>
                <App />
                {showDesignDock ? <FloatingDesignDock position="bottom-right" /> : null}
              </RuntimeErrorBoundary>
            </MotionConfig>
          </ThemeProvider>
        </QueryClientProvider>
      )}
    </MatryxAppProvider>
  </React.StrictMode>
);
