import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { Toaster } from "react-hot-toast";
import { GlobalStyles, AlertsManager } from "@bigcommerce/big-design";
import { theme } from "@bigcommerce/big-design-theme";
import { ThemeProvider, createGlobalStyle } from "styled-components";
import "./css/app.css";
import AppRoutes from "./routes";
import api, { ensureCsrfCookie } from "./api/client";
import { ThemeToggleProvider, useThemeToggle } from "./context/ThemeContext";
import { alertsManager } from "./alertsManager";

// Prefetch CSRF cookie but do not block first paint — a hung API call leaves a blank iframe.
void ensureCsrfCookie();

interface ColorSchemeProps {
  $isDark: boolean;
}

const ColorSchemeStyle = createGlobalStyle<ColorSchemeProps>`
  :root {
    color-scheme: ${({ $isDark }) => ($isDark ? "dark" : "light")};
  }
  body {
    background-color: ${({ $isDark }) => ($isDark ? "#0f0f1a" : "rgb(246, 247, 252)")};
    color: ${({ $isDark }) => ($isDark ? "#e8e8f5" : "#111827")};
  }
`;

const lightTheme = {
  ...theme,
  colors: {
    ...theme.colors,
    secondary50: "#313440",
    secondary60: "#313440",
    secondary70: "#313440",
  },
};

const darkTheme = {
  ...theme,
  colors: {
    ...theme.colors,
    white: "#1a1a2e",
    secondary10: "#14141f",
    secondary20: "rgba(255,255,255,0.08)",
    secondary30: "rgba(255,255,255,0.15)",
    secondary50: "#fff",
    secondary60: "#fff",
    secondary70: "#fff",
    primary: "#7c9ef0",
    primary10: "#1a2040",
  },
};

function ThemedShell() {
  const { isDark } = useThemeToggle();

  return (
    <ThemeProvider theme={isDark ? darkTheme : lightTheme}>
      <ColorSchemeStyle $isDark={isDark} />
      <GlobalStyles />
      <AlertsManager manager={alertsManager} />
      <BrowserRouter>
        <AppRoutes />
        <Toaster position="top-right" />
      </BrowserRouter>
    </ThemeProvider>
  );
}

const AuthErrorScreen = () => {
  return (
    <div
      style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgb(246, 247, 252)",
        padding: "0 16px",
      }}
    >
      <div style={{ textAlign: "center", maxWidth: 448 }}>
        <p style={{ margin: "0 0 8px", fontSize: 15, color: "#111827" }}>
          Unable to authenticate with BigCommerce.
        </p>
        <p style={{ margin: 0, fontSize: 13, color: "#6b7280" }}>
          Please reopen the app from the BigCommerce Apps menu.
        </p>
      </div>
    </div>
  );
};

const handleAuth = async () => {
  const params = new URLSearchParams(window.location.search);
  const signedPayload = params.get("signed_payload");
  const signedPayloadJwt = params.get("signed_payload_jwt");

  if (signedPayload || signedPayloadJwt) {
    // Persist the signed_payload so it can be forwarded to activity Log
    if (signedPayload) {
      sessionStorage.setItem("bc_signed_payload", signedPayload);
    } else if (signedPayloadJwt) {
      sessionStorage.setItem("bc_signed_payload", signedPayloadJwt);
    }

    const authParams = new URLSearchParams();
    if (signedPayload) authParams.set("signed_payload", signedPayload);
    if (signedPayloadJwt)
      authParams.set("signed_payload_jwt", signedPayloadJwt);

    await api.post(`/api/auth/bigcommerce?${authParams.toString()}`);

    window.history.replaceState({}, "", window.location.pathname);
  }

  await ensureCsrfCookie();
};

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

handleAuth()
  .then(() => {
    root.render(
      <StrictMode>
        <ThemeToggleProvider>
          <ThemedShell />
        </ThemeToggleProvider>
      </StrictMode>,
    );
  })
  .catch(() => {
    root.render(<AuthErrorScreen />);
  });