/**
 * index.html entry — Phase-1 STAGING operator login → terminal view.
 *
 * The deployed Phase-1 relay serves this bundle and enables `POST /auth/mint` (B5). Flow:
 * password → mint a §4.3 capability token bound to a fresh browser DPoP key → open the WS carrying
 * the token (+ a DPoP proof signed by the SAME key) via the subprotocol → drive the terminal view.
 * No inline script (strict-CSP friendly): loaded via <script type="module">.
 */
import { readConfig, type RelayWebConfig } from '../config'
import { mountStagingLogin, type StagingSession } from '../login-staging'
import { createPassthroughTransport } from '../ws-transport'
import { mountTerminalView } from '../terminal-view'
import { DPOP_HTM, htuFor } from '../dpop'

async function connect(
  cfg: RelayWebConfig,
  session: StagingSession,
  loginRoot: HTMLElement,
  termRoot: HTMLElement,
): Promise<void> {
  // Sign a fresh DPoP proof for THIS upgrade with the key the token binds (`cnf.jkt`).
  const nowSec = Math.floor(Date.now() / 1000)
  const dpopProof = await session.dpop.proof(htuFor(session.aud), DPOP_HTM, nowSec)

  const transport = createPassthroughTransport(cfg, {
    capabilityToken: session.token,
    dpopProof,
  })
  // Reveal the terminal only after the socket is open; on failure the login screen stays visible.
  await transport.open()
  loginRoot.hidden = true
  termRoot.hidden = false
  mountTerminalView(termRoot, transport)
}

function boot(): void {
  const cfg = readConfig(window.location)
  const loginRoot = document.getElementById('login')
  const termRoot = document.getElementById('terminal')
  if (!loginRoot || !termRoot) return

  mountStagingLogin(loginRoot, cfg, {
    onSuccess: (session) => {
      void connect(cfg, session, loginRoot, termRoot).catch(() => {
        // Connection denied/dropped — keep the operator on the login screen (no bearer in logs).
        loginRoot.hidden = false
        termRoot.hidden = true
      })
    },
  })
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', boot)
} else {
  boot()
}
