import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { RouterProvider } from "@tanstack/react-router";

import "./styles.css";
import { getRouter } from "./router";
import { SetupRequired } from "./components/setup-required";
import {
  SUPABASE_URL,
  SUPABASE_ANON_KEY,
  isValidSupabaseUrl,
  isValidSupabaseKey,
} from "./lib/env";

// Startup guard: detect missing/placeholder Supabase config BEFORE any
// provider mounts. Otherwise the Supabase client throws
// `Invalid supabaseUrl` at first access, which crashes the error boundary
// (it uses useI18n) and leaves the buyer with an opaque error.
const isValidUrl = isValidSupabaseUrl(SUPABASE_URL);
const isValidKey = isValidSupabaseKey(SUPABASE_ANON_KEY);

const rootEl = document.getElementById("root")!;
const root = createRoot(rootEl);

function renderSetup(missing: { url: boolean; key: boolean }, message?: string) {
  root.render(
    <StrictMode>
      <SetupRequired missing={missing} message={message} />
    </StrictMode>,
  );
}

if (!isValidUrl || !isValidKey) {
  renderSetup({ url: !isValidUrl, key: !isValidKey });
} else {
  try {
    const router = getRouter();
    root.render(
      <StrictMode>
        <RouterProvider router={router} />
      </StrictMode>,
    );
  } catch (err) {
    // Any unexpected startup crash (e.g. Supabase client init failure with a
    // malformed URL/key that passed the lightweight checks above) should
    // surface the setup screen instead of a blank/non-recoverable error.
    console.error("[startup] Falling back to SetupRequired:", err);
    renderSetup(
      { url: false, key: false },
      err instanceof Error ? err.message : "Unknown startup error",
    );
  }
}

// Last-resort safety net: an async error before any boundary mounts would
// otherwise leave the app blank. Catch it and show the setup screen.
window.addEventListener("error", (e) => {
  const msg = e.error?.message ?? e.message ?? "";
  if (/supabase|VITE_SUPABASE/i.test(msg)) {
    renderSetup({ url: !isValidUrl, key: !isValidKey }, msg);
  }
});
