import { useEffect, useMemo } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Link, useSearchParams } from 'react-router-dom'
import { buildAuthApiBaseUrls, createDesktopLinkToken, getAuthHealth, getReleaseManifest, type AuthHealthPayload } from '../auth/auth-api'
import { usePlatformAuth, type PlatformUser } from '../auth/platform-auth'
import { SiteMetadata } from '../components/seo/SiteMetadata'
import { HyperTwistButton, HyperTwistButtonAnchor, HyperTwistButtonLink } from '../components/ui/HyperTwistButton'
import { OperationalStatusCallout } from '../components/ui/OperationalStatusCallout'
import { ProductSurfaceMatrix } from '../components/ui/ProductSurfaceMatrix'
import { ReleaseValidationSummary } from '../components/ui/ReleaseValidationSummary'
import { buildLiveLaunchBlockerDetails, resolvePublicLaunchStatusSummary } from '../public-launch'
import { downloadTargets, launchReadiness, mplSourceUrl, openSourceRepoUrl, publicDocsUrl, releaseNotesUrl } from '../site-config'
import { buildReleaseMetadataItems, resolveReleaseManifestView, type ReleaseManifestView } from '../release-manifest'
import {
  buildProtectedDownloadPath,
  buildSupportPath,
  getDownloadPlatformLabel,
  isExternalHref,
  normalizeDownloadPlatform,
} from '../site-routes'
import {
  browserDesktopRealityCards,
  controlProfileRosterCards,
  desktopDownloadSteps,
  desktopFirstLaunchCards,
  desktopWorkflowTracks,
  inputAndDevicePostureCards,
  operatorDesktopQuickstartCards,
  productSurfaceMatrixRows,
  roadmapHonestyCards,
  supportEscalationCards,
} from '../site-data'
import { downloadablePublicManualHref, supportTopicDirectory } from './public-page-helpers'

function Panel({
  title,
  children,
  kicker,
}: {
  title: string
  children: React.ReactNode
  kicker?: string
}) {
  return (
    <article className="panel">
      {kicker ? <p className="eyebrow">{kicker}</p> : null}
      <h2>{title}</h2>
      {children}
    </article>
  )
}

function buildProtectedReleaseManifestFallback(user: PlatformUser | null | undefined, supportEmail: string) {
  return {
    downloadTargets,
    publicDocsUrl,
    releaseNotesUrl,
    correspondingSourceUrl: mplSourceUrl,
    openSourceRepoUrl,
    supportEmail,
    viewer: user ? {
      authenticated: true,
      canDownload: Boolean(user.canDownload),
      plan: user.plan,
      role: user.role || null,
      accessStatus: user.billing?.accessStatus || null,
    } : undefined,
  }
}

function useProtectedAuthHealthQuery(scope: string) {
  return useQuery({
    queryKey: ['auth-health', scope],
    queryFn: getAuthHealth,
    retry: false,
  })
}

function useProtectedReleaseManifestQuery(scope: string, userId: string | undefined, canDownload: boolean) {
  return useQuery({
    queryKey: ['release-manifest', scope, userId || 'anonymous', canDownload ? 'download' : 'nodownload'],
    queryFn: getReleaseManifest,
    retry: false,
  })
}

function useProtectedReleaseSurface(scope: string) {
  const platformAuth = usePlatformAuth()
  const { user, reconcileReleaseAuthority, invalidateSession, superTokensConfigured } = platformAuth
  const canDownload = user?.canDownload === true
  const releaseManifestQuery = useProtectedReleaseManifestQuery(scope, user?.id, canDownload)
  const releaseManifest = useMemo(
    () => resolveReleaseManifestView(
      releaseManifestQuery.data?.manifest,
      buildProtectedReleaseManifestFallback(user, user?.email || 'hello@hypertwist.app'),
    ),
    [releaseManifestQuery.data?.manifest, user],
  )

  useEffect(() => {
    const liveViewer = releaseManifestQuery.data?.manifest?.viewer
    if (liveViewer?.authenticated && typeof reconcileReleaseAuthority === 'function') {
      reconcileReleaseAuthority(liveViewer)
    }
  }, [reconcileReleaseAuthority, releaseManifestQuery.data?.manifest?.viewer])

  useEffect(() => {
    const liveViewer = releaseManifestQuery.data?.manifest?.viewer
    if (
      user
      && superTokensConfigured
      && liveViewer
      && liveViewer.authenticated === false
      && typeof invalidateSession === 'function'
    ) {
      invalidateSession('release_manifest_unauthorized')
    }
  }, [invalidateSession, releaseManifestQuery.data?.manifest?.viewer, superTokensConfigured, user])

  return {
    ...platformAuth,
    canDownload,
    releaseManifest,
    releaseManifestQuery,
    releaseAuthoritySyncItems: platformAuth.releaseAuthoritySyncItems ?? [],
  }
}

function getProtectedDownloadActionLabel({
  configured,
  viewerCanDownload,
  releaseAuthorityUnavailable,
}: {
  configured: boolean
  viewerCanDownload: boolean
  releaseAuthorityUnavailable: boolean
}) {
  if (!configured) {
    return 'Release access is not published yet'
  }

  if (viewerCanDownload) {
    return releaseAuthorityUnavailable
      ? 'Live release authority temporarily unavailable'
      : 'Download temporarily unavailable'
  }

  return 'Account not entitled yet'
}

function isUnauthorizedAuthApiError(error: unknown) {
  return typeof error === 'object'
    && error !== null
    && 'status' in error
    && Number((error as { status?: number }).status) === 401
}

function formatAuthMethodLabel(method: PlatformUser['authMethod'] | undefined) {
  switch (method) {
    case 'email':
      return 'Email and password'
    case 'github':
      return 'GitHub'
    case 'google':
      return 'Google'
    case 'orcid':
      return 'ORCID'
    case 'supertokens':
      return 'Shared SuperTokens session'
    default:
      return 'Unknown'
  }
}

function ProtectedAuthSessionAuthorityPanel({
  title,
  kicker,
  user,
  superTokensConfigured,
  healthQuery,
}: {
  title: string
  kicker: string
  user: PlatformUser | null | undefined
  superTokensConfigured: boolean
  healthQuery: ReturnType<typeof useProtectedAuthHealthQuery>
}) {
  return (
    <Panel title={title} kicker={kicker}>
      <ul className="list">
        <li>Signed-in method: {formatAuthMethodLabel(user?.authMethod)}</li>
        <li>Auth stack: {superTokensConfigured ? 'SuperTokens-backed' : 'Local recovery mode'}</li>
        {healthQuery.data ? (
          <>
            <li>Shared auth configured: {healthQuery.data.supertokens.configured ? 'yes' : 'no'}</li>
            <li>Shared auth core reachable: {healthQuery.data.supertokens.reachable ? 'yes' : 'no'}</li>
            <li>Shared auth ready: {healthQuery.data.supertokens.ready ? 'yes' : 'no'}</li>
            <li>Core API version: {healthQuery.data.supertokens.apiVersion || 'unavailable'}</li>
            <li>
              Available provider routes: Email/password on, GitHub {healthQuery.data.supertokens.oauth?.github ? 'on' : 'off'}, Google {healthQuery.data.supertokens.oauth?.google ? 'on' : 'off'}, ORCID {healthQuery.data.supertokens.oauth?.orcid ? 'on' : 'off'}
            </li>
            <li>
              Recovery mode: {healthQuery.data.fallback.active
                ? `active${healthQuery.data.fallback.reason ? ` (${healthQuery.data.fallback.reason})` : ''}`
                : 'inactive'}
            </li>
            <li>Runtime mode: {healthQuery.data.runtime.mode}</li>
            <li>API domain: {healthQuery.data.runtime.api_domain}</li>
            <li>Website domain: {healthQuery.data.runtime.website_domain}</li>
            <li>Cookie secure: {healthQuery.data.runtime.cookie_secure ? 'yes' : 'no'}</li>
            <li>Public auth origin ready: {healthQuery.data.runtime.public_origin_ready ? 'yes' : 'no'}</li>
          </>
        ) : null}
      </ul>
      {healthQuery.isLoading ? <p>Checking auth server health...</p> : null}
      {healthQuery.isError ? (
        <OperationalStatusCallout
          badge="Auth probe degraded"
          title="Auth health probe failed."
          summary="The local fallback can still keep the protected browser shell usable."
          sections={[
            {
              title: 'What still works',
              items: [
                'Local session, packaged proof, and browser-to-desktop rollout guidance remain visible.',
                'Protected dashboard orientation and support escalation surfaces remain available.',
              ],
            },
            {
              title: 'What stays intentionally bounded',
              items: [
                'Do not treat browser auth as shared production authority until the live auth probe recovers.',
              ],
            },
            {
              title: 'Recommended recovery order',
              items: [
                'Restore shared auth reachability before trusting live entitlement or desktop-link issuance.',
                'Use operator support if the protected dashboard stays in degraded auth state.',
              ],
            },
          ]}
        />
      ) : null}
      {healthQuery.data?.fallback.active ? (
        <OperationalStatusCallout
          badge="Dashboard recovery mode"
          title="Shared auth core is not fully ready right now."
          summary={`Dashboard recovery mode remains available${healthQuery.data.fallback.reason ? ` (${healthQuery.data.fallback.reason})` : ''}.`}
          sections={[
            {
              title: 'What still works',
              items: [
                'Bounded session continuity, packaged proof, and operator guidance remain usable inside the protected dashboard.',
                'Account, release, and desktop-pairing surfaces can still be reviewed without claiming live shared-auth authority.',
              ],
            },
            {
              title: 'What stays intentionally bounded',
              items: [
                'Live entitlement proof, shared-production session authority, and rollout trust should wait for the auth core to recover.',
              ],
            },
            {
              title: 'Recommended recovery order',
              items: [
                'Clear auth-core readiness problems first, then re-check release authority and desktop-link issuance.',
              ],
            },
          ]}
        />
      ) : null}
      {healthQuery.data && (healthQuery.data.runtime.errors.length > 0 || healthQuery.data.runtime.warnings.length > 0) ? (
        <div className="callout">
          <p>Runtime deployment diagnostics</p>
          {healthQuery.data.runtime.errors.length > 0 ? (
            <ul className="list">
              {healthQuery.data.runtime.errors.map((item) => (
                <li key={item}>Error: {item}</li>
              ))}
            </ul>
          ) : null}
          {healthQuery.data.runtime.warnings.length > 0 ? (
            <ul className="list">
              {healthQuery.data.runtime.warnings.map((item) => (
                <li key={item}>Warning: {item}</li>
              ))}
            </ul>
          ) : null}
        </div>
      ) : null}
    </Panel>
  )
}

function ReleaseAuthorityLinks({
  releaseManifest,
  includeProtectedLaunchStatusLink = false,
  includePublicNoticesLink = false,
  includeProtectedNoticesLink = false,
}: {
  releaseManifest: ReleaseManifestView
  includeProtectedLaunchStatusLink?: boolean
  includePublicNoticesLink?: boolean
  includeProtectedNoticesLink?: boolean
}) {
  const hasLinks = Boolean(
    downloadablePublicManualHref
      || releaseManifest.public_docs_url
      || releaseManifest.release_notes_url
      || releaseManifest.corresponding_source_url
      || releaseManifest.open_source_repo_url
      || includeProtectedLaunchStatusLink
      || includePublicNoticesLink
      || includeProtectedNoticesLink,
  )

  if (!hasLinks) {
    return null
  }

  return (
    <div className="button-row top-gap">
      <HyperTwistButtonAnchor tone="ghost" href={downloadablePublicManualHref} download>
        Download operator manual (.md)
      </HyperTwistButtonAnchor>
      {releaseManifest.public_docs_url ? (
        <HyperTwistButtonAnchor tone="ghost" href={releaseManifest.public_docs_url} target="_blank" rel="noreferrer">
          Public docs
        </HyperTwistButtonAnchor>
      ) : null}
      {releaseManifest.release_notes_url ? (
        <HyperTwistButtonAnchor tone="ghost" href={releaseManifest.release_notes_url} target="_blank" rel="noreferrer">
          Release notes
        </HyperTwistButtonAnchor>
      ) : null}
      {releaseManifest.corresponding_source_url ? (
        <HyperTwistButtonAnchor tone="ghost" href={releaseManifest.corresponding_source_url} target="_blank" rel="noreferrer">
          Corresponding source
        </HyperTwistButtonAnchor>
      ) : null}
      {releaseManifest.open_source_repo_url ? (
        <HyperTwistButtonAnchor tone="ghost" href={releaseManifest.open_source_repo_url} target="_blank" rel="noreferrer">
          Repository/notices
        </HyperTwistButtonAnchor>
      ) : null}
      {includeProtectedLaunchStatusLink ? (
        <HyperTwistButtonLink tone="ghost" to="/app/launch-status">
          Protected launch status
        </HyperTwistButtonLink>
      ) : null}
      {includeProtectedNoticesLink ? (
        <HyperTwistButtonLink tone="ghost" to="/app/notices">
          Protected notices
        </HyperTwistButtonLink>
      ) : null}
      {includePublicNoticesLink ? (
        <HyperTwistButtonLink tone="ghost" to="/open-source-notices">
          Public notices
        </HyperTwistButtonLink>
      ) : null}
    </div>
  )
}

function findWindowsManifestTarget(releaseManifest: ReleaseManifestView) {
  return releaseManifest.platforms.find((platform) => platform.platform_key === 'windows') || null
}

const protectedPackagedDesktopProofTitle = 'Current packaged desktop proof'

type ProtectedSupportTopicRoute = {
  label: string
  to: string
}

type ProtectedSupportTopicGuide = (typeof supportTopicDirectory)[number] & {
  actions: readonly ProtectedSupportTopicRoute[]
}

type ProtectedReleaseAction = {
  label: string
  href: string
  primary?: boolean
}

type ProtectedLaunchReadinessAction = {
  label: string
  to: string
}

type ProtectedReleaseActionSurface = {
  badge: string
  tone: 'success' | 'info'
  title: string
  summary: string
  items: readonly string[]
  actions: readonly ProtectedReleaseAction[]
}

function buildProtectedSupportTopicActions(topicKey: string): readonly ProtectedSupportTopicRoute[] {
  switch (topicKey) {
    case 'launch-readiness':
      return [
        { label: 'Open protected launch status', to: '/app/launch-status' },
        { label: 'Open downloads', to: buildProtectedDownloadPath('windows') },
        { label: 'Open notices', to: '/app/notices' },
        { label: 'Open pricing', to: '/pricing' },
      ]
    case 'operator-access':
      return [
        { label: 'Open protected launch status', to: '/app/launch-status' },
        { label: 'Open downloads', to: buildProtectedDownloadPath('windows') },
        { label: 'Open dashboard', to: '/app' },
        { label: 'Open account', to: '/app/account' },
      ]
    case 'studio-rollout':
      return [
        { label: 'Open protected launch status', to: '/app/launch-status' },
        { label: 'Open browser access', to: '/app/browser-access' },
        { label: 'Open notices', to: '/app/notices' },
        { label: 'Review release notes', to: '/changelog' },
      ]
    default:
      return []
  }
}

const protectedSupportTopicGuides: readonly ProtectedSupportTopicGuide[] = supportTopicDirectory.map((topic) => ({
  ...topic,
  actions: buildProtectedSupportTopicActions(topic.topicKey),
}))

function ProtectedActionLink({
  action,
}: {
  action: ProtectedReleaseAction
}) {
  const className = action.primary ? 'button button--primary' : 'button button--ghost'

  if (isExternalHref(action.href)) {
    return (
      <a className={className} href={action.href} target="_blank" rel="noreferrer">
        {action.label}
      </a>
    )
  }

  return (
    <Link className={className} to={action.href}>
      {action.label}
    </Link>
  )
}

function ProtectedLaunchReadinessPanel({
  title,
  kicker,
  description,
  authHealth,
  launchStatus,
  releaseManifestQuery,
  actions = [],
}: {
  title: string
  kicker: string
  description?: string
  authHealth?: AuthHealthPayload | null
  launchStatus: ReturnType<typeof resolvePublicLaunchStatusSummary>
  releaseManifestQuery: {
    isLoading: boolean
    isError: boolean
  }
  actions?: readonly ProtectedLaunchReadinessAction[]
}) {
  const launchReadinessIssues = launchStatus.missingLabels
  const liveBlockerDetails = useMemo(
    () => buildLiveLaunchBlockerDetails(authHealth, launchStatus),
    [authHealth, launchStatus],
  )

  return (
    <Panel title={title} kicker={kicker}>
      {description ? <p>{description}</p> : null}
      <p className={`status-pill${launchStatus.ready ? ' status-pill--success' : ''}`}>
        {launchStatus.ready ? 'Launch-ready status' : 'Early-access status'}
      </p>
      <ul className="list">
        {launchStatus.checklist.map((item) => (
          <li key={item.id}>
            {item.label}: {item.configured
              ? (item.id === 'public-auth-runtime' ? 'production-ready' : 'configured')
              : (item.id === 'public-auth-runtime' ? 'local-or-mixed' : 'pending')}
          </li>
        ))}
        <li>Operator checkout target: {launchStatus.targets.operatorCheckoutTarget || 'support follow-up active'}</li>
        <li>Studio checkout target: {launchStatus.targets.studioCheckoutTarget || 'support follow-up active'}</li>
      </ul>
      {liveBlockerDetails.length > 0 ? (
        <div className="callout top-gap">
          <p>{launchStatus.ready ? 'Live runtime notes' : 'Current early-access blockers from the live auth runtime'}</p>
          <ul className="list">
            {liveBlockerDetails.map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        </div>
      ) : null}
      {releaseManifestQuery.isLoading ? (
        <p>Refreshing release-manifest download readiness from the auth server.</p>
      ) : null}
      {releaseManifestQuery.isError ? (
        <ProtectedReleaseAuthorityNotice
          badge="Dashboard release recovery"
          title="Live release-manifest lookup failed."
          summary="Download readiness is currently using local recovery metadata rather than current runtime release authority."
          stillWorks={[
            'Protected launch-readiness interpretation, packaged proof, and account status remain visible.',
            'The protected browser shell can still separate auth, package, runtime, and rollout work while release authority recovers.',
          ]}
          actionTo="/app/downloads"
          actionLabel="Open downloads"
        />
      ) : null}
      {launchReadinessIssues.length > 0 ? (
        <p className="form-error">
          Public launch is not fully configured yet: {launchReadinessIssues.join('; ')}.
        </p>
      ) : (
        <p>Core public release configuration is present for the current bounded website lane.</p>
      )}
      {actions.length > 0 ? (
        <div className="button-row top-gap">
          {actions.map((action) => (
            <HyperTwistButtonLink key={`${title}-${action.label}`} tone="ghost" to={action.to}>
              {action.label}
            </HyperTwistButtonLink>
          ))}
        </div>
      ) : null}
    </Panel>
  )
}

function describeReleaseTarget(
  platform: ReleaseManifestView['platforms'][number] | null | undefined,
) {
  if (!platform) {
    return 'No desktop target selected yet'
  }

  const metadata: string[] = []
  if (platform.version) {
    metadata.push(platform.version)
  }
  if (platform.channel) {
    metadata.push(platform.channel)
  }

  return metadata.length > 0
    ? `${platform.platform} (${metadata.join(', ')})`
    : platform.platform
}

function buildProtectedCheckoutActions(releaseManifest: ReleaseManifestView) {
  const operatorCheckoutUrl = releaseManifest.commerce?.operator_checkout_url || null
  const studioCheckoutUrl = releaseManifest.commerce?.studio_checkout_url || null
  const preferredCheckoutUrl = releaseManifest.viewer.plan === 'studio'
    ? (studioCheckoutUrl || operatorCheckoutUrl)
    : (operatorCheckoutUrl || studioCheckoutUrl)

  const preferredCheckoutLabel = preferredCheckoutUrl === studioCheckoutUrl
    ? 'Open studio checkout'
    : 'Open operator checkout'

  const secondaryCheckoutUrl = [operatorCheckoutUrl, studioCheckoutUrl]
    .find((candidate) => candidate && candidate !== preferredCheckoutUrl) || null

  const secondaryCheckoutLabel = secondaryCheckoutUrl === studioCheckoutUrl
    ? 'Open studio checkout'
    : 'Open operator checkout'

  return [
    preferredCheckoutUrl ? {
      label: preferredCheckoutLabel,
      href: preferredCheckoutUrl,
      primary: true,
    } : null,
    secondaryCheckoutUrl ? {
      label: secondaryCheckoutLabel,
      href: secondaryCheckoutUrl,
    } : null,
  ].filter((action): action is ProtectedReleaseAction => action != null)
}

function buildProtectedReleaseActionSurface({
  releaseManifest,
  requestedPlatform,
  releaseAuthorityUnavailable,
}: {
  releaseManifest: ReleaseManifestView
  requestedPlatform?: string | null
  releaseAuthorityUnavailable: boolean
}): ProtectedReleaseActionSurface {
  const configuredTargets = releaseManifest.platforms.filter((platform) => platform.configured)
  const requestedTarget = requestedPlatform
    ? (releaseManifest.platforms.find((platform) => platform.platform_key === requestedPlatform) || null)
    : null
  const downloadableTargets = releaseManifest.platforms.filter((platform) => Boolean(platform.download_url))
  const primaryDownloadTarget = downloadableTargets.find((platform) => (
    requestedTarget ? platform.platform_key === requestedTarget.platform_key : platform.platform_key === 'windows'
  )) || downloadableTargets[0] || null
  const supportEmail = releaseManifest.support_email || 'hello@hypertwist.app'
  const manifestPlan = releaseManifest.viewer.plan || 'unresolved'
  const manifestAccessStatus = releaseManifest.viewer.accessStatus || 'not resolved yet'
  const configuredTargetsLabel = `${configuredTargets.length}/${releaseManifest.platforms.length} configured`

  if (releaseAuthorityUnavailable) {
    if (releaseManifest.viewer.canDownload) {
      return {
        badge: 'Release recovery mode',
        tone: 'info',
        title: 'Live release authority must recover before package delivery resumes.',
        summary:
          'Your signed-in account still resolves to desktop access, but this protected lane intentionally withholds direct downloads until the auth server returns.',
        items: [
          `Manifest viewer plan: ${manifestPlan}`,
          `Manifest viewer access: ${manifestAccessStatus}`,
          `Protected target: ${requestedTarget ? describeReleaseTarget(requestedTarget) : 'Windows default'}`,
          `Configured release targets: ${configuredTargetsLabel}`,
          `Support contact: ${supportEmail}`,
        ],
        actions: [
          { label: 'Open downloads', href: buildProtectedDownloadPath('windows'), primary: true },
          { label: 'Open protected launch status', href: '/app/launch-status' },
          { label: 'Review notices', href: '/app/notices' },
          { label: 'Get help', href: buildSupportPath('operator-access') },
        ],
      }
    }

    return {
      badge: 'Release authority degraded',
      tone: 'info',
      title: 'Wait for live release authority before trusting upgrade or delivery status.',
      summary:
        'This protected lane is still useful for orientation, but checkout, entitlement, and package-delivery decisions should wait until the auth server is back.',
      items: [
        `Manifest viewer plan: ${manifestPlan}`,
        `Manifest viewer access: ${manifestAccessStatus}`,
        `Configured release targets: ${configuredTargetsLabel}`,
        `Support contact: ${supportEmail}`,
      ],
      actions: [
        { label: 'Open pricing', href: '/pricing', primary: true },
        { label: 'Open protected launch status', href: '/app/launch-status' },
        { label: 'Review notices', href: '/app/notices' },
        { label: 'Get help', href: buildSupportPath('operator-access') },
      ],
    }
  }

  if (releaseManifest.viewer.canDownload && primaryDownloadTarget?.download_url) {
    const primaryActionTarget = requestedTarget && requestedTarget.configured === false
      ? primaryDownloadTarget
      : (requestedTarget || primaryDownloadTarget)

    return {
      badge: 'Download ready',
      tone: 'success',
      title: requestedTarget && requestedTarget.configured === false
        ? `${requestedTarget.platform} is not published yet, but another entitled package is ready.`
        : `${primaryActionTarget.platform} package is ready for this account.`,
      summary: requestedTarget && requestedTarget.configured === false
        ? `Your requested ${requestedTarget.platform} lane is not published yet, but the protected release lane can still deliver ${describeReleaseTarget(primaryDownloadTarget)} right now.`
        : 'The protected release lane now has both live entitlement and a current package target, so download and release references can stay attached to the same operator workflow.',
      items: [
        `Manifest viewer plan: ${manifestPlan}`,
        `Manifest viewer access: ${manifestAccessStatus}`,
        `Primary release target: ${describeReleaseTarget(primaryActionTarget)}`,
        `Configured release targets: ${configuredTargetsLabel}`,
        `Support contact: ${supportEmail}`,
      ],
      actions: [
        { label: `Download ${primaryActionTarget.platform} package`, href: primaryDownloadTarget.download_url, primary: true },
        { label: 'Open protected launch status', href: '/app/launch-status' },
        { label: 'Review notices', href: '/app/notices' },
        { label: 'Review release notes', href: '/changelog' },
      ],
    }
  }

  if (configuredTargets.length === 0) {
    return {
      badge: 'Awaiting packaged release target',
      tone: 'info',
      title: 'Desktop access is visible, but no packaged target is published yet.',
      summary:
        'This protected lane can still show account and release status, but it cannot deliver a desktop package until at least one target is published.',
      items: [
        `Manifest viewer plan: ${manifestPlan}`,
        `Manifest viewer access: ${manifestAccessStatus}`,
        `Configured release targets: ${configuredTargetsLabel}`,
        `Support contact: ${supportEmail}`,
      ],
      actions: [
        { label: 'Review release notes', href: '/changelog', primary: true },
        { label: 'Open protected launch status', href: '/app/launch-status' },
        { label: 'Review notices', href: '/app/notices' },
        { label: 'Get help', href: buildSupportPath('launch-readiness') },
      ],
    }
  }

  if (!releaseManifest.viewer.canDownload) {
    const checkoutActions = buildProtectedCheckoutActions(releaseManifest)
    const statusItems = [
      `Manifest viewer plan: ${manifestPlan}`,
      `Manifest viewer access: ${manifestAccessStatus}`,
      `Configured release targets: ${configuredTargetsLabel}`,
      `Operator checkout target: ${releaseManifest.commerce?.operator_checkout_url ? 'available' : 'support follow-up'}`,
      `Studio checkout target: ${releaseManifest.commerce?.studio_checkout_url ? 'available' : 'support follow-up'}`,
    ]

    if (checkoutActions.length > 0) {
      return {
        badge: 'Upgrade or provisioning required',
        tone: 'info',
        title: 'Desktop package delivery still requires billing or operator provisioning.',
        summary:
          'The protected release lane can show live release status now, but it still keeps actual package delivery behind the current checkout and entitlement rules.',
        items: [
          ...statusItems,
          `Support contact: ${supportEmail}`,
        ],
        actions: [
          ...checkoutActions,
          { label: 'Open protected launch status', href: '/app/launch-status' },
          { label: 'Open pricing', href: '/pricing' },
        ],
      }
    }

    return {
      badge: 'Checkout not live yet',
      tone: 'info',
      title: 'Protected release status is ready, but live checkout is not available yet.',
      summary:
        'This deployment can show the signed-in release lane, yet commercial access still depends on operator help because live checkout targets are not available.',
      items: [
        ...statusItems,
        `Support contact: ${supportEmail}`,
      ],
      actions: [
        { label: 'Open pricing', href: '/pricing', primary: true },
        { label: 'Open protected launch status', href: '/app/launch-status' },
        { label: 'Review notices', href: '/app/notices' },
        { label: 'Get help', href: buildSupportPath('operator-access') },
      ],
    }
  }

  return {
    badge: 'Release lane ready for review',
    tone: 'info',
    title: 'Protected release status is available for operator follow-through.',
    summary:
      'The protected lane is carrying live release metadata, packaged proof, and sign-in continuity even though a direct package action is not available from this exact state.',
    items: [
      `Manifest viewer plan: ${manifestPlan}`,
      `Manifest viewer access: ${manifestAccessStatus}`,
      `Configured release targets: ${configuredTargetsLabel}`,
      `Support contact: ${supportEmail}`,
    ],
    actions: [
      { label: 'Open downloads', href: buildProtectedDownloadPath('windows'), primary: true },
      { label: 'Open protected launch status', href: '/app/launch-status' },
      { label: 'Review notices', href: '/app/notices' },
      { label: 'Get help', href: buildSupportPath('operator-access') },
    ],
  }
}

function ProtectedReleaseAuthorityNotice({
  badge,
  title,
  summary,
  stillWorks,
  actionTo,
  actionLabel,
}: {
  badge: string
  title: string
  summary: string
  stillWorks: readonly string[]
  actionTo: string
  actionLabel: string
}) {
  return (
    <OperationalStatusCallout
      badge={badge}
      title={title}
      summary={summary}
      sections={[
        {
          title: 'What still works',
          items: stillWorks,
        },
        {
          title: 'What stays intentionally withheld',
          items: [
            'Direct package delivery remains intentionally withheld until the auth server returns.',
            'Live server-backed release authority is not claimed while this protected lane is in recovery mode.',
          ],
        },
        {
          title: 'Recommended recovery order',
          items: [
            'Wait for the auth server to recover, then refresh this protected lane before treating release metadata as live authority.',
            'Use operator support if recovery mode persists while rollout or entitlement work is blocked.',
          ],
        },
      ]}
      actions={[
        { label: actionLabel, to: actionTo },
        { label: 'Open protected launch status', to: '/app/launch-status' },
        { label: 'Open support', to: buildSupportPath('operator-access') },
      ]}
    />
  )
}

function ProtectedReleaseActionPanel({
  title,
  kicker,
  releaseManifest,
  requestedPlatform,
  releaseAuthorityUnavailable = false,
}: {
  title: string
  kicker: string
  releaseManifest: ReleaseManifestView
  requestedPlatform?: string | null
  releaseAuthorityUnavailable?: boolean
}) {
  const surface = buildProtectedReleaseActionSurface({
    releaseManifest,
    requestedPlatform,
    releaseAuthorityUnavailable,
  })

  return (
    <Panel title={title} kicker={kicker}>
      <p className={`status-pill${surface.tone === 'success' ? ' status-pill--success' : ' status-pill--info'}`}>
        {surface.badge}
      </p>
      <p><strong>{surface.title}</strong></p>
      <p>{surface.summary}</p>
      <ul className="list top-gap">
        {surface.items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
      <div className="button-row top-gap">
        {surface.actions.map((action) => (
          <ProtectedActionLink key={`${surface.badge}-${action.label}`} action={action} />
        ))}
      </div>
    </Panel>
  )
}

function ProtectedSupportTopicPanel({
  title,
  kicker,
  description,
  topicKey,
}: {
  title: string
  kicker: string
  description: string
  topicKey: string
}) {
  const topic = protectedSupportTopicGuides.find((item) => item.topicKey === topicKey)
  if (!topic) {
    return null
  }

  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        <article className="card card--compact">
          <p className="status-pill status-pill--info">{topic.title}</p>
          <p>{topic.description}</p>
          <ul className="list top-gap">
            {topic.steps.map((step) => (
              <li key={step}>{step}</li>
            ))}
          </ul>
          <div className="button-row top-gap">
            {topic.actions.map((action) => (
              <HyperTwistButtonLink key={`${topic.topicKey}-${action.label}`} tone="ghost" to={action.to}>
                {action.label}
              </HyperTwistButtonLink>
            ))}
          </div>
        </article>
      </div>
    </Panel>
  )
}

function ProtectedReleaseReferencesPanel({
  title,
  kicker,
  description,
  releaseManifest,
}: {
  title: string
  kicker: string
  description: string
  releaseManifest: ReleaseManifestView
}) {
  const supportEmail = releaseManifest.support_email || 'hello@hypertwist.app'

  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <ul className="list top-gap">
        <li>Public docs URL: {releaseManifest.public_docs_url || 'configure before launch'}</li>
        <li>Release notes URL: {releaseManifest.release_notes_url || 'configure before launch'}</li>
        <li>Corresponding-source URL: {releaseManifest.corresponding_source_url || 'configure before launch'}</li>
        <li>Public repository/notices URL: {releaseManifest.open_source_repo_url || 'configure before launch'}</li>
        <li>Operator support contact: {supportEmail}</li>
      </ul>
      <ReleaseAuthorityLinks
        releaseManifest={releaseManifest}
        includeProtectedLaunchStatusLink
        includeProtectedNoticesLink
        includePublicNoticesLink
      />
    </Panel>
  )
}

function PackagedValidationPanel({
  title,
  kicker,
  description,
  emptyMessage,
  releaseManifest,
}: {
  title: string
  kicker: string
  description: string
  emptyMessage: string
  releaseManifest: ReleaseManifestView
}) {
  const manifestWindowsTarget = findWindowsManifestTarget(releaseManifest)

  return (
    <Panel title={title} kicker={kicker}>
      {manifestWindowsTarget ? (
        <>
          <p>{description}</p>
          <ReleaseValidationSummary platform={manifestWindowsTarget} />
        </>
      ) : (
        <p className="form-error">{emptyMessage}</p>
      )}
    </Panel>
  )
}

function DesktopFirstLaunchChecklist({ title, kicker }: { title: string; kicker: string }) {
  return (
    <Panel title={title} kicker={kicker}>
      <div className="card-grid">
        {desktopFirstLaunchCards.map((card) => (
          <article key={card.title} className="card card--compact">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
    </Panel>
  )
}

function OperatorDesktopQuickstartPanel({
  title,
  kicker,
  description,
}: {
  title: string
  kicker: string
  description: string
}) {
  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        {operatorDesktopQuickstartCards.map((card) => (
          <article key={card.title} className="card card--compact">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
      <div className="button-row top-gap">
        <HyperTwistButtonLink tone="ghost" to="/app/downloads">
          Open downloads
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to="/app/browser-access">
          Open browser access
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to="/docs">
          Open public manual
        </HyperTwistButtonLink>
      </div>
    </Panel>
  )
}

function ProtectedSoftwareWorkflowPanel({
  title,
  kicker,
  description,
  limit,
}: {
  title: string
  kicker: string
  description: string
  limit?: number
}) {
  const cards = typeof limit === 'number' ? desktopWorkflowTracks.slice(0, limit) : desktopWorkflowTracks

  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        {cards.map((card) => (
          <article key={card.title} className="card card--compact">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.steps.map((step) => (
                <li key={step}>{step}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
      <div className="button-row top-gap">
        <HyperTwistButtonLink tone="ghost" to="/app/downloads">
          Open downloads
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to="/app/browser-access">
          Open browser access
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to="/docs">
          Open public manual
        </HyperTwistButtonLink>
      </div>
    </Panel>
  )
}

function SupportEscalationChecklist({
  title,
  kicker,
  description,
  secondaryLink,
}: {
  title: string
  kicker: string
  description: string
  secondaryLink: {
    to: string
    label: string
  }
}) {
  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        {supportEscalationCards.map((card) => (
          <article key={card.title} className="card card--compact">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ))}
      </div>
      <div className="button-row top-gap">
        <HyperTwistButtonLink tone="ghost" to={buildSupportPath('operator-access')}>
          Open support
        </HyperTwistButtonLink>
        <HyperTwistButtonLink tone="ghost" to={secondaryLink.to}>
          {secondaryLink.label}
        </HyperTwistButtonLink>
      </div>
    </Panel>
  )
}

function ProtectedOperatorQuickRoutesPanel({
  title,
  kicker,
  description,
}: {
  title: string
  kicker: string
  description: string
}) {
  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        {protectedSupportTopicGuides.map((topic) => (
          <article key={topic.topicKey} className="card card--compact">
            <h3>{topic.title}</h3>
            <p>{topic.description}</p>
            <ul className="list top-gap">
              {topic.steps.map((step) => (
                <li key={step}>{step}</li>
              ))}
            </ul>
            <div className="button-row top-gap">
              {topic.actions.map((action) => (
                <HyperTwistButtonLink key={`${topic.topicKey}-${action.label}`} tone="ghost" to={action.to}>
                  {action.label}
                </HyperTwistButtonLink>
              ))}
            </div>
          </article>
        ))}
      </div>
    </Panel>
  )
}

function ControlRosterManualPanel({
  title,
  kicker,
  description,
}: {
  title: string
  kicker: string
  description: string
}) {
  const xrBoundaryCard = inputAndDevicePostureCards.find(
    (card) => card.title === 'XR groundwork exists, but the full VR lane is not finished',
  )

  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        {controlProfileRosterCards.map((card) => (
          <article key={card.title} className="card card--compact">
            <h3>{card.title}</h3>
            <p>{card.description}</p>
            <ul className="list top-gap">
              {card.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ))}
        {xrBoundaryCard ? (
          <article className="card card--compact">
            <h3>{xrBoundaryCard.title}</h3>
            <p>{xrBoundaryCard.description}</p>
            <ul className="list top-gap">
              {xrBoundaryCard.bullets.map((bullet) => (
                <li key={bullet}>{bullet}</li>
              ))}
            </ul>
          </article>
        ) : null}
      </div>
    </Panel>
  )
}

function getProtectedRealityAction(cardAction: { to: string; label: string }) {
  if (cardAction.to === '/download') {
    return {
      to: '/app/downloads',
      label: 'Open downloads',
    }
  }

  if (cardAction.to === '/app') {
    return {
      to: '/app',
      label: 'Open dashboard',
    }
  }

  return cardAction
}

function ProtectedBrowserDesktopRealityPanel({
  title,
  kicker,
  description,
}: {
  title: string
  kicker: string
  description: string
}) {
  return (
    <Panel title={title} kicker={kicker}>
      <p>{description}</p>
      <div className="card-grid top-gap">
        {browserDesktopRealityCards.map((card) => {
          const action = getProtectedRealityAction(card.action)

          return (
            <article key={card.title} className="card card--compact">
              <p className="status-pill status-pill--info">{card.posture}</p>
              <h3>{card.title}</h3>
              <p>{card.description}</p>
              <ul className="list top-gap">
                {card.bullets.map((bullet) => (
                  <li key={bullet}>{bullet}</li>
                ))}
              </ul>
              <div className="button-row top-gap">
                <HyperTwistButtonLink tone="ghost" to={action.to}>
                  {action.label}
                </HyperTwistButtonLink>
              </div>
            </article>
          )
        })}
      </div>
    </Panel>
  )
}

export function DashboardOverviewPage() {
  const {
    user,
    superTokensConfigured,
    invalidateSession,
    releaseAuthoritySyncItems,
    releaseManifest,
    releaseManifestQuery,
  } = useProtectedReleaseSurface('dashboard')
  const healthQuery = useProtectedAuthHealthQuery('dashboard')

  const desktopLinkMutation = useMutation({
    mutationFn: createDesktopLinkToken,
    onError(error) {
      if (isUnauthorizedAuthApiError(error) && typeof invalidateSession === 'function') {
        invalidateSession('desktop_link_unauthorized')
      }
    },
  })

  const launchStatus = useMemo(() => (
    resolvePublicLaunchStatusSummary(
      healthQuery.data,
      releaseManifestQuery.data?.manifest,
      launchReadiness,
    )
  ), [healthQuery.data, releaseManifestQuery.data?.manifest])

  const verifyUrl = useMemo(() => {
    const token = desktopLinkMutation.data?.token
    if (!token) return ''
    const [baseUrl] = buildAuthApiBaseUrls()
    if (!baseUrl) return ''
    return `${baseUrl}/api/auth/desktop-link/verify?token=${encodeURIComponent(token)}`
  }, [desktopLinkMutation.data?.token])

  return (
    <>
      <SiteMetadata
        title="HyperTwist dashboard"
        description="Open the protected HyperTwist dashboard for account state, auth health, billing status, release readiness, and desktop-link pairing."
        canonicalPath="/app"
        robots="noindex,nofollow"
      />
      <div className="panel-grid">
        <Panel title="Account state" kicker="Live session">
          <p><strong>{user?.name}</strong></p>
          <p>{user?.email}</p>
          <p>Plan: {user?.plan}</p>
          <p>Role: {user?.role || 'operator'}</p>
          <p>Desktop downloads: {user?.canDownload ? 'enabled' : 'not yet entitled'}</p>
          {!superTokensConfigured || user?.billing?.source === 'local-fallback' ? (
            <p className="form-error">
              This session is currently using local recovery mode, not fully shared production auth.
            </p>
        ) : null}
        {releaseManifestQuery.data?.manifest && releaseAuthoritySyncItems.length > 0 ? (
          <div className="callout top-gap">
              <p className="status-pill status-pill--info">Live authority sync</p>
              <p>
                The protected browser session was refreshed from live release authority so the local dashboard view catches up to current account-access truth.
              </p>
              <ul className="list top-gap">
                {releaseAuthoritySyncItems.map((item) => (
                  <li key={item}>{item}</li>
                ))}
              </ul>
            </div>
          ) : null}
        </Panel>

      <ProtectedAuthSessionAuthorityPanel
        title="Auth and session authority"
        kicker="Browser shell"
        user={user}
        superTokensConfigured={superTokensConfigured}
        healthQuery={healthQuery}
      />

      <Panel title="Desktop-link pairing" kicker="Browser to desktop handoff">
        <p>Generate a short-lived token so the local desktop runtime can verify your browser session without exposing account credentials.</p>
        <HyperTwistButton
          type="button"
          onClick={() => desktopLinkMutation.mutate()}
          disabled={desktopLinkMutation.isPending}
        >
          {desktopLinkMutation.isPending ? 'Generating token...' : 'Generate desktop-link token'}
        </HyperTwistButton>
        {desktopLinkMutation.isError ? (
          <p className="form-error">Could not generate a token. Ensure the auth server is reachable and your session is valid.</p>
        ) : null}
        {desktopLinkMutation.data ? (
          <div className="code-block top-gap">
            <p>Token: <code>{desktopLinkMutation.data.token}</code></p>
            <p>Expires: {desktopLinkMutation.data.expires_at}</p>
            <p>Verify URL: <code>{verifyUrl || 'same-origin verify route'}</code></p>
          </div>
        ) : null}
      </Panel>

      <OperatorDesktopQuickstartPanel
        title="First simulator session"
        kicker="End-to-end operator manual"
        description="The protected dashboard now also condenses the real operator journey into one place so account state, desktop-link pairing, first launch, native training verification, and the current XR/controller boundary can be reviewed together instead of reconstructed from scattered cards."
      />

      <ProtectedSoftwareWorkflowPanel
        title="Software workflows after access is resolved"
        kicker="Protected simulator-use manual"
        description="The protected dashboard should also say what the installed software is actually for once access, pairing, and release status are already settled."
        limit={4}
      />

      <Panel title="Billing and entitlement state" kicker="Release access">
        <ul className="list">
          <li>Source: {user?.billing?.source || 'session'}</li>
          <li>Access status: {user?.billing?.accessStatus || 'session-default'}</li>
          <li>Desktop download access: {user?.billing?.canDownload ? 'enabled' : 'not yet enabled'}</li>
          <li>Last billing event: {user?.billing?.lastEventType || 'none recorded'}</li>
        </ul>
      </Panel>

      <ProtectedReleaseActionPanel
        title="Current release action"
        kicker="Protected access guidance"
        releaseManifest={releaseManifest}
        releaseAuthorityUnavailable={releaseManifestQuery.isError}
      />

      <ProtectedLaunchReadinessPanel
        title="Launch readiness"
        kicker="Public release configuration"
        authHealth={healthQuery.data}
        launchStatus={launchStatus}
        releaseManifestQuery={releaseManifestQuery}
        actions={[
          { label: 'Open protected launch status', to: '/app/launch-status' },
          { label: 'Open downloads', to: buildProtectedDownloadPath('windows') },
          { label: 'Open notices', to: '/app/notices' },
        ]}
      />

      <ProtectedOperatorQuickRoutesPanel
        title="Protected operator quick routes"
        kicker="Signed-in help lanes"
        description="These signed-in quick routes mirror the same launch, access, and rollout lanes exposed on the public support surface, but they now open the direct protected destinations instead of sending the operator back through auth first."
      />

      <ProtectedBrowserDesktopRealityPanel
        title="Protected browser-versus-desktop reality"
        kicker="Signed-in product boundary"
        description="Sign-in should not blur the same truth the public manual now states plainly: the browser lane handles account, release, and pairing work, the desktop runtime remains simulator authority, and headset/controller widening still requires packaged validation."
      />

      <PackagedValidationPanel
        title={protectedPackagedDesktopProofTitle}
        kicker="Desktop proof"
        description="This dashboard now surfaces the same server-backed Windows package proof that the public and protected release pages consume. That keeps higher-dimensional desktop validation truth separate from launch-tier checkout or download configuration."
        emptyMessage="The live release manifest did not return a Windows platform entry, so packaged desktop validation proof is unavailable here right now."
        releaseManifest={releaseManifest}
      />

      <ControlRosterManualPanel
        title="Native control and settings roster"
        kicker="Desktop runtime truth"
        description="This protected dashboard now mirrors the native operator and training inspect surfaces so signed-in users can see the shipped control profile, scenic presets, dedicated-family selectors, selector-recall continuity, and the still-bounded XR/controller line without opening the simulator first."
      />

      <DesktopFirstLaunchChecklist
        title="Desktop rollout follow-through"
        kicker="Post-download operator manual"
      />

      <Panel title="Current product-surface map" kicker="Operator orientation">
        <p>
          The protected dashboard is only one surface in the product. This shared map keeps account,
          embedded-browser, desktop-runtime, and future-branch truth visible without forcing operators to reconstruct topology from separate pages.
        </p>
        <div className="top-gap">
          <ProductSurfaceMatrix rows={productSurfaceMatrixRows} />
        </div>
      </Panel>

        <Panel title="Product boundary" kicker="Roadmap honesty">
          <ul className="list">
            {roadmapHonestyCards.map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        </Panel>
      </div>
    </>
  )
}

export function ProtectedLaunchStatusPage() {
  const {
    user,
    superTokensConfigured,
    releaseManifest,
    releaseManifestQuery,
  } = useProtectedReleaseSurface('launch-status')
  const healthQuery = useProtectedAuthHealthQuery('launch-status')

  const launchStatus = useMemo(() => (
    resolvePublicLaunchStatusSummary(
      healthQuery.data,
      releaseManifestQuery.data?.manifest,
      launchReadiness,
    )
  ), [healthQuery.data, releaseManifestQuery.data?.manifest])

  return (
    <>
      <SiteMetadata
        title="HyperTwist protected launch status"
        description="Review the signed-in HyperTwist launch-readiness status, release action, package proof, and rollout references."
        canonicalPath="/app/launch-status"
        robots="noindex,nofollow"
      />
      <div className="panel-grid">
        <ProtectedAuthSessionAuthorityPanel
          title="Auth and session authority"
          kicker="Launch dependency"
          user={user}
          superTokensConfigured={superTokensConfigured}
          healthQuery={healthQuery}
        />

        <ProtectedLaunchReadinessPanel
          title="Protected launch status"
          kicker="Signed-in rollout authority"
          description="This signed-in route keeps the live launch checklist, current targets, and rollout blockers in one operator-facing surface instead of leaving launch authority distributed across the dashboard and public pages."
          authHealth={healthQuery.data}
          launchStatus={launchStatus}
          releaseManifestQuery={releaseManifestQuery}
          actions={[
            { label: 'Open downloads', to: buildProtectedDownloadPath('windows') },
            { label: 'Open notices', to: '/app/notices' },
            { label: 'Open public launch status', to: '/launch-status' },
          ]}
        />

        <ProtectedReleaseActionPanel
          title="Current release action"
          kicker="Protected access guidance"
          releaseManifest={releaseManifest}
          releaseAuthorityUnavailable={releaseManifestQuery.isError}
        />

        <PackagedValidationPanel
          title={protectedPackagedDesktopProofTitle}
          kicker="Desktop proof"
          description="This protected launch route keeps rollout status anchored to the same Windows higher-dimensional package proof used by the public launch lane and the signed-in dashboard."
          emptyMessage="The current protected launch-status route could not find a Windows release target, so packaged desktop evidence is unavailable here right now."
          releaseManifest={releaseManifest}
        />

        <ProtectedSupportTopicPanel
          title="Launch-readiness support lane"
          kicker="Signed-in escalation"
          description="When rollout work turns from checklist review into action, this protected lane keeps the next signed-in destinations explicit."
          topicKey="launch-readiness"
        />

        <ProtectedReleaseReferencesPanel
          title="Launch references and notices"
          kicker="Distribution follow-through"
          description="Rollout status is only trustworthy when docs, release notes, corresponding source, public notices, and protected notices remain reachable from the same signed-in launch surface."
          releaseManifest={releaseManifest}
        />

        <ProtectedBrowserDesktopRealityPanel
          title="Protected browser-versus-desktop reality"
          kicker="Signed-in product boundary"
          description="Launch authority belongs to the browser shell because checkout, notices, and release references are browser-owned, while the real simulator still remains native and the XR/controller branch remains explicitly bounded."
        />
      </div>
    </>
  )
}

export function DownloadCenterPage() {
  const { user, canDownload, releaseManifest, releaseManifestQuery } = useProtectedReleaseSurface('protected')
  const [searchParams] = useSearchParams()
  const requestedPlatform = normalizeDownloadPlatform(searchParams.get('platform'))
  const orderedTargets = useMemo(() => {
    if (!requestedPlatform) {
      return releaseManifest.platforms
    }

    const prioritizedTarget = releaseManifest.platforms.find((target) => target.platform_key === requestedPlatform)
    if (!prioritizedTarget) {
      return releaseManifest.platforms
    }

    return [
      prioritizedTarget,
      ...releaseManifest.platforms.filter((target) => target.platform_key !== requestedPlatform),
    ]
  }, [releaseManifest.platforms, requestedPlatform])
  const requestedPlatformLabel = requestedPlatform ? getDownloadPlatformLabel(requestedPlatform) : null
  const viewerCanDownload = releaseManifest.viewer.canDownload || canDownload
  const releaseAuthorityUnavailable = releaseManifestQuery.isError

  return (
    <>
      <SiteMetadata
        title="HyperTwist downloads"
        description="Use the protected HyperTwist release surface to download entitled desktop builds, review release notes, and preserve your platform selection."
        canonicalPath="/app/downloads"
        robots="noindex,nofollow"
      />
      <div className="panel-grid">
        {releaseManifestQuery.isLoading ? (
          <Panel title="Release manifest status" kicker="Runtime authority">
            <p>Loading the current server-backed release manifest. Local recovery metadata remains visible until the live manifest arrives.</p>
          </Panel>
        ) : null}

        {releaseManifestQuery.isError ? (
          <Panel title="Release manifest status" kicker="Runtime authority">
            <ProtectedReleaseAuthorityNotice
              badge="Protected release recovery"
              title="The live release manifest could not be loaded from the auth server right now."
              summary="This panel is showing bounded recovery metadata instead of current runtime release authority, and direct package delivery remains intentionally withheld until the auth server returns."
              stillWorks={[
                'Requested platform targeting, packaged proof, and protected rollout guidance remain visible.',
                'Signed-in entitlement status can still be reviewed without pretending the unavailable manifest is live authority.',
              ]}
              actionTo="/app"
              actionLabel="Open dashboard"
            />
          </Panel>
        ) : null}

        <ProtectedReleaseActionPanel
          title="Current release action"
          kicker="Protected access guidance"
          releaseManifest={releaseManifest}
          requestedPlatform={requestedPlatform}
          releaseAuthorityUnavailable={releaseAuthorityUnavailable}
        />

        <Panel title="Release targets" kicker="Desktop distribution">
          {!viewerCanDownload ? (
            <p className="form-error">
              Your current account does not yet have desktop download entitlement.
              Complete the matching checkout or operator provisioning step, then refresh this dashboard.
            </p>
          ) : null}
          {releaseAuthorityUnavailable && viewerCanDownload ? (
            <div className="callout top-gap">
              <p className="status-pill status-pill--info">Release recovery mode</p>
              <p>
                Your signed-in account still resolves to desktop access, but live release authority is temporarily unavailable.
                Direct package delivery remains intentionally withheld until the auth server returns.
              </p>
            </div>
          ) : null}
          {requestedPlatformLabel ? (
            <div className="callout top-gap">
              <p className="status-pill status-pill--info">Requested target</p>
              <p>
                The browser handoff preserved your {requestedPlatformLabel} selection so you land on the matching protected release lane first.
              </p>
            </div>
          ) : null}
          <div className="card-grid">
            {orderedTargets.map((target) => {
              const metadataItems = buildReleaseMetadataItems(target)
              return (
                <article
                  key={target.platform}
                  className={`card card--compact${target.platform_key === requestedPlatform ? ' card--selected' : ''}`}
                >
                  <div className="status-row">
                    {target.platform_key === requestedPlatform ? (
                      <p className="status-pill status-pill--info">Requested target</p>
                    ) : null}
                    <p className="status-pill">{target.subtitle}</p>
                  </div>
                  <h3>{target.platform}</h3>
                  <p>{target.details}</p>
                  {metadataItems.length > 0 ? (
                    <ul className="list top-gap">
                      {metadataItems.map((item) => (
                        <li key={`${target.platform_key}-${item.label}`}>
                          {item.label}: {item.value}
                        </li>
                      ))}
                    </ul>
                  ) : null}
                  <ReleaseValidationSummary platform={target} />
                  {target.download_url && viewerCanDownload ? (
                    <HyperTwistButtonAnchor className="button--full" href={target.download_url}>
                      Download {target.platform}
                    </HyperTwistButtonAnchor>
                  ) : (
                    <div className="button button--ghost button--full is-disabled" aria-disabled="true">
                      {getProtectedDownloadActionLabel({
                        configured: target.configured,
                        viewerCanDownload,
                        releaseAuthorityUnavailable,
                      })}
                    </div>
                  )}
                </article>
              )
            })}
          </div>
        </Panel>

        <Panel title="Release guide" kicker="Operator onboarding">
          <ul className="list">
            {desktopDownloadSteps.map((step) => (
              <li key={step}>{step}</li>
            ))}
          </ul>
          <ReleaseAuthorityLinks
            releaseManifest={releaseManifest}
            includeProtectedLaunchStatusLink
            includePublicNoticesLink
            includeProtectedNoticesLink
          />
        </Panel>

        <ProtectedSoftwareWorkflowPanel
          title="What the downloaded software already supports"
          kicker="Protected simulator-use manual"
          description="Protected package access is more useful when the same route also teaches the real desktop workflows that follow immediately after install."
          limit={4}
        />

        <ProtectedOperatorQuickRoutesPanel
          title="Protected operator quick routes"
          kicker="Signed-in help lanes"
          description="These quick routes keep the entitled download surface aligned with the same launch, access, and rollout lanes used across the broader protected operator shell."
        />

        <ProtectedBrowserDesktopRealityPanel
          title="Protected browser-versus-desktop reality"
          kicker="Signed-in product boundary"
          description="Entitled download access should not make the browser shell sound like simulator parity. This panel keeps the operator-facing access lane, native runtime authority, and unfinished XR/controller boundary explicit."
        />

        <PackagedValidationPanel
          title={protectedPackagedDesktopProofTitle}
          kicker="Protected release evidence"
          description="This protected download center now mirrors the same Windows packaged-validation proof used across the public and protected release surfaces so entitled package access stays tied to real native evidence."
          emptyMessage="The protected download center could not find a Windows release target, so packaged desktop proof is unavailable here right now."
          releaseManifest={releaseManifest}
        />

        <DesktopFirstLaunchChecklist
          title="First launch follow-through"
          kicker="Desktop setup"
        />

        <SupportEscalationChecklist
          title="Download and rollout escalation"
          kicker="Keep account, package, runtime, and compliance issues separated"
          description="Use the same bounded escalation map here so signed-in operators can distinguish entitlement trouble, package trouble, runtime regressions, and rollout/compliance work before escalating."
          secondaryLink={{ to: '/app/notices', label: 'Review notices' }}
        />

        <Panel title="Current product-surface map" kicker="Protected operator orientation">
          <p>
            The entitled download lane is only one part of the product. Keep the browser dashboard,
            embedded browser shell, native runtime, and still-frozen browser branch separated so release actions do not drift into the wrong surface.
          </p>
          <div className="top-gap">
            <ProductSurfaceMatrix rows={productSurfaceMatrixRows} />
          </div>
        </Panel>
      </div>
    </>
  )
}

export function BrowserAccessPage() {
  const { user, releaseManifest, releaseManifestQuery } = useProtectedReleaseSurface('browser-access')
  const healthQuery = useProtectedAuthHealthQuery('browser-access')
  const configuredPlatformCount = useMemo(
    () => releaseManifest.platforms.filter((platform) => platform.configured).length,
    [releaseManifest.platforms],
  )

  return (
    <>
      <SiteMetadata
        title="HyperTwist browser access"
        description="Review the HyperTwist browser-access boundary, embedded browser role, and the still-future optional full-browser branch."
        canonicalPath="/app/browser-access"
        robots="noindex,nofollow"
      />
      <div className="panel-grid">
        <Panel title="Current browser role" kicker="Shipping lane">
          <ul className="list">
            <li>The embedded browser/CEF shell is live and owned as part of the current shipping model.</li>
            <li>Browser runtime status, runtime-ready typing, and native operator diagnostics are already surfaced in the desktop runtime.</li>
            <li>The public browser dashboard is for operator/account/release access, not a claim of full simulator parity.</li>
          </ul>
          {healthQuery.isLoading ? <p>Checking current browser-shell auth state...</p> : null}
        {healthQuery.isError ? (
            <OperationalStatusCallout
              badge="Browser access fallback"
              title="Runtime auth-health could not be loaded."
              summary="The page is still using the bounded dashboard role rather than claiming browser-simulator parity."
              sections={[
                {
                  title: 'What still works',
                  items: [
                    'Browser-to-desktop handoff guidance and native packaged proof remain visible.',
                    'The signed-in browser shell can still orient the operator without claiming simulator parity.',
                  ],
                },
                {
                  title: 'Recommended recovery order',
                  items: [
                    'Restore auth-health reachability before treating this route as live browser-session authority.',
                  ],
                },
              ]}
            />
          ) : null}
          {healthQuery.data ? (
            <ul className="list top-gap">
              <li>Auth runtime mode: {healthQuery.data.runtime.mode}</li>
              <li>Public auth origin ready: {healthQuery.data.runtime.public_origin_ready ? 'yes' : 'no'}</li>
              <li>Fallback currently active: {healthQuery.data.fallback.active ? 'yes' : 'no'}</li>
              <li>Session plan: {user?.plan || 'not resolved yet'}</li>
              <li>Desktop download entitlement: {user?.canDownload ? 'enabled' : 'not yet entitled'}</li>
            </ul>
          ) : null}
        </Panel>
        <Panel title="Browser-to-desktop handoff" kicker="Operator workflow">
          <p>
            The browser shell exists to resolve account, release, and pairing state before the desktop runtime takes over the real simulator job.
          </p>
          <ul className="list top-gap">
            {desktopDownloadSteps.map((step) => (
              <li key={step}>{step}</li>
            ))}
          </ul>
          <div className="button-row top-gap">
            <HyperTwistButtonLink tone="ghost" to="/app">
              Open dashboard
            </HyperTwistButtonLink>
            <HyperTwistButtonLink tone="ghost" to="/app/downloads">
              Open downloads
            </HyperTwistButtonLink>
          </div>
        </Panel>
        <ProtectedSoftwareWorkflowPanel
          title="Desktop workflows behind the browser handoff"
          kicker="Protected simulator-use manual"
          description="Once browser access has done its job, these are the actual desktop workflows HyperTwist already supports today."
          limit={4}
        />
        <ProtectedReleaseActionPanel
          title="Current release action"
          kicker="Protected access guidance"
          releaseManifest={releaseManifest}
          releaseAuthorityUnavailable={releaseManifestQuery.isError}
        />
        <ProtectedBrowserDesktopRealityPanel
          title="Protected browser-versus-desktop reality"
          kicker="Signed-in product boundary"
          description="This route exists to explain and support the handoff, not to overclaim browser simulator parity. The same blunt surface split and XR truth now stay visible after sign-in as well."
        />
        <ControlRosterManualPanel
          title="Native control and XR boundary"
          kicker="Desktop handoff truth"
          description="This protected browser route keeps the simulator handoff honest by showing what the native runtime already owns today and where the later XR/controller completion packet still begins."
        />
        <Panel title="Release authority around the browser shell" kicker="Distribution context">
        {releaseManifestQuery.isError ? (
            <ProtectedReleaseAuthorityNotice
              badge="Browser-access release recovery"
              title="Live release-manifest lookup failed."
              summary="Browser-shell release context is currently using recovery metadata instead of current auth-server authority."
              stillWorks={[
                'Browser-to-desktop handoff guidance, packaged proof, and support references remain available.',
                'This route can still show the bounded browser-shell role without claiming live release authority.',
              ]}
              actionTo="/app"
              actionLabel="Open dashboard"
            />
          ) : null}
          <ul className="list">
            <li>Configured release targets: {configuredPlatformCount}/{releaseManifest.platforms.length}</li>
            <li>Manifest viewer access: {releaseManifest.viewer.accessStatus || 'not resolved yet'}</li>
            <li>Support contact: {releaseManifest.support_email}</li>
          </ul>
          <ReleaseAuthorityLinks
            releaseManifest={releaseManifest}
            includeProtectedLaunchStatusLink
            includeProtectedNoticesLink
          />
        </Panel>
        <PackagedValidationPanel
          title={protectedPackagedDesktopProofTitle}
          kicker="Browser-to-desktop release evidence"
          description="This protected browser route mirrors the current Windows package proof so account access, pairing, and browser-to-desktop handoff stay anchored to the real native release lane instead of sounding like a browser-only simulator claim."
          emptyMessage="The current protected browser route could not find a Windows release target, so native packaged-validation proof is unavailable here right now."
          releaseManifest={releaseManifest}
        />
        <SupportEscalationChecklist
          title="Operator escalation map"
          kicker="Keep browser, package, runtime, and rollout issues separated"
          description="Use the same bounded escalation map as the public support lane so protected browser access does not collapse access problems, package problems, runtime regressions, and rollout/compliance questions into one vague bucket."
          secondaryLink={{ to: '/app/notices', label: 'Review notices' }}
        />
        <Panel title="Optional branches remain bounded" kicker="Not widened here">
          <ul className="list">
            <li>The optional full-browser client remains spec-only.</li>
            <li>MagicTile native renderer widening remains closed unless a real browser-host gap is proven.</li>
            <li>This dashboard intentionally stays above those boundaries instead of silently crossing them.</li>
          </ul>
          <ul className="list top-gap">
            {roadmapHonestyCards.map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        </Panel>
      </div>
    </>
  )
}

export function AccountPage() {
  const {
    user,
    superTokensConfigured,
    releaseAuthoritySyncItems,
    releaseManifest,
    releaseManifestQuery,
  } = useProtectedReleaseSurface('account')
  const healthQuery = useProtectedAuthHealthQuery('account')
  const configuredPlatforms = useMemo(
    () => releaseManifest.platforms.filter((platform) => platform.configured),
    [releaseManifest.platforms],
  )

  return (
    <>
      <SiteMetadata
        title="HyperTwist account"
        description="Inspect your protected HyperTwist account profile, plan, billing status, and auth stack mode."
        canonicalPath="/app/account"
        robots="noindex,nofollow"
      />
      <div className="panel-grid">
        <Panel title="Session profile" kicker="Account details">
          <ul className="list">
            <li>Email: {user?.email}</li>
            <li>Name: {user?.name}</li>
            <li>Plan: {user?.plan}</li>
            <li>Role: {user?.role || 'operator'}</li>
            <li>Desktop downloads: {user?.canDownload ? 'enabled' : 'not yet entitled'}</li>
            <li>Billing status: {user?.billing?.accessStatus || 'session-default'}</li>
            <li>Billing source: {user?.billing?.source || 'session'}</li>
          </ul>
          {releaseManifestQuery.data?.manifest && releaseAuthoritySyncItems.length > 0 ? (
            <div className="callout top-gap">
              <p className="status-pill status-pill--info">Live authority sync</p>
              <p>
                The protected browser session was refreshed from live release authority so the local account snapshot matches current release-access truth.
              </p>
              <ul className="list top-gap">
                {releaseAuthoritySyncItems.map((item) => (
                  <li key={item}>{item}</li>
                ))}
              </ul>
            </div>
          ) : null}
        </Panel>
        <ProtectedAuthSessionAuthorityPanel
          title="Auth and session authority"
          kicker="Protected browser identity"
          user={user}
          superTokensConfigured={superTokensConfigured}
          healthQuery={healthQuery}
        />
        <Panel title="Entitlement and release access" kicker="Protected release lane">
          {releaseManifestQuery.isLoading ? <p>Refreshing release-access status from the live manifest...</p> : null}
        {releaseManifestQuery.isError ? (
            <ProtectedReleaseAuthorityNotice
              badge="Account release recovery"
              title="Live release-manifest lookup failed."
              summary="This account view is using bounded recovery metadata until auth-server release authority returns."
              stillWorks={[
                'Signed-in profile, entitlement status, and packaged proof remain visible.',
                'Protected follow-through links still keep account, download, notices, and support separated.',
              ]}
              actionTo="/app"
              actionLabel="Open dashboard"
            />
          ) : null}
          <ul className="list">
            <li>Manifest viewer authenticated: {releaseManifest.viewer.authenticated ? 'yes' : 'no'}</li>
            <li>Manifest viewer plan: {releaseManifest.viewer.plan || user?.plan || 'not resolved yet'}</li>
            <li>Manifest viewer access: {releaseManifest.viewer.accessStatus || 'not resolved yet'}</li>
            <li>Configured release targets: {configuredPlatforms.length}/{releaseManifest.platforms.length}</li>
          </ul>
          {configuredPlatforms.length > 0 ? (
            <ul className="list top-gap">
              {configuredPlatforms.map((platform) => {
                const metadataItems = buildReleaseMetadataItems(platform)
                const compactMetadata = metadataItems.slice(0, 2).map((item) => `${item.label} ${item.value}`).join(', ')
                return (
                  <li key={platform.platform_key}>
                    {platform.platform}: {platform.subtitle}{compactMetadata ? ` (${compactMetadata})` : ''}
                  </li>
                )
              })}
            </ul>
          ) : null}
        </Panel>

        <ProtectedReleaseActionPanel
          title="Current release action"
          kicker="Protected access guidance"
          releaseManifest={releaseManifest}
          releaseAuthorityUnavailable={releaseManifestQuery.isError}
        />

        <PackagedValidationPanel
          title={protectedPackagedDesktopProofTitle}
          kicker="Release evidence"
          description="Entitlement and manifest access stay more trustworthy when the same protected account route also exposes the current Windows packaged proof for the higher-dimensional desktop runtime."
          emptyMessage="The current protected account route could not find a Windows release target, so packaged desktop evidence is unavailable here right now."
          releaseManifest={releaseManifest}
        />
        <ProtectedBrowserDesktopRealityPanel
          title="Protected browser-versus-desktop reality"
          kicker="Signed-in product boundary"
          description="Account status should not make the browser shell sound like simulator ownership. This signed-in account route keeps the same explicit browser-versus-desktop split visible while plan, entitlement, and release-access state are being reviewed."
        />
        <ControlRosterManualPanel
          title="Current simulator control ownership"
          kicker="Signed-in runtime state"
          description="Your account and entitlement state matter here, but the real simulator still lives on the desktop side. This roster keeps the current control/settings truth visible after sign-in instead of dropping back to a thinner account-only shell."
        />
        <Panel title="Account follow-through" kicker="Next actions">
          <p>
            Use the dashboard when you need a desktop-link token, the download center when you need an entitled package, and the notices lane when you need distribution/legal references.
          </p>
          <div className="button-row top-gap">
            <HyperTwistButtonLink tone="ghost" to="/app">
              Open dashboard
            </HyperTwistButtonLink>
            <HyperTwistButtonLink tone="ghost" to="/app/downloads">
              Open downloads
            </HyperTwistButtonLink>
            <HyperTwistButtonLink tone="ghost" to="/app/notices">
              Review notices
            </HyperTwistButtonLink>
            <HyperTwistButtonLink tone="ghost" to={buildSupportPath('operator-access')}>
              Get help
            </HyperTwistButtonLink>
          </div>
          <ReleaseAuthorityLinks
            releaseManifest={releaseManifest}
            includeProtectedLaunchStatusLink
            includeProtectedNoticesLink
          />
        </Panel>

        <ProtectedSoftwareWorkflowPanel
          title="Desktop workflows available to this account"
          kicker="Protected simulator-use manual"
          description="Account, plan, and entitlement status exist to unlock real native workflows. This panel keeps those practical simulator uses visible after sign-in."
          limit={4}
        />

        <DesktopFirstLaunchChecklist
          title="Desktop access follow-through"
          kicker="After sign-in"
        />
      </div>
    </>
  )
}

export function NoticesPage() {
  const { releaseManifest, releaseManifestQuery } = useProtectedReleaseSurface('notices')
  const configuredPlatforms = useMemo(
    () => releaseManifest.platforms.filter((platform) => platform.configured),
    [releaseManifest.platforms],
  )

  return (
    <>
      <SiteMetadata
        title="HyperTwist notices"
        description="Review the protected HyperTwist distribution notices and corresponding-source requirements for downloadable builds."
        canonicalPath="/app/notices"
        robots="noindex,nofollow"
      />
      <div className="panel-grid">
        <Panel title="Distribution notices" kicker="Legal follow-through">
          <p>
            Pricing, checkout, and download surfaces must expose open-source notices and corresponding-source guidance whenever shipped builds contain MPL-covered material.
          </p>
          {releaseManifestQuery.isLoading ? <p>Refreshing notices status from the live release manifest...</p> : null}
          {releaseManifestQuery.isError ? (
            <ProtectedReleaseAuthorityNotice
              badge="Notices recovery"
              title="Live release-manifest lookup failed."
              summary="This page is using bounded recovery notice metadata until auth-server release authority returns."
              stillWorks={[
                'Protected notice references, corresponding-source status, and packaged proof remain visible.',
                'Operators can still keep distribution work separate from runtime and entitlement work while authority recovers.',
              ]}
              actionTo="/app/downloads"
              actionLabel="Open downloads"
            />
          ) : null}
          <ul className="list top-gap">
            <li>Configured release targets: {configuredPlatforms.length}/{releaseManifest.platforms.length}</li>
            <li>Viewer download access: {releaseManifest.viewer.canDownload ? 'enabled' : 'not yet enabled'}</li>
            <li>Public repository/notices URL: {releaseManifest.open_source_repo_url || 'add the public repository/notices URL before wider launch'}</li>
            <li>Corresponding-source URL: {releaseManifest.corresponding_source_url || 'add the corresponding-source URL before wider launch'}</li>
          </ul>
        </Panel>
        <ProtectedReleaseActionPanel
          title="Current release action"
          kicker="Protected access guidance"
          releaseManifest={releaseManifest}
          releaseAuthorityUnavailable={releaseManifestQuery.isError}
        />
        <Panel title="Operator obligations" kicker="Keep aligned">
          <ul className="list">
            <li>Keep pricing, download, and notices surfaces aligned whenever a public downloadable build is offered.</li>
            <li>Keep release notes and package proof reachable so public audiences can see what build state is actually being distributed.</li>
            <li>Do not present browser access as simulator parity just because distribution/legal pages are live.</li>
          </ul>
          {releaseManifest.platforms.length > 0 ? (
            <ul className="list top-gap">
              {releaseManifest.platforms.map((platform) => (
                <li key={platform.platform_key}>
                  {platform.platform}: {platform.configured ? 'published' : 'pending publication'}{platform.validation_summary ? `, validation ${platform.validation_summary.result}` : ''}
                </li>
              ))}
            </ul>
          ) : null}
        </Panel>
        <PackagedValidationPanel
          title={protectedPackagedDesktopProofTitle}
          kicker="Distribution evidence"
          description="This protected notices lane now keeps the downloadable release story tied to the current Windows desktop package proof instead of only naming validation abstractly. That makes notices, corresponding source, and package status easier to read together."
          emptyMessage="The current protected notices route could not find a Windows release target, so packaged desktop evidence is unavailable here right now."
          releaseManifest={releaseManifest}
        />
        <ProtectedBrowserDesktopRealityPanel
          title="Protected browser-versus-desktop reality"
          kicker="Distribution boundary"
          description="Distribution and compliance work should not blur the same product split either. This protected notices route keeps the browser-support role, native simulator authority, and unfinished XR/controller boundary explicit while operators review downloadable release obligations."
        />
        <Panel title="Reference surfaces" kicker="Release references">
          <p>
            Operators should keep public notices, protected notices, release notes, and corresponding source reachable from the same release story.
          </p>
          <ReleaseAuthorityLinks
            releaseManifest={releaseManifest}
            includeProtectedLaunchStatusLink
            includeProtectedNoticesLink
            includePublicNoticesLink
          />
        </Panel>
        <SupportEscalationChecklist
          title="Escalation and release follow-through"
          kicker="Protected operator manual"
          description="When distribution or compliance work is underway, support should still separate entitlement, package, runtime, and rollout problems while keeping the protected notices lane tied to the same release story as download, support, and corresponding source."
          secondaryLink={{ to: '/app/downloads', label: 'Open downloads' }}
        />
      </div>
    </>
  )
}
