import { describe, expect, it, vi } from 'vitest'
import {
  deriveContentKey,
  encodeEnvelope,
  openReplayCiphertext,
  randomBytes,
  sealReplayFrame,
} from 'relay-e2e'
import { mountPreviewGrid } from '../src/preview-grid'
import type { PreviewDeps, ReplaySource } from '../src/preview-client'
import type { ApiClient } from '../src/api-client'
import type { HostRecord } from '../src/api-schemas'

const ALG = 'aes-256-gcm' as const

function host(sub: string): HostRecord {
  return {
    hostId: `id-${sub}`,
    accountId: 'acc',
    subdomain: sub,
    agentPubkey: new Uint8Array([1]),
    enrollFpr: `fpr-${sub}`,
    status: 'online',
    lastSeen: '2026-01-01T00:00:00Z',
    createdAt: '2026-01-01T00:00:00Z',
    revokedAt: null,
  }
}

const EPOCH = 'gen-1' // FIX 3b / F6: per-generation key diversifier (seal + declare under the same one).

function sealed(sessionId: string, secret: Uint8Array, line: string): ReplaySource {
  const k = deriveContentKey({ hostContentSecret: secret, sessionId, alg: ALG, epoch: EPOCH })
  return {
    sessionId,
    alg: ALG,
    epoch: EPOCH,
    frames: [encodeEnvelope(sealReplayFrame(k, 0n, new TextEncoder().encode(line)))],
  }
}

function fakeApi(hosts: readonly HostRecord[]): ApiClient {
  return {
    listHosts: vi.fn(async () => hosts),
    getHost: vi.fn(),
    requestPairingCode: vi.fn(),
    hostStatus: vi.fn(),
    issueCapabilityToken: vi.fn(),
  } as unknown as ApiClient
}

const realDeps: PreviewDeps = {
  deriveContentKey,
  openReplayCiphertext,
  createTerminal: () => ({ open: () => {}, write: () => {}, dispose: () => {} }),
}

const flush = () => new Promise((r) => setTimeout(r, 0))

describe('mountPreviewGrid (T9)', () => {
  it('renders one preview card per authorized host', async () => {
    const root = document.createElement('div')
    const secret = randomBytes(32)
    const loadReplay = vi.fn(async (hostId: string) => ({
      replay: sealed(hostId, secret, 'screen'),
      hostContentSecret: secret,
    }))
    const grid = mountPreviewGrid(root, fakeApi([host('a'), host('b')]), loadReplay, realDeps)
    await flush()
    await flush()
    expect(root.querySelectorAll('.preview-card')).toHaveLength(2)
    grid.dispose()
  })

  it('a host the account can\'t reach (loadReplay rejects) → "unavailable", never a foreign screen (INV1)', async () => {
    const root = document.createElement('div')
    const loadReplay = vi.fn(async () => {
      throw new Error('forbidden')
    })
    const grid = mountPreviewGrid(root, fakeApi([host('a')]), loadReplay, realDeps)
    await flush()
    await flush()
    expect(root.querySelector('.preview-unavailable')?.textContent).toBe('unavailable')
    grid.dispose()
  })

  it('a listHosts failure renders a grid-level error, not a fabricated screen', async () => {
    const root = document.createElement('div')
    const api = {
      listHosts: vi.fn(async () => {
        throw new Error('unauth')
      }),
    } as unknown as ApiClient
    const grid = mountPreviewGrid(root, api, vi.fn(), realDeps)
    await flush()
    expect(root.querySelector('.preview-grid-error')?.textContent).toBe('Could not load previews.')
    grid.dispose()
  })

  it('dispose() tears down every preview client (no leaked xterms)', async () => {
    const root = document.createElement('div')
    const secret = randomBytes(32)
    const disposed: string[] = []
    const deps: PreviewDeps = {
      deriveContentKey,
      openReplayCiphertext,
      createTerminal: () => ({ open: () => {}, write: () => {}, dispose: () => disposed.push('x') }),
    }
    const loadReplay = vi.fn(async (hostId: string) => ({
      replay: sealed(hostId, secret, 'screen'),
      hostContentSecret: secret,
    }))
    const grid = mountPreviewGrid(root, fakeApi([host('a')]), loadReplay, deps)
    await flush()
    await flush()
    grid.dispose()
    expect(disposed.length).toBeGreaterThan(0)
  })
})
