import { Box, Paper, Typography } from "@exotel-npm-dev/signal-design-system";
import { useEffect, useRef, useState } from "react";
import { ensureAafSdkLoaded, getAafSdkScriptUrl } from "./aaf/loadAafSdkIfNeeded";
import { registerAafSdk } from "./aaf/registerAafSdk.generated";
import { EventLoggerView } from "./components/EventLoggerView";
import { GWT_USE_CASE_KEY } from "./generated/useCaseKey";
import { AppTheme } from "./theme/AppTheme";

function ShellApp() {
  const statusRef = useRef<HTMLDivElement>(null);
  const [sdkPhase, setSdkPhase] = useState<"boot" | "error">("boot");

  useEffect(() => {
    const el = statusRef.current;
    let cancelled = false;

    void (async () => {
      try {
        if (el) el.textContent = "Checking AmeyoClient / aaf_sdk.js…";
        await ensureAafSdkLoaded();
        if (cancelled) return;
        await registerAafSdk(el);
      } catch (err: unknown) {
        if (cancelled) return;
        console.error("AAF bootstrap", err);
        setSdkPhase("error");
        if (el) {
          el.textContent =
            err instanceof Error
              ? err.message
              : "AAF bootstrap failed — see console.";
        }
      }
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <>
      <Typography variant="h5" component="h1" gutterBottom>
        GWT AAF slot
      </Typography>
      <Typography variant="body2" color="text.secondary" paragraph>
        If the parent did not inject <code>AmeyoClient</code>, this app loads the SDK script (same
        path as <code>background-app</code>): <code>{getAafSdkScriptUrl()}</code> — using query{" "}
        <code>sdkBaseUrl</code> or <code>origin</code> if set, otherwise <code>location.origin</code>{" "}
        (same order as Omni <code>getSdkModuleUrl</code>). Use <code>?sdkBaseUrl=…</code> when the SDK
        lives under a webapp prefix (e.g. <code>/ameyo40</code>).
      </Typography>
      {sdkPhase === "boot" && (
        <Typography variant="caption" color="text.secondary" display="block" sx={{ mb: 1 }}>
          Bootstrapping SDK…
        </Typography>
      )}
      <Paper variant="outlined" sx={{ p: 2, maxWidth: 720 }}>
        <Typography variant="subtitle2" color="text.secondary" gutterBottom>
          SDK status
        </Typography>
        <Box
          ref={statusRef}
          aria-live="polite"
          sx={{ typography: "body2", minHeight: "1.5rem" }}
        />
      </Paper>
    </>
  );
}

export function App() {
  return (
    <AppTheme>
      {GWT_USE_CASE_KEY === "global-events-logger" ? <EventLoggerView /> : <ShellApp />}
    </AppTheme>
  );
}
