import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

// Capacitor native bootstrap — only runs when packaged inside the Android app.
// In the browser preview these calls are no-ops because isNativePlatform() === false.
async function initNative() {
  try {
    const { Capacitor } = await import("@capacitor/core");
    if (!Capacitor.isNativePlatform()) return;

    const [{ StatusBar, Style }, { SplashScreen }, { App: CapApp }] = await Promise.all([
      import("@capacitor/status-bar"),
      import("@capacitor/splash-screen"),
      import("@capacitor/app"),
    ]);

    await StatusBar.setBackgroundColor({ color: "#C8102E" });
    await StatusBar.setStyle({ style: Style.Dark });

    // Hide splash after the React tree is mounted.
    setTimeout(() => SplashScreen.hide().catch(() => {}), 600);

    // Android back button: go back in history; exit only when at the root.
    CapApp.addListener("backButton", ({ canGoBack }) => {
      if (canGoBack && window.history.length > 1) {
        window.history.back();
      } else {
        CapApp.exitApp();
      }
    });
  } catch {
    // Capacitor not available (running in browser) — ignore.
  }
}

createRoot(document.getElementById("root")!).render(<App />);
initNative();
