import { beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import { ROUTER_FUTURE_FLAGS } from '../router/router-future'

const mockUsePlatformAuth = vi.fn()
const mockGetAuthHealth = vi.fn()
const mockGetReleaseManifest = vi.fn()
const mockInvalidateSession = vi.fn()

vi.mock('../auth/platform-auth', () => ({
  usePlatformAuth: () => mockUsePlatformAuth(),
}))

vi.mock('../auth/auth-api', () => ({
  buildAuthApiBaseUrls: () => ['https://hypertwist.app'],
  createDesktopLinkToken: vi.fn(),
  getAuthHealth: (...args: unknown[]) => mockGetAuthHealth(...args),
  getReleaseManifest: (...args: unknown[]) => mockGetReleaseManifest(...args),
}))

import { AccountPage, BrowserAccessPage, DownloadCenterPage, NoticesPage, ProtectedLaunchStatusPage } from '../pages/app-pages'

function renderPage(page: React.ReactNode, initialEntry: string) {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  })

  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter initialEntries={[initialEntry]} future={ROUTER_FUTURE_FLAGS}>
        {page}
      </MemoryRouter>
    </QueryClientProvider>,
  )
}

function byExactTextContent(expected: string, tagName?: string) {
  return (_content: string, node: Element | null) => (
    node?.textContent === expected
      && (tagName ? node.tagName === tagName.toUpperCase() : true)
  )
}

describe('protected app pages', () => {
  beforeEach(() => {
    cleanup()
    mockUsePlatformAuth.mockReset()
    mockGetAuthHealth.mockReset()
    mockGetReleaseManifest.mockReset()
    mockInvalidateSession.mockReset()

    mockUsePlatformAuth.mockReturnValue({
      user: {
        id: 'operator-1',
        name: 'Operator',
        email: 'operator@hypertwist.app',
        authMethod: 'email',
        plan: 'operator',
        role: 'operator',
        canDownload: true,
        billing: {
          source: 'session',
          accessStatus: 'active',
          canDownload: true,
          lastEventType: 'transaction.completed',
        },
      },
      superTokensConfigured: true,
      invalidateSession: (...args: unknown[]) => mockInvalidateSession(...args),
      reconcileReleaseAuthority: vi.fn(),
      releaseAuthoritySyncItems: [],
    })

    mockGetAuthHealth.mockResolvedValue({
      ok: true,
      service: 'hypertwist-auth-server',
      supertokens: {
        configured: true,
        reachable: true,
        ready: true,
        apiVersion: '5.0',
        oauth: {
          github: false,
          google: false,
        },
      },
      fallback: {
        enabled: true,
        active: false,
        reason: null,
      },
      billing: {
        statePath: '/tmp/hypertwist-billing.json',
        processedEventCount: 1,
        pricePlanMapConfigured: true,
        productPlanMapConfigured: true,
        webhookSecretConfigured: true,
      },
      runtime: {
        mode: 'public',
        public_origin_ready: true,
        cookie_secure: true,
        api_domain: 'https://hypertwist.app',
        website_domain: 'https://hypertwist.app',
        warnings: [],
        errors: [],
      },
    })

    mockGetReleaseManifest.mockResolvedValue({
      ok: true,
      manifest: {
        generated_at: '2026-06-22T12:00:00.000Z',
        support_email: 'hello@hypertwist.app',
        public_docs_url: 'https://docs.hypertwist.app',
        release_notes_url: 'https://notes.hypertwist.app',
        corresponding_source_url: 'https://hypertwist.app/open-source/source.zip',
        open_source_repo_url: 'https://github.com/hypertwist/hypertwist',
        viewer: {
          authenticated: true,
          canDownload: true,
          plan: 'operator',
          role: 'operator',
          accessStatus: 'active',
        },
        platforms: [
          {
            platform_key: 'windows',
            platform: 'Windows',
            subtitle: 'Primary shipping lane',
            details: 'Current packaged validation is strongest on the Windows Unreal lane.',
            configured: true,
            channel: 'candidate',
            version: '1.0.0',
            build_id: 'win64-1000',
            published_at: '2026-06-22T00:00:00.000Z',
            file_name: 'HyperTwist-Windows.zip',
            file_size_bytes: 1048576,
            checksum_sha256: 'abc123',
            download_url: 'https://downloads.hypertwist.app/windows.exe',
            download_available: true,
            validation_summary: {
              lane: 'Windows Unreal packaged validation',
              result: 'passed',
              generated_at: '2026-06-22T01:43:08.7625247Z',
              configuration: 'Development',
              skip_build: true,
              smoke_map_count: 2,
              smoke_maps: [
                {
                  map_url: '/Game/HyperTwistTraining/Maps/L_HyperTwist_Magic120CellTraining',
                  label: 'Magic120Cell dedicated-family training map',
                  result: 'passed',
                },
                {
                  map_url: '/Game/HyperTwistTraining/Maps/L_HyperTwist_MagicCube5DTraining',
                  label: 'MagicCube5D dedicated-family training map',
                  result: 'passed',
                },
              ],
            },
          },
          {
            platform_key: 'macos',
            platform: 'macOS',
            subtitle: 'Planned distribution surface',
            details: 'List a signed desktop build here when the package lane is opened.',
            configured: false,
            channel: 'preview',
            version: null,
            build_id: null,
            published_at: null,
            file_name: null,
            file_size_bytes: null,
            checksum_sha256: null,
            download_url: null,
            download_available: false,
          },
        ],
      },
    })
  })

  it('surfaces live browser-shell status and browser-to-desktop guidance', async () => {
    renderPage(<BrowserAccessPage />, '/app/browser-access')

    expect(await screen.findByText('Current browser role')).toBeTruthy()
    expect(screen.getByText('Current release action')).toBeTruthy()
    expect((await screen.findByRole('link', { name: 'Download Windows package' })).getAttribute('href')).toBe('https://downloads.hypertwist.app/windows.exe')
    expect(screen.getByText('Current packaged desktop proof')).toBeTruthy()
    expect(screen.getByText('Packaged validation passed')).toBeTruthy()
    expect(screen.getByText(/Magic120Cell dedicated-family training map: passed/i)).toBeTruthy()
    expect(screen.getByText('Protected browser-versus-desktop reality')).toBeTruthy()
    expect(screen.getByText('Why the website feels fast and focused')).toBeTruthy()
    expect(screen.getByText('Desktop workflows behind the browser handoff')).toBeTruthy()
    expect(screen.getByText('4. Open the higher-dimensional families')).toBeTruthy()
    expect(screen.getByText('Native control and XR boundary')).toBeTruthy()
    expect(screen.getByText('Shipped classic control profile')).toBeTruthy()
    expect(await screen.findByText(byExactTextContent('Auth runtime mode: public', 'LI'))).toBeTruthy()
    expect(await screen.findByText(byExactTextContent('Configured release targets: 1/2', 'LI'))).toBeTruthy()
    expect(screen.getByText('Operator escalation map')).toBeTruthy()
    expect(screen.getByText('Account and entitlement issues')).toBeTruthy()
    expect(screen.getAllByRole('link', { name: 'Open dashboard' }).every((link) => link.getAttribute('href') === '/app')).toBe(true)
    expect(screen.getAllByRole('link', { name: 'Protected launch status' }).every((link) => link.getAttribute('href') === '/app/launch-status')).toBe(true)
    expect(screen.getByRole('link', { name: 'Protected notices' }).getAttribute('href')).toBe('/app/notices')
    expect(screen.getByRole('link', { name: 'Open support' }).getAttribute('href')).toBe('/support?topic=operator-access')
  })

  it('surfaces a dedicated protected launch-status route with signed-in rollout authority', async () => {
    renderPage(<ProtectedLaunchStatusPage />, '/app/launch-status')

    expect(await screen.findByRole('heading', { name: 'Protected launch status' })).toBeTruthy()
    expect(screen.getByText('Signed-in rollout authority')).toBeTruthy()
    expect(screen.getByText('Current release action')).toBeTruthy()
    expect(screen.getByText('Current packaged desktop proof')).toBeTruthy()
    expect(screen.getByText('Launch-readiness support lane')).toBeTruthy()
    expect(screen.getByText('Launch references and notices')).toBeTruthy()
    expect(screen.getByText('Protected browser-versus-desktop reality')).toBeTruthy()
    expect(screen.getByRole('link', { name: 'Open public launch status' }).getAttribute('href')).toBe('/launch-status')
    expect(screen.getAllByRole('link', { name: 'Open protected launch status' }).every((link) => link.getAttribute('href') === '/app/launch-status')).toBe(true)
    expect(await screen.findByText(byExactTextContent('Public repository/notices URL: https://github.com/hypertwist/hypertwist', 'LI'))).toBeTruthy()
    expect(screen.getByRole('link', { name: 'Protected notices' }).getAttribute('href')).toBe('/app/notices')
    expect(screen.getByRole('link', { name: 'Public notices' }).getAttribute('href')).toBe('/open-source-notices')
  })

  it('uses the authoritative auth-health launch summary on the protected launch route when the server provides it', async () => {
    mockGetAuthHealth.mockResolvedValue({
      ok: true,
      service: 'hypertwist-auth-server',
      supertokens: {
        configured: true,
        reachable: true,
        ready: true,
        apiVersion: '5.0',
        oauth: {
          github: false,
          google: false,
        },
      },
      fallback: {
        enabled: true,
        active: false,
        reason: null,
      },
      billing: {
        statePath: '/tmp/hypertwist-billing.json',
        processedEventCount: 1,
        pricePlanMapConfigured: true,
        productPlanMapConfigured: true,
        webhookSecretConfigured: true,
      },
      runtime: {
        mode: 'public',
        public_origin_ready: true,
        cookie_secure: true,
        api_domain: 'https://hypertwist.app',
        website_domain: 'https://hypertwist.app',
        warnings: [],
        errors: [],
      },
      launch: {
        posture: 'preview',
        ready: false,
        readiness: {
          windowsDownloadConfigured: true,
          operatorCheckoutConfigured: true,
          studioCheckoutConfigured: true,
          mplSourceConfigured: true,
          openSourceRepoConfigured: true,
          billingProductPlanMapConfigured: true,
          billingPricePlanMapConfigured: true,
          billingWebhookSecretConfigured: true,
          publicAuthRuntimeReady: true,
        },
        checklist: [
          {
            id: 'windows-download',
            label: 'Windows release authority',
            configured: true,
            requiredForPublicLaunch: true,
          },
        ],
        missingLabels: ['preview-tier launch gate'],
        targets: {
          operatorCheckoutTarget: 'https://buy.paddle.com/operator-authoritative',
          studioCheckoutTarget: 'https://buy.paddle.com/studio-authoritative',
        },
      },
    })

    renderPage(<ProtectedLaunchStatusPage />, '/app/launch-status')

    expect(await screen.findByText('Windows release authority: configured')).toBeTruthy()
    expect(screen.getByText('Operator checkout target: https://buy.paddle.com/operator-authoritative')).toBeTruthy()
    expect(screen.getByText('Studio checkout target: https://buy.paddle.com/studio-authoritative')).toBeTruthy()
    expect(screen.getByText(/Public launch is not fully configured yet: public launch gate\./i)).toBeTruthy()
  })

  it('surfaces concrete early-access blockers on the protected launch route', async () => {
    mockGetAuthHealth.mockResolvedValue({
      ok: true,
      service: 'hypertwist-auth-server',
      supertokens: {
        configured: true,
        reachable: true,
        ready: false,
        apiVersion: '5.0',
        oauth: {
          github: false,
          google: false,
        },
      },
      fallback: {
        enabled: true,
        active: false,
        reason: null,
      },
      billing: {
        statePath: '/tmp/hypertwist-billing.json',
        processedEventCount: 1,
        pricePlanMapConfigured: false,
        productPlanMapConfigured: false,
        webhookSecretConfigured: false,
      },
      runtime: {
        mode: 'mixed',
        public_origin_ready: true,
        cookie_secure: true,
        api_domain: 'https://hypertwist.app',
        website_domain: 'https://hypertwist.app',
        warnings: ['SUPERTOKENS_CORE_URI still targets a loopback/local-development host.'],
        errors: [],
      },
      launch: {
        posture: 'preview',
        ready: false,
        readiness: {
          windowsDownloadConfigured: false,
          operatorCheckoutConfigured: false,
          studioCheckoutConfigured: false,
          mplSourceConfigured: true,
          openSourceRepoConfigured: true,
          billingProductPlanMapConfigured: false,
          billingPricePlanMapConfigured: false,
          billingWebhookSecretConfigured: false,
          publicAuthRuntimeReady: false,
        },
        checklist: [
          {
            id: 'windows-download',
            label: 'Windows release authority',
            configured: false,
            requiredForPublicLaunch: true,
          },
        ],
        missingLabels: ['windows release authority', 'operator checkout URL', 'studio checkout URL'],
        targets: {
          operatorCheckoutTarget: null,
          studioCheckoutTarget: null,
        },
      },
    })

    renderPage(<ProtectedLaunchStatusPage />, '/app/launch-status')

    expect(await screen.findByText('Current early-access blockers from the live auth runtime')).toBeTruthy()
    expect(screen.getByText('Windows release delivery is still routed through signed-in account follow-up.')).toBeTruthy()
    expect(screen.getByText('Operator checkout is currently handled through account or support follow-up.')).toBeTruthy()
    expect(screen.getByText('Studio checkout is currently handled through account or support follow-up.')).toBeTruthy()
    expect(screen.getByText('Shared browser-auth runtime still needs production readiness confirmation on the current deployment.')).toBeTruthy()
    expect(screen.getByText('Paddle webhook verification still needs to be enabled for fully automated billing updates.')).toBeTruthy()
    expect(screen.getByText('Billing product-plan mapping still needs to be connected to the live subscription catalog.')).toBeTruthy()
    expect(screen.getByText('Billing price-plan mapping still needs to be connected to the live subscription catalog.')).toBeTruthy()
    expect(screen.getByText('Runtime warning: SUPERTOKENS_CORE_URI still targets a loopback/local-development host.')).toBeTruthy()
  })

  it('keeps the protected download center aligned with packaged proof, notices, and escalation guidance', async () => {
    renderPage(<DownloadCenterPage />, '/app/downloads?platform=windows')

    expect(await screen.findByText('Release targets')).toBeTruthy()
    expect(await screen.findByText('Version: 1.0.0')).toBeTruthy()
    expect(screen.getAllByText('Requested target').length).toBeGreaterThan(0)
    expect(screen.getByText('Current release action')).toBeTruthy()
    expect(screen.getByText('Windows package is ready for this account.')).toBeTruthy()
    expect(screen.getByRole('link', { name: 'Download Windows package' }).getAttribute('href')).toBe('https://downloads.hypertwist.app/windows.exe')
    expect(screen.getByText('Current packaged desktop proof')).toBeTruthy()
    expect(screen.getAllByText('Packaged validation passed').length).toBeGreaterThan(0)
    expect(screen.getByText('Protected operator quick routes')).toBeTruthy()
    expect(screen.getByText('What the downloaded software already supports')).toBeTruthy()
    expect(screen.getByText('3. Review replay, coaching, and analytics')).toBeTruthy()
    expect(screen.getByText('Protected browser-versus-desktop reality')).toBeTruthy()
    expect(screen.getByText('Why the desktop app exists')).toBeTruthy()
    expect(screen.getByRole('link', { name: 'Open account' }).getAttribute('href')).toBe('/app/account')
    expect(screen.getAllByRole('link', { name: 'Open browser access' }).every((link) => link.getAttribute('href') === '/app/browser-access')).toBe(true)
    expect(screen.getByText('Download and rollout escalation')).toBeTruthy()
    expect(screen.getByText('Current product-surface map')).toBeTruthy()
    expect(screen.getByText('Signed-in dashboard')).toBeTruthy()
    expect(screen.getAllByRole('link', { name: 'Protected launch status' }).every((link) => link.getAttribute('href') === '/app/launch-status')).toBe(true)
    expect(screen.getByRole('link', { name: 'Protected notices' }).getAttribute('href')).toBe('/app/notices')
    expect(screen.getByRole('link', { name: 'Public notices' }).getAttribute('href')).toBe('/open-source-notices')
    expect(screen.getAllByRole('link', { name: 'Download operator manual (.md)' }).every((link) => link.getAttribute('href') === '/manual/hypertwist-operator-manual.md')).toBe(true)
    expect(screen.getByRole('link', { name: 'Download Windows' }).getAttribute('href')).toBe('https://downloads.hypertwist.app/windows.exe')
  })

  it('surfaces account release access and protected follow-through links', async () => {
    renderPage(<AccountPage />, '/app/account')

    expect(await screen.findByText('Session profile')).toBeTruthy()
    expect(screen.getByText('Auth and session authority')).toBeTruthy()
    expect(await screen.findByText(byExactTextContent('Signed-in method: Email and password', 'LI'))).toBeTruthy()
    expect(await screen.findByText(byExactTextContent('Available provider routes: Email/password on, GitHub off, Google off, ORCID off', 'LI'))).toBeTruthy()
    expect(await screen.findByText(byExactTextContent('API domain: https://hypertwist.app', 'LI'))).toBeTruthy()
    expect(await screen.findByRole('link', { name: 'Download Windows package' })).toBeTruthy()
    expect(screen.getByText('Current packaged desktop proof')).toBeTruthy()
    expect(screen.getByText('Packaged validation passed')).toBeTruthy()
    expect(screen.getByText('Protected browser-versus-desktop reality')).toBeTruthy()
    expect(screen.getByText('Why the website feels fast and focused')).toBeTruthy()
    expect(screen.getByText('Current simulator control ownership')).toBeTruthy()
    expect(screen.getByText('Current release action')).toBeTruthy()
    expect(screen.getByRole('link', { name: 'Download Windows package' }).getAttribute('href')).toBe('https://downloads.hypertwist.app/windows.exe')
    expect(screen.getByText('Desktop workflows available to this account')).toBeTruthy()
    expect(screen.getByText('2. Run a recognition and correction workflow')).toBeTruthy()
    expect(screen.getAllByText(/classic-wca-keyboard\/v1/i).length).toBeGreaterThan(0)
    expect(screen.getByText('XR reopen requirements')).toBeTruthy()
    expect(screen.getByText('The native simulator now also owns first-party user-facing controller settings, layout presets, and rebinding truth for the exact shipped XR input ids.')).toBeTruthy()
    expect(screen.getByText(byExactTextContent('Billing source: session', 'LI'))).toBeTruthy()
    expect(await screen.findAllByText(byExactTextContent('Manifest viewer access: active', 'LI'))).toHaveLength(2)
    expect(await screen.findByText(byExactTextContent('Windows: Primary shipping lane (Version 1.0.0, Channel candidate)', 'LI'))).toBeTruthy()
    expect(screen.getAllByRole('link', { name: 'Open downloads' }).every((link) => link.getAttribute('href') === '/app/downloads')).toBe(true)
    expect(screen.getAllByRole('link', { name: 'Protected launch status' }).every((link) => link.getAttribute('href') === '/app/launch-status')).toBe(true)
    expect(screen.getAllByRole('link', { name: 'Download operator manual (.md)' }).every((link) => link.getAttribute('href') === '/manual/hypertwist-operator-manual.md')).toBe(true)
    expect(screen.getByRole('link', { name: 'Get help' }).getAttribute('href')).toBe('/support?topic=operator-access')
    expect(screen.getByText('Desktop access follow-through')).toBeTruthy()
    expect(screen.getByText('Verify the current training lanes')).toBeTruthy()
  })

  it('surfaces protected notices references and release-target notice status', async () => {
    renderPage(<NoticesPage />, '/app/notices')

    expect(await screen.findByText('Distribution notices')).toBeTruthy()
    expect(screen.getByText('Current release action')).toBeTruthy()
    expect((await screen.findByRole('link', { name: 'Download Windows package' })).getAttribute('href')).toBe('https://downloads.hypertwist.app/windows.exe')
    expect(screen.getByText('Current packaged desktop proof')).toBeTruthy()
    expect(screen.getByText('Packaged validation passed')).toBeTruthy()
    expect(screen.getByText('Protected browser-versus-desktop reality')).toBeTruthy()
    expect(screen.getByText('Why the desktop app exists')).toBeTruthy()
    expect(await screen.findAllByText(byExactTextContent('Configured release targets: 1/2', 'LI'))).toHaveLength(1)
    expect(screen.getByText(byExactTextContent('Public repository/notices URL: https://github.com/hypertwist/hypertwist', 'LI'))).toBeTruthy()
    expect(screen.getByText(byExactTextContent('Corresponding-source URL: https://hypertwist.app/open-source/source.zip', 'LI'))).toBeTruthy()
    expect(screen.getByText(byExactTextContent('Windows: published, validation passed', 'LI'))).toBeTruthy()
    expect(screen.getByText('Escalation and release follow-through')).toBeTruthy()
    expect(screen.getByText('Download and install issues')).toBeTruthy()
    expect(screen.getByRole('link', { name: 'Public notices' }).getAttribute('href')).toBe('/open-source-notices')
    expect(screen.getAllByRole('link', { name: 'Protected launch status' }).every((link) => link.getAttribute('href') === '/app/launch-status')).toBe(true)
    expect(screen.getAllByRole('link', { name: 'Open downloads' }).every((link) => link.getAttribute('href') === '/app/downloads')).toBe(true)
  })

  it('keeps local signed-in viewer state when protected pages recover from unavailable live release-manifest authority', async () => {
    mockGetReleaseManifest.mockRejectedValue(new Error('release manifest unavailable'))

    renderPage(<AccountPage />, '/app/account')

    expect(await screen.findByText('Session profile')).toBeTruthy()
    expect(await screen.findByText(byExactTextContent('Manifest viewer authenticated: yes', 'LI'))).toBeTruthy()
    expect(await screen.findAllByText(byExactTextContent('Manifest viewer plan: operator', 'LI'))).toHaveLength(2)
    expect(await screen.findAllByText(byExactTextContent('Manifest viewer access: active', 'LI'))).toHaveLength(2)
    expect(screen.getByText(/bounded recovery metadata until auth-server release authority returns/i)).toBeTruthy()
  })

  it('invalidates the protected browser session when live release-manifest authority comes back anonymous', async () => {
    mockGetReleaseManifest.mockResolvedValue({
      ok: true,
      manifest: {
        generated_at: '2026-06-23T12:00:00.000Z',
        support_email: 'hello@hypertwist.app',
        public_docs_url: 'https://docs.hypertwist.app',
        release_notes_url: 'https://notes.hypertwist.app',
        corresponding_source_url: 'https://hypertwist.app/open-source/source.zip',
        open_source_repo_url: 'https://github.com/hypertwist/hypertwist',
        viewer: {
          authenticated: false,
          canDownload: false,
          plan: null,
          role: null,
          accessStatus: null,
        },
        platforms: [
          {
            platform_key: 'windows',
            platform: 'Windows',
            subtitle: 'Primary shipping lane',
            details: 'Current packaged validation is strongest on the Windows Unreal lane.',
            configured: true,
            channel: 'candidate',
            version: '1.0.0',
            build_id: 'win64-1000',
            published_at: '2026-06-22T00:00:00.000Z',
            file_name: 'HyperTwist-Windows.zip',
            file_size_bytes: 1048576,
            checksum_sha256: 'abc123',
            download_url: null,
            download_available: false,
            validation_summary: {
              lane: 'Windows Unreal packaged validation',
              result: 'passed',
              generated_at: '2026-06-22T01:43:08.7625247Z',
              configuration: 'Development',
              skip_build: true,
              smoke_map_count: 2,
              smoke_maps: [
                {
                  map_url: '/Game/HyperTwistTraining/Maps/L_HyperTwist_Magic120CellTraining',
                  label: 'Magic120Cell dedicated-family training map',
                  result: 'passed',
                },
                {
                  map_url: '/Game/HyperTwistTraining/Maps/L_HyperTwist_MagicCube5DTraining',
                  label: 'MagicCube5D dedicated-family training map',
                  result: 'passed',
                },
              ],
            },
          },
        ],
      },
    })

    renderPage(<AccountPage />, '/app/account')

    await waitFor(() => {
      expect(mockInvalidateSession).toHaveBeenCalledWith('release_manifest_unauthorized')
    })
  })

  it('surfaces live authority sync details after the protected account lane refreshes from manifest truth', async () => {
    mockUsePlatformAuth.mockReturnValue({
      user: {
        id: 'operator-1',
        name: 'Operator',
        email: 'operator@hypertwist.app',
        authMethod: 'email',
        plan: 'free',
        role: 'viewer',
        canDownload: false,
        billing: {
          source: 'session',
          accessStatus: 'session-default',
          canDownload: false,
          lastEventType: 'transaction.completed',
        },
      },
      superTokensConfigured: true,
      invalidateSession: (...args: unknown[]) => mockInvalidateSession(...args),
      reconcileReleaseAuthority: vi.fn(),
      releaseAuthoritySyncItems: [
        'Plan changed from local free to live operator.',
        'Desktop download access changed from local not entitled to live enabled.',
        'Access status changed from local session-default to live active.',
      ],
    })

    renderPage(<AccountPage />, '/app/account')

    expect(await screen.findByText('Live authority sync')).toBeTruthy()
    expect(screen.getByText(/plan changed from local free to live operator/i)).toBeTruthy()
    expect(screen.getByText(/desktop download access changed from local not entitled to live enabled/i)).toBeTruthy()
    expect(screen.getByText(/access status changed from local session-default to live active/i)).toBeTruthy()
  })

  it('turns protected non-entitled account state into explicit checkout guidance when live commerce targets exist', async () => {
    mockUsePlatformAuth.mockReturnValue({
      user: {
        id: 'viewer-1',
        name: 'Viewer',
        email: 'viewer@hypertwist.app',
        authMethod: 'email',
        plan: 'free',
        role: 'viewer',
        canDownload: false,
        billing: {
          source: 'billing-state',
          accessStatus: 'payment_required',
          canDownload: false,
          lastEventType: 'transaction.payment_failed',
        },
      },
      superTokensConfigured: true,
      invalidateSession: (...args: unknown[]) => mockInvalidateSession(...args),
      reconcileReleaseAuthority: vi.fn(),
      releaseAuthoritySyncItems: [],
    })

    mockGetReleaseManifest.mockResolvedValue({
      ok: true,
      manifest: {
        generated_at: '2026-06-23T12:00:00.000Z',
        support_email: 'hello@hypertwist.app',
        public_docs_url: 'https://docs.hypertwist.app',
        release_notes_url: 'https://notes.hypertwist.app',
        corresponding_source_url: 'https://hypertwist.app/open-source/source.zip',
        open_source_repo_url: 'https://github.com/hypertwist/hypertwist',
        commerce: {
          operator_checkout_url: 'https://buy.paddle.com/operator-live',
          studio_checkout_url: 'https://buy.paddle.com/studio-live',
          plan_price_operator: '$29/mo',
          plan_price_studio: '$99/mo',
        },
        viewer: {
          authenticated: true,
          canDownload: false,
          plan: 'free',
          role: 'viewer',
          accessStatus: 'payment_required',
        },
        platforms: [
          {
            platform_key: 'windows',
            platform: 'Windows',
            subtitle: 'Primary shipping lane',
            details: 'Current packaged validation is strongest on the Windows Unreal lane.',
            configured: true,
            channel: 'candidate',
            version: '1.0.1',
            build_id: 'win64-1001',
            published_at: '2026-06-23T00:00:00.000Z',
            file_name: 'HyperTwist-Windows.zip',
            file_size_bytes: 1048576,
            checksum_sha256: 'abc124',
            download_url: null,
            download_available: false,
            validation_summary: {
              lane: 'Windows Unreal packaged validation',
              result: 'passed',
              generated_at: '2026-06-23T01:43:08.7625247Z',
              configuration: 'Development',
              skip_build: true,
              smoke_map_count: 2,
              smoke_maps: [
                {
                  map_url: '/Game/HyperTwistTraining/Maps/L_HyperTwist_Magic120CellTraining',
                  label: 'Magic120Cell dedicated-family training map',
                  result: 'passed',
                },
                {
                  map_url: '/Game/HyperTwistTraining/Maps/L_HyperTwist_MagicCube5DTraining',
                  label: 'MagicCube5D dedicated-family training map',
                  result: 'passed',
                },
              ],
            },
          },
        ],
      },
    })

    renderPage(<AccountPage />, '/app/account')

    expect(await screen.findByText('Current release action')).toBeTruthy()
    expect(await screen.findByText('Desktop package delivery still requires billing or operator provisioning.')).toBeTruthy()
    expect((await screen.findByRole('link', { name: 'Open operator checkout' })).getAttribute('href')).toBe('https://buy.paddle.com/operator-live')
    expect(screen.getByRole('link', { name: 'Open studio checkout' }).getAttribute('href')).toBe('https://buy.paddle.com/studio-live')
    expect(screen.getByRole('link', { name: 'Open pricing' }).getAttribute('href')).toBe('/pricing')
  })
})
