import { UEBridge } from './runtime/bridge';
import { resolveBootState } from './runtime/boot-state';
import { BrowserSupportAdapters, listAdapters, loadAdapter } from './runtime/registry';
import { createBrowserShell } from './runtime/shell';

declare global {
  interface Window {
    HyperTwistBrowserRuntime?: {
      adapters: typeof BrowserSupportAdapters;
      listAdapters: typeof listAdapters;
      loadAdapter: typeof loadAdapter;
      receiveCommand: (payload: unknown) => void;
      setShellState: (payload: unknown) => void;
      renderShell: (root: HTMLElement) => void;
      sendState: (payload: unknown) => void;
    };
  }
}

const BootState = resolveBootState();
const PendingCommands = [...(BootState.pendingCommands ?? [])];
const PendingShellStates = [...(BootState.pendingShellStates ?? [])];
BootState.runtimeMode = 'bundled-module';
BootState.runtimeReadyAtUtc = new Date().toISOString();
BootState.runtimeStatusId = 'runtime-ready';
BootState.queuedCommandCountAtRuntimeReady = PendingCommands.length;
BootState.queuedShellStateCountAtRuntimeReady = PendingShellStates.length;
BootState.adapterCount = listAdapters().length;
BootState.shellAuthority = 'Content/Browser/index.html';

const runtimeApi = {
  adapters: BrowserSupportAdapters,
  listAdapters,
  loadAdapter,
  receiveCommand(payload: unknown) {
    UEBridge.receiveCommand(payload);
  },
  setShellState(payload: unknown) {
    UEBridge.setShellState(payload);
  },
  renderShell(root: HTMLElement) {
    createBrowserShell(root);
  },
  sendState(payload: unknown) {
    UEBridge.sendState(payload);
  }
};

window.HyperTwistBrowserRuntime = runtimeApi;

const RootElement = document.getElementById('app');
if (RootElement instanceof HTMLElement)
{
  runtimeApi.renderShell(RootElement);
}

BootState.pendingCommands = [];
PendingCommands.forEach((Payload) => runtimeApi.receiveCommand(Payload));

BootState.pendingShellStates = [];
PendingShellStates.forEach((Payload) => runtimeApi.setShellState(Payload));

UEBridge.notifyRuntimeReady({
  status: 'ready',
  runtime: 'hypertwist-browser-runtime',
  mode: BootState.runtimeMode,
  adapterCount: BootState.adapterCount,
  shellAuthority: BootState.shellAuthority,
  queuedCommandCountAtRuntimeReady: BootState.queuedCommandCountAtRuntimeReady,
  queuedShellStateCountAtRuntimeReady: BootState.queuedShellStateCountAtRuntimeReady
});
