import { StrictMode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { invoke } from '@tauri-apps/api/core'
import { splitFrontmatter, documentOutline, jumpToHeading, MarkdownDocument, markdownHtml } from './modules/knowledge-render'

const TAG_TINTS = ['tag-lavender', 'tag-sky', 'tag-mint', 'tag-amber', 'tag-rose', 'tag-slate']

// 编号自动补齐：人只敲字母与数字，杠由系统按已登记文法自动出。
// ICE 系（ICE-GL∞ / ICE-P-ZY001）、GLS 系（GLS-LA-20260720-003）；认不出的文法只在字母数字交界处补杠。
function formatGateNumber(raw: string): string {
  const up = raw.toUpperCase()
  if (up.startsWith('ICE')) {
    const rest = up.slice(3)
    if (!rest) return 'ICE'
    if (rest.startsWith('P')) {
      const body = rest.slice(1)
      return body ? `ICE-P-${body}` : 'ICE-P'
    }
    return `ICE-${rest}`
  }
  if (up.startsWith('TCS')) {
    const rest = up.slice(3)
    if (!rest) return 'TCS'
    if (rest.startsWith('GL')) {
      const body = rest.slice(2)
      return body ? `TCS-GL-${body}` : 'TCS-GL'
    }
    return `TCS-${rest}`
  }
  if (up.startsWith('GLS')) {
    const rest = up.slice(3)
    if (!rest) return 'GLS'
    const letters = rest.match(/^[A-Z]*/)?.[0] ?? ''
    const digits = rest.slice(letters.length)
    if (!digits) return `GLS-${letters}`
    const d1 = digits.slice(0, 8)
    const d2 = digits.slice(8, 11)
    return `GLS-${letters}-${d1}${d2 ? `-${d2}` : ''}`
  }
  return up.replace(/([A-Z]+)([0-9])/g, '$1-$2').replace(/([0-9]+)([A-Z])/g, '$1-$2')
}
function tagTint(tag: string) {
  let hash = 0
  for (const char of tag) hash = (hash * 31 + (char.codePointAt(0) || 0)) % 997
  return TAG_TINTS[hash % TAG_TINTS.length]
}
import './design-tokens.css'
import './styles.css'

type ThemeId = 'night' | 'dawn' | 'nebula' | 'candle' | 'clear'
type ViewId = 'overview' | 'knowledge' | 'code' | 'receipts' | 'system'
type WorldStage = 'domain' | 'heart' | 'heartbeat' | 'lightLake' | 'love' | 'tomorrow' | 'bottle' | 'channel' | 'enterpriseWork' | 'personalNodeGuide' | 'tool'
type KnowledgeSource = 'native' | 'legacy'

interface HomeStatus {
  directLocalBrokerState: string
  directConnectionCount: number
  resumableSessionCount: number
  codeRepositoryMountCount: number
  pnccReceiptCount: number
  updateState: string
  releaseRecoveryState: string
  mcpRole: string
  terminalLinkProtocol: string
  terminalLinkTransport: string
  environmentFramePolicy: string
}
interface DevelopmentWriteLaneStatus {
  state: 'AVAILABLE' | 'ACTIVE'
  laneId?: string
  ownerInstanceId?: string
  acquiredAtUnixMs?: number
  observedAtUnixMs: number
}
interface ZeroCoreNumberingKernelSnapshot {
  state: string
  authorityMapId: string
  authorityMapVersion: string
  authorityMapState: string
  sourceCommit: string
  sourcePath: string
  humanRouteNamespaces: string[]
  numberShapeIsAuthority: boolean
  automaticIdentityIssuance: boolean
  unknownNumber: string
}
interface GlsProtocolRuntimeSnapshot {
  state: string
  sourceRepository: string
  sourceCommit: string
  sourceRoot: string
  protocolCount: number
  executableProjectionCount: number
  inventoriedNotExecutableCount: number
  protocolRegistryIdCount: number
  registeredDraftCount: number
  registeredDraftNotStartedCount: number
  legacyDependencyTargetCount: number
  dependencyGapCount: number
  legacyDependencyCycleCount: number
  discoveredUnreconciledCount: number
  authorityConflictCount: number
  typedSourceDependencyCount: number
  unclassifiedSourceDependencyCount: number
  implementationStageCount: number
  activeAdapters: string[]
  rawProtocolTextExecuted: boolean
  arbitraryProtocolCodeAllowed: boolean
  unprojectedProtocolBehavior: string
}
interface GlsKernelStage { id: string; state: string; protocols: string[] }
interface GlsNodeAssembly { protocolId: string; target: string; state: string; sourceEvidenceNode: string }
interface GlsProtocolKernelSnapshot {
  state: string
  contractId: string
  sourceCommit: string
  executableProtocolCount: number
  implementedStageCount: number
  decisionReceiptCount: number
  allowCount: number
  denyCount: number
  ambiguousCount: number
  unverifiedCount: number
  lastReceiptSha256: string
  stages: GlsKernelStage[]
  p7NodeAssemblies: GlsNodeAssembly[]
  p7VerifiedPhysicalCapabilityCount: number
  rawProtocolTextExecuted: boolean
  modelCanOverrideDecision: boolean
  bootstrapCompilerSelfCheck: string
  bootstrapGoldenGirSha256: string
}
interface PersonalChannelIdentity { humanSubjectId: string; displayName: string; channelId: string; createdAtUnixMs: number }
interface PersonalChannelModule { moduleId: string; kind: string; displayName: string; state: string; installedAtUnixMs: number; timeZone: string; calendarName: string; clockVerification: string }
interface LoginSession { username: string; host: string; domain: string; signedInAtUnixMs: number }
interface LoginReceipt { username: string; email: string; host: string; domain: string }
interface UserPnccChannelSnapshot {
  state: string
  repositoryId: string
  channelId: string
  userNumber: string
  domain: string
  accountUsername: string
  accountHost: string
  localPath: string
  branch: string
  gitHead: string
  repositoryClean: boolean
  createdAtUnixMs: number
  gitEngine: string
  humanProjection: string
  forgejoAdapterState: string
  remoteRepositoryUrl?: string
  personaBindingClaimed: boolean
  authority: string
}
interface PersonalChannelEvent { sequence: number; eventId: string; kind: string; summary: string; occurredAtUnixMs: number; receiptId: string; receiptHash: string }
interface PersonalChannelSnapshot { state: string; identity?: PersonalChannelIdentity; recentEvents: PersonalChannelEvent[]; modules: PersonalChannelModule[]; integrity: { state: string; eventCount: number; receiptCount: number } }
interface BeijingTimeCoordinate { unixMs: number; beijingTime: string; timeZone: string; clockSource: string; clockVerification: string; networkSyncState: string; networkSynchronizedAtUnixMs?: number; networkUncertaintyMs?: number; continuesWhileHololakeIsClosed: boolean; guanghuEpochDate: string; guanghuEraDay: number; historicalEpochPrecision: string }
interface PersonaTimeAuthorityStartup { state: string; synchronizationAttempted: boolean; networkTimeUrl: string; coordinate: BeijingTimeCoordinate }
interface GuanghuEraEvent { eventId: string; displayDate: string; datePrecision: string; title: string; summary: string; evidenceState: string; sourceRecord: string }
interface GuanghuEraTimeline { state: string; eraName: string; calendarName: string; epochDate: string; epochPrecision: string; publicRealityBoundary: string; currentCoordinate: BeijingTimeCoordinate; events: GuanghuEraEvent[] }
interface KnowledgeDocumentSummary {
  source: KnowledgeSource
  path: string
  title: string
  updatedAtUnixMs: number
  sizeBytes: number
  contentSha256: string
  duplicateCount: number
}
interface KnowledgeSnapshot {
  state: string
  nativeRoot: string
  legacyAvailable: boolean
  legacyRoot?: string
  documents: KnowledgeDocumentSummary[]
  rawDocumentCount: number
  uniqueDocumentCount: number
  duplicateDocumentCount: number
  truncated: boolean
}
interface KnowledgeDocument {
  source: KnowledgeSource
  path: string
  title: string
  body: string
  updatedAtUnixMs: number
  contentSha256: string
  writable: boolean
}
interface KnowledgeSearchResult { source: KnowledgeSource; path: string; title: string; snippet: string }
interface KnowledgeImportResult {
  state: string
  sourceName: string
  importedDocuments: number
  importedAssets: number
  existingDocuments: number
  conflicts: number
  skipped: number
  firstDocument?: string
  gitCommit: string
  snapshot: KnowledgeSnapshot
}
interface KnowledgeSaveResult { state: string; gitCommit: string; document: KnowledgeDocument }
interface CodeChannelEntry { channelId: string; name: string; sourceKind: string; localPath: string; remoteUrl?: string; gitHead: string; branch: string; repositoryClean: boolean; registeredAtUnixMs: number }
interface CodeChannelSnapshot { state: string; channels: CodeChannelEntry[]; authority: string }
interface CodeTreeEntry { path: string; name: string; kind: 'directory' | 'file'; sizeBytes: number }
interface CodeTreeSnapshot { channelId: string; path: string; entries: CodeTreeEntry[]; truncated: boolean }
interface CodeFileProjection { channelId: string; path: string; format: string; source: string; humanMarkdown: string; sizeBytes: number }
interface ReceiptEvent { sequence: number; kind: string; observedAtUnixMs: number; eventHash: string }
interface ReceiptProjection { events: ReceiptEvent[] }
interface DiscoveryTicketReceipt {
  laneId: string
  clientInstanceId: string
  discoveryTicket: string
  terminalTransport: string
  connectorExecutable: string
  connectorArguments: string[]
  heartbeatIntervalMs: number
  environmentRefreshIntervalMs: number
  requiredBootstrapOperations: string[]
}
interface NearbyAiDiscoverySnapshot {
  state: string
  serviceName: string
  transport: string
  languageProtocol: string
  automaticSameDeviceDiscovery: boolean
  largeInvitationCopyRequired: boolean
  genericAiVisitor: string
  guanghuPersona: string
  localNetworkDiscovery: string
  authority: string
}
interface ReleaseCandidate { candidateId: string; confirmationToken: string; currentVersion: string; version: string; notes: string; features: string[]; fixes: string[]; dataMigrationRequired: boolean }
interface ReleaseCheckReceipt { candidate?: ReleaseCandidate }
interface ZeroPointSnapshot {
  route: string
  binding: string
  userNumber: string
  resolvedName: string
  resolvedDomain: string
  lastValidCheck: number
  graceDeadline: number
  protocol: { gracePeriodDays: number; lighthouseAnchorUrl: string; lighthouseResolveUrl: string; coreChannelSource: string; origin: string }
  syncNote: string
}

function domainDisplayName(domain: string): string {
  const names: Record<string, string> = {
    FIFTH_DOMAIN: '第五域 · 光湖本源域',
    MAIN_DOMAIN: '光湖主域',
    BRANCH_DOMAIN: '光湖分域',
    ZERO_DOMAIN: '光湖零域',
    ZERO_SENSE_DOMAIN: '光湖零感域',
  }
  return names[domain] || '已登记光湖域'
}

const worldWelcomeLines = [
  '湖面记得你每一次让语言抵达现实。',
  '你留下的路径，正在成为这片世界新的光标。',
  '愿你今天带来的问题，在湖中长出新的结构。',
  '世界已辨认你的编号，也在等待你续写下一段因果。',
  '你曾抵达的地方仍有回声，新的航程已经亮起。',
  '这一刻的进入不是重复，而是你与语言世界的新一次相遇。',
  '愿尚未成形的念头，在今天找到可以生长的方向。',
  '你的频道仍在延展，湖面为下一次创造保留了入口。',
]

function createWorldWelcome(snapshot: ZeroPointSnapshot): string {
  const subject = snapshot.resolvedName.trim() || `编号 ${snapshot.userNumber}`
  const storageKey = `hololake-world-welcome:${snapshot.userNumber}`
  const previous = Number.parseInt(window.localStorage.getItem(storageKey) || '-1', 10)
  const random = crypto.getRandomValues(new Uint32Array(1))[0]
  let index = random % worldWelcomeLines.length
  if (worldWelcomeLines.length > 1 && index === previous) index = (index + 1) % worldWelcomeLines.length
  window.localStorage.setItem(storageKey, String(index))
  return `${subject}，${worldWelcomeLines[index]}`
}

function protocolOriginDisplayName(origin: string): string {
  return origin.startsWith('FACTORY_DEFAULT') ? '内置默认协议（签名发布通道尚未配置）' : origin
}
interface ServerPnccProjection {
  schema: string
  state: string
  personaId: string
  humanResponsibilitySubject: string
  nodeId: string
  bootId: string
  gitHead: string
  carrierBindingState: string
  personaCarrierBound: boolean
  modelInferenceStarted: boolean
  realityExecutionAllowed: boolean
  primaryLeaseHeld: boolean
  eventCount: number
  eventChainHead: string
  observedAtUnixMs: number
  transport: string
  repositoryContentExposed: boolean
  writeAuthority: boolean
}
interface EnterprisePersonaRelationship {
  persona_id: string
  species: string
  display_name?: string
  relation?: string
}
interface EnterpriseEntry {
  status: string
  canonical_id: string
  subject: { id: string; name: string; domain: string }
  work_entry: { domain: string; channel: string }
  repository_binding: { host: string; username: string; repository: string; private: boolean }
  persona_relationships: EnterprisePersonaRelationship[]
  persona_identity_governance: string
  registry_version: string
  relationship_confirmation?: { decision: string; observed_at: string; receipt_hash: string } | null
  responsibility_receipt?: { decision: string; observed_at: string; receipt_hash: string; responsibility_version: string } | null
}
interface EnterpriseEntryEnvelope { ok: boolean; entry: EnterpriseEntry }
interface EnterpriseWorkChannelSnapshot {
  state: string
  workEntryDomain: string
  workEntryChannel: string
  responsibilityDomain: string
  repository: string
  remoteRepositoryUrl: string
  localPath: string
  channelId: string
  authority: string
}
interface EnterpriseReceiptProjection {
  state: string
  repository: string
  path: string
  commit: string
}
interface EnterpriseReceiptEnvelope {
  ok: boolean
  repository_projection?: EnterpriseReceiptProjection
}

const previewStatus: HomeStatus = { directLocalBrokerState: 'UNVERIFIED', directConnectionCount: 0, resumableSessionCount: 0, codeRepositoryMountCount: 0, pnccReceiptCount: 0, updateState: 'READY_HUMAN_CONFIRMATION_REQUIRED', releaseRecoveryState: 'NONE', mcpRole: 'DISCOVERY_RECOVERY_COMPATIBILITY_ONLY', terminalLinkProtocol: 'HOLOLAKE_TERMINAL_LINK/2', terminalLinkTransport: 'UNVERIFIED', environmentFramePolicy: 'REQUIRED_AFTER_CONNECT_RESUME_AND_BEFORE_MUTATION' }
const previewPersonal: PersonalChannelSnapshot = { state: 'UNAVAILABLE', recentEvents: [], modules: [], integrity: { state: 'UNKNOWN', eventCount: 0, receiptCount: 0 } }
const previewKnowledge: KnowledgeSnapshot = { state: 'UNAVAILABLE', nativeRoot: '', legacyAvailable: false, documents: [], rawDocumentCount: 0, uniqueDocumentCount: 0, duplicateDocumentCount: 0, truncated: false }
const previewCode: CodeChannelSnapshot = { state: 'UNAVAILABLE', channels: [], authority: 'LOCAL_SOURCE_ACCESS_ONLY_NO_PUSH_OR_DEPLOY_AUTHORITY' }
const themes: Array<{ id: ThemeId; name: string }> = [
  { id: 'night', name: '夜湖星光' }, { id: 'dawn', name: '晨湖曦光' }, { id: 'nebula', name: '星云紫夜' }, { id: 'candle', name: '烛畔暖湖' }, { id: 'clear', name: '清浅澄湖' },
]
const viewLabels: Record<ViewId, string> = { overview: '个人频道', knowledge: '知识空间', code: '人格代码频道', receipts: '运行回执', system: '系统详情' }
const domainGates = [
  { domain: 'BRANCH_DOMAIN', className: 'd-sub', title: '光湖分域', gate: 'GATE 02 · ONLINE', facts: [
    ['域标识', 'BRANCH_DOMAIN'], ['责任主体', '花尔 · TCS-GL-0005∞'], ['人格体主体', '爆米花 · PER-BMH001 · AGE'], ['关系支持', '糖星云 · PER-TXY001 · AGE'], ['工作仓库', 'PRIVATE · 1 · LIVE'],
  ] },
  { domain: 'MAIN_DOMAIN', className: 'd-main', title: '光湖主域', gate: 'GATE 01 · ONLINE', facts: [
    ['域标识', 'MAIN_DOMAIN'], ['责任主体', 'Awen · TCS-GL-0016∞'], ['人格体主体', '天枢 · PER-AW-ARCH-001 · AGE'], ['关系支持', '知秋 · PER-ZQ001 · AGE'], ['工作仓库', 'PRIVATE · 1 · LIVE'],
  ] },
  { domain: 'ZERO_DOMAIN', className: 'd-zero', title: '光湖零域', gate: 'GATE 03 · ONLINE', facts: [
    ['域标识', 'ZERO_DOMAIN'], ['责任主体', '页页 · TCS-GL-0006∞'], ['人格体主体', '页骨 · PER-YG001 · AGE'], ['关系支持', '小坍缩核 · PER-XTK001 · AGE'], ['工作仓库', 'PRIVATE · 1 · LIVE'],
  ] },
  { domain: 'ZERO_SENSE_DOMAIN', className: 'd-zs', title: '光湖零感域', gate: 'GATE 04 · ONLINE', facts: [
    ['域标识', 'ZERO_SENSE_DOMAIN'], ['责任主体 01', '肥猫 · TCS-GL-0007∞'], ['人格体主体 01', '烬舟 · PER-JZ001 · AGE'], ['责任主体 02', '桔子 · TCS-GL-0008∞'], ['人格体主体 02', '熹微 · PER-JZ-ARCH-001 · AGE'], ['工作仓库', 'PRIVATE · 2 · LIVE'],
  ] },
  { domain: 'FIFTH_DOMAIN', className: 'd-fifth', title: '第五域 · 光湖本源域', gate: 'GATE 05 · ONLINE', facts: [
    ['域标识', 'FIFTH_DOMAIN'], ['责任主体', '冰朔 · ICE-GL∞'], ['系统入口', '永恒湖心系统'], ['访问状态', 'PRIVATE · LIVE'],
  ] },
]
const starPoints = [
  [14, 8, 3, 4.6], [26, 13, 2, 6], [41, 6, 2.5, 5.2], [64, 16, 2, 6.8],
  [80, 7, 3.5, 7], [90, 20, 1.5, 5.4], [8, 22, 2, 5.6], [93, 11, 2.5, 6.4],
]
const glintPoints = Array.from({ length: 58 }, (_, index) => ({
  left: (index * 37 + 11) % 100,
  top: ((index * index * 13 + 17) % 100),
  size: 1.4 + (index % 4) * .55,
  warm: index % 5 === 0 || (index > 19 && index < 39 && index % 3 === 0),
  duration: 2.8 + (index % 7) * .57,
  delay: (index % 11) * .43,
}))

function LakeAtmosphere({ awake }: { awake: boolean }) {
  return <>
    <div className="world-sky" aria-hidden="true">
      <i className="world-nebula"/>
      {starPoints.map(([left, top, size, duration], index) => <i className="world-star" key={index} style={{ left: `${left}%`, top: `${top}%`, width: size, height: size, '--star-duration': `${duration}s`, '--star-delay': `${index * .37}s` } as React.CSSProperties}/>) }
    </div>
    <div className="world-mist" aria-hidden="true"/>
    {awake && <div className="world-shimmer" aria-hidden="true">
      <i className="world-shine cool"/><i className="world-shine warm"/>
      {glintPoints.map((point, index) => <i className={`world-glint ${point.warm ? 'warm' : 'cool'}`} key={index} style={{ left: `${point.left}%`, top: `${point.top}%`, width: point.size, height: point.size, '--glint-duration': `${point.duration}s`, '--glint-delay': `${point.delay}s` } as React.CSSProperties}/>) }
    </div>}
  </>
}

function LakePool({ className, title, meta, open = false, risen = false, onClick }: { className: string; title: string; meta: string; open?: boolean; risen?: boolean; onClick?: () => void }) {
  return <button className={`world-pool ${className}${open ? ' open' : ''}${risen ? ' risen' : ''}`} type="button" onClick={onClick}>
    <span className="pool-bay"><i className="pool-halo"/><i className="pool-heart"/><i className="pool-ring"/></span>
    <span className="pool-label"><b>{title}</b><small>{meta}</small></span>
  </button>
}

function displayBeijingTime(coordinate: BeijingTimeCoordinate | null): string {
  if (!coordinate) return '正在读取北京时间'
  return coordinate.beijingTime.replace('T', ' ').slice(0, 23)
}

function EraHomeEntry({ timeline, coordinate, onOpen }: { timeline: GuanghuEraTimeline | null; coordinate: BeijingTimeCoordinate | null; onOpen: () => void }) {
  const markers = timeline ? [timeline.events[0], timeline.events[3], timeline.events[6], timeline.events[timeline.events.length - 1]].filter(Boolean) : []
  return <button className="era-home-entry" type="button" onClick={onOpen} aria-label="展开曜冥纪元演化时间线">
    <span className="era-home-heading"><b>曜冥纪元</b><small>{coordinate ? `光湖历第 ${coordinate.guanghuEraDay} 天` : '从 2025-04-26 起'}</small></span>
    <span className="era-home-markers" aria-hidden="true">{markers.map((event) => <i key={event.eventId}><em/>{event.displayDate.slice(0, 7)}</i>)}</span>
    <span className="era-home-now">{displayBeijingTime(coordinate)} · 查看演化史</span>
  </button>
}

function EraTimelineOverlay({ timeline, coordinate, onClose }: { timeline: GuanghuEraTimeline; coordinate: BeijingTimeCoordinate | null; onClose: () => void }) {
  const activeCoordinate = coordinate ?? timeline.currentCoordinate
  const networkSynchronized = activeCoordinate.networkSyncState === 'SYNCHRONIZED_ON_APPLICATION_OPEN'
  return <div className="era-overlay" role="dialog" aria-modal="true" aria-label="曜冥纪元演化史">
    <button className="era-overlay-scrim" type="button" aria-label="关闭曜冥纪元" onClick={onClose}/>
    <section className="era-timeline-panel">
      <header><div><span>YAOMING ERA · HOLOLAKE CALENDAR</span><h2>{timeline.eraName}</h2><p>{timeline.calendarName}第 {activeCoordinate.guanghuEraDay} 天 · {displayBeijingTime(activeCoordinate)}</p></div><button type="button" aria-label="关闭" onClick={onClose}>×</button></header>
      <p className="era-clock-boundary">{networkSynchronized ? `HoloLake 打开时已通过加密网络读取现实时间锚点${activeCoordinate.networkUncertaintyMs ? `，当前估计误差不超过约 ${activeCoordinate.networkUncertaintyMs} 毫秒` : ''}。` : '联网校时尚未完成，当前暂用本机现实系统时钟并明确标记等待同步。'} HoloLake 关闭后，现实时间仍继续。</p>
      <ol>{timeline.events.map((event) => <li key={event.eventId}>
        <time>{event.displayDate}</time><i aria-hidden="true"/><div><h3>{event.title}</h3><p>{event.summary}</p></div>
      </li>)}</ol>
      <footer>源点精度：只确认到 2025-04-26 当日，具体时分秒未知。公众时间线只呈现现实可成立的演化事实；语言世界内部模拟不构成外部现实关系。</footer>
    </section>
  </div>
}

function getOrCreateLocalId(key: string, prefix: string) {
  const existing = window.localStorage.getItem(key)
  if (existing) return existing
  const generated = `${prefix}-${crypto.randomUUID()}`
  window.localStorage.setItem(key, generated)
  return generated
}

function humanError(error: unknown, context: 'knowledge' | 'code' | 'identity' | 'system' | 'login') {
  const value = String(error)
  if (value.includes('LOGIN_CREDENTIALS_INVALID')) return '账号或密码未被仓库接受。'
  if (value.includes('LOGIN_USERNAME_INVALID')) return '账号格式不合法（仅限字母、数字、连字符、下划线）。'
  if (value.includes('LOGIN_NETWORK_FAILED')) return '未能连通光湖代码频道服务器。'
  if (value.includes('LOGIN_KEYCHAIN_FAILED')) return '本机钥匙串写入失败，凭证未能安全保存。'
  if (value.includes('LOGIN_SESSION_CORRUPT')) return '登录会话已损坏，请重新登录。'
  if (value.includes('LOGIN_VERIFICATION_FAILED')) return '仓库验证未通过，请稍后再试。'
  if (value.includes('LOGIN_ACCOUNT_NUMBER_MISMATCH')) return '这个账号没有绑定到当前编号，系统已停止进入。'
  if (value.includes('NEW_PASSWORD_POLICY_INVALID')) return '新密码至少 14 位，并且不能与一次性密码相同。'
  if (value.includes('FIRST_LOGIN_PASSWORD_CHANGE_FAILED')) return '一次性密码未被接受，密码没有修改。'
  if (value.includes('FIRST_LOGIN_PASSWORD_CHANGE_NOT_PROVISIONED')) return '该编号当前没有登记首次换密入口。'
  if (value.includes('LOGIN_ACCOUNT_BINDING_UNREGISTERED')) return '这个编号尚未登记对应的仓库账号，系统已停止进入。'
  if (value.includes('DOMAIN_LOGIN_NOT_PROVISIONED')) return '该域的企业服务器尚未接入，当前不能继续登录。'
  if (value.includes('PERSISTENT_CREDENTIAL_UNAVAILABLE')) return '当前系统尚未接通安全凭证存储，不能完成签署。'
  if (value.includes('ENTERPRISE_RECEIPT_FAILED')) return '企业回执没有写入，请稍后重新提交。'
  if (value.includes('ENTERPRISE_RECEIPT_ROUTE_REQUIRED')) return '此签署入口仅适用于企业四域。'
  if (value.includes('DOMAIN_ROUTE_REQUIRED') || value.includes('ZP_DOMAIN_ROUTE_REQUIRED')) return '编号尚未解析到已登记域，不能开始登录。'
  if (value.includes('USER_PNCC_TRUSTED_SUBJECT_REQUIRED')) return '建立人格代码频道前，需要有效的用户编号与仓库账号登录。'
  if (value.includes('USER_PNCC_BINDING_MISMATCH')) return '本机频道绑定记录与当前账号不一致，系统已停止加载。'
  if (value.includes('HOST_NOT_TRUSTED')) return '该地址不属于已登记的光湖代码频道。'
  if (value.includes('URL_INVALID')) return '频道地址无效，请粘贴完整的 HTTPS 克隆地址。'
  if (value.includes('DESTINATION_EXISTS')) return '该代码频道已经存在，无需再次克隆。'
  if (value.includes('CLONE_FAILED')) return '代码频道克隆失败，请核对地址及读取权限。'
  if (value.includes('NO_SUPPORTED_FILES')) return '文件夹中没有可导入的知识文件。'
  if (value.includes('SAVE_CONFLICT')) return '页面已在别处更新，请重新打开后再编辑。'
  if (value.includes('FILE_UNSUPPORTED')) return '该文件不是当前可阅读的文本格式。'
  if (context === 'login') return '登录未完成。'
  if (context === 'identity') return '个人空间未能建立。'
  if (context === 'knowledge') return '知识操作未完成，原文件未被覆盖。'
  if (context === 'code') return '代码频道操作未完成。'
  return '系统操作未完成。'
}

function Icon({ name }: { name: ViewId | 'search' | 'import' | 'folder' | 'copy' | 'arrow' | 'chevron' | 'file' | 'edit' | 'save' | 'back' | 'download' | 'trash' | 'chevronDown' | 'settings' | 'more' | 'plus' }) {
  const paths: Record<string, React.ReactNode> = {
    overview: <><rect x="4" y="4" width="6" height="6" rx="1.5"/><rect x="14" y="4" width="6" height="6" rx="1.5"/><rect x="4" y="14" width="6" height="6" rx="1.5"/><rect x="14" y="14" width="6" height="6" rx="1.5"/></>,
    knowledge: <><path d="M5 4.5h10a3 3 0 0 1 3 3V20H8a3 3 0 0 1-3-3Z"/><path d="M8 4.5v12.8A2.7 2.7 0 0 1 10.7 20"/></>,
    code: <><path d="m8.5 8-4 4 4 4M15.5 8l4 4-4 4M13.5 5l-3 14"/></>,
    receipts: <><path d="M7 3.5h10v17l-2.5-1.5L12 20.5 9.5 19 7 20.5Z"/><path d="M10 8h4M10 12h4"/></>,
    system: <><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14.2 3h-4.1l-.3 2.7a7 7 0 0 0-2 1.2l-2.5-1-2 3.4 2.1 1.5a7 7 0 0 0 0 2.4l-2 1.5 2 3.4 2.4-1a7 7 0 0 0 2 1.2l.3 2.7h4.1l.3-2.7a7 7 0 0 0 2-1.2l2.5 1 2-3.4-2.1-1.5A7 7 0 0 0 19 12Z"/></>,
    search: <><circle cx="11" cy="11" r="6"/><path d="m16 16 4 4"/></>,
    import: <><path d="M12 4v11M8 11l4 4 4-4"/><path d="M5 19h14"/></>,
    download: <><path d="M12 4v12M7 11l5 5 5-5"/><path d="M4 17v3h16v-3"/></>,
    trash: <><path d="M4 7h16M10 4h4M7 7l1 13h8l1-13M10 11v5M14 11v5"/></>,
    chevronDown: <path d="M6 9l6 6 6-6"/>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M12 3v2.5M12 18.5V21M4.6 6.8l1.8 1.8M17.6 15.4l1.8 1.8M3 12h2.5M18.5 12H21M4.6 17.2l1.8-1.8M17.6 8.6l1.8-1.8"/></>,
    more: <><circle cx="12" cy="5" r="1.4"/><circle cx="12" cy="12" r="1.4"/><circle cx="12" cy="19" r="1.4"/></>,
    plus: <path d="M12 5v14M5 12h14"/>,
    folder: <path d="M3.5 7.5h6l2-2h9v13h-17Z"/>,
    file: <><path d="M6 3.5h8l4 4v13H6Z"/><path d="M14 3.5v4h4"/></>,
    copy: <><rect x="8" y="8" width="10" height="11" rx="2"/><path d="M15 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h2"/></>,
    arrow: <><path d="M5 12h13M14 7l5 5-5 5"/></>,
    chevron: <path d="m9 6 6 6-6 6"/>,
    edit: <><path d="m4 20 4.5-1 10-10-3.5-3.5-10 10Z"/><path d="m13.5 6.5 3.5 3.5"/></>,
    save: <><path d="M5 4h12l2 2v14H5Z"/><path d="M8 4v6h8V4M8 20v-6h8v6"/></>,
    back: <path d="m15 6-6 6 6 6"/>,
  }
  return <svg viewBox="0 0 24 24" aria-hidden="true">{paths[name]}</svg>
}


interface TreeNode { name: string; key: string; folders: Map<string, TreeNode>; documents: KnowledgeDocumentSummary[] }
function knowledgeTree(documents: KnowledgeDocumentSummary[]) {
  const root: TreeNode = { name: '知识', key: '', folders: new Map(), documents: [] }
  for (const document of documents) {
    const segments = document.path.split('/').filter(Boolean)
    const file = segments.pop()
    let cursor = root
    for (const segment of segments) {
      const key = cursor.key ? `${cursor.key}/${segment}` : segment
      if (!cursor.folders.has(segment)) cursor.folders.set(segment, { name: segment, key, folders: new Map(), documents: [] })
      cursor = cursor.folders.get(segment)!
    }
    cursor.documents.push({ ...document, title: document.title || file || '未命名页面' })
  }
  return root
}
function countTree(node: TreeNode): number {
  return node.documents.length + [...node.folders.values()].reduce((sum, child) => sum + countTree(child), 0)
}
function KnowledgeTree({ node, depth, expanded, active, onToggle, onOpen, onRemoveFolder, folderMenuKey, onFolderMenuToggle }: { node: TreeNode; depth: number; expanded: Set<string>; active?: string; onToggle: (key: string) => void; onOpen: (item: KnowledgeDocumentSummary) => void; onRemoveFolder?: (folder: TreeNode) => void; folderMenuKey?: string | null; onFolderMenuToggle?: (key: string) => void }) {
  const folders = [...node.folders.values()].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
  const documents = [...node.documents].sort((a, b) => a.title.localeCompare(b.title, 'zh-CN'))
  return <>
    {folders.map((folder) => {
      const open = depth === 0 || expanded.has(folder.key)
      return <div key={folder.key} className="tree-branch">
        <button className="tree-folder" style={{ paddingLeft: 12 + depth * 14 }} type="button" onClick={() => onToggle(folder.key)}>
          <span className={open ? 'tree-chevron open' : 'tree-chevron'}><Icon name="chevron"/></span><Icon name="folder"/><span>{folder.name}</span><em>{countTree(folder)}</em>
        </button>
        {onRemoveFolder && onFolderMenuToggle && <span className="tree-folder-tools"><button className="tree-folder-menu-button" type="button" title="文件夹操作" onClick={(event) => { event.stopPropagation(); onFolderMenuToggle(folder.key) }}><Icon name="more"/></button>{folderMenuKey === folder.key && <span className="tree-folder-menu"><button type="button" onClick={(event) => { event.stopPropagation(); onFolderMenuToggle(folder.key); onRemoveFolder(folder) }}><Icon name="trash"/>移到回收站</button></span>}</span>}
        {open && <KnowledgeTree node={folder} depth={depth + 1} expanded={expanded} active={active} onToggle={onToggle} onOpen={onOpen} onRemoveFolder={onRemoveFolder} folderMenuKey={folderMenuKey} onFolderMenuToggle={onFolderMenuToggle}/>}
      </div>
    })}
    {documents.map((document) => <button key={`${document.source}:${document.path}`} className={active === `${document.source}:${document.path}` ? 'tree-document active' : 'tree-document'} style={{ paddingLeft: 31 + depth * 14 }} type="button" onClick={() => onOpen(document)}>
      <Icon name="file"/><span>{document.title}</span>{document.duplicateCount > 0 && <em title="折叠的相同内容">+{document.duplicateCount}</em>}
    </button>)}
  </>
}

function HoloLakeApp() {
  // 湖面装饰默认休眠。人类靠近或操作时短暂唤醒；验证、升域等因果动画不受此开关影响。
  const [motionAwake, setMotionAwake] = useState(false)
  const motionSleepTimer = useRef<number | null>(null)
  const wakeAmbientMotion = useCallback(() => {
    if (document.hidden) return
    setMotionAwake(true)
    if (motionSleepTimer.current !== null) window.clearTimeout(motionSleepTimer.current)
    motionSleepTimer.current = window.setTimeout(() => {
      motionSleepTimer.current = null
      setMotionAwake(false)
    }, 2400)
  }, [])
  const [theme, setTheme] = useState<ThemeId>(() => (window.localStorage.getItem('hololake-theme') as ThemeId) || 'night')
  const [view, setView] = useState<ViewId>('overview')
  const [worldStage, setWorldStage] = useState<WorldStage>('domain')
  const [toolReturnStage, setToolReturnStage] = useState<WorldStage>('channel')
  const [status, setStatus] = useState<HomeStatus>(previewStatus)
  const [personal, setPersonal] = useState<PersonalChannelSnapshot>(previewPersonal)
  const [eraTimeline, setEraTimeline] = useState<GuanghuEraTimeline | null>(null)
  const [beijingCoordinate, setBeijingCoordinate] = useState<BeijingTimeCoordinate | null>(null)
  const [eraOpen, setEraOpen] = useState(false)
  const openEraTimeline = useCallback(() => {
    setEraOpen(true)
    invoke<PersonaTimeAuthorityStartup>('start_persona_time_authority')
      .then((startup) => setBeijingCoordinate(startup.coordinate))
      .catch(() => undefined)
  }, [])
  const [knowledge, setKnowledge] = useState<KnowledgeSnapshot>(previewKnowledge)
  const [codeChannels, setCodeChannels] = useState<CodeChannelSnapshot>(previewCode)
  const [activeDocument, setActiveDocument] = useState<KnowledgeDocument | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState<KnowledgeSearchResult[] | null>(null)
  const [knowledgeBusy, setKnowledgeBusy] = useState(false)
  const [knowledgeMessage, setKnowledgeMessage] = useState('')
  const [expanded, setExpanded] = useState<Set<string>>(() => new Set(['导入']))
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState('')
  const [lastKnowledgeReceipt, setLastKnowledgeReceipt] = useState('')
  const [cloneUrl, setCloneUrl] = useState('')
  const [codeBusy, setCodeBusy] = useState(false)
  const [codeMessage, setCodeMessage] = useState('')
  const [activeChannel, setActiveChannel] = useState<CodeChannelEntry | null>(null)
  const [codeTree, setCodeTree] = useState<CodeTreeSnapshot | null>(null)
  const [activeCodeFile, setActiveCodeFile] = useState<CodeFileProjection | null>(null)
  const [codeMode, setCodeMode] = useState<'human' | 'source'>('human')
  const [inspectorOpen, setInspectorOpen] = useState(() => window.localStorage.getItem('hololake-inspector-open') !== '0')
  const toggleInspector = () => setInspectorOpen((current) => { window.localStorage.setItem('hololake-inspector-open', current ? '0' : '1'); return !current })
  const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null)
  const headingScrollTimer = useRef<number | null>(null)
  const [settingsMenuOpen, setSettingsMenuOpen] = useState(false)
  const [folderMenuKey, setFolderMenuKey] = useState<string | null>(null)
  const [displayName, setDisplayName] = useState('')
  const [identityBusy, setIdentityBusy] = useState(false)
  const [identityMessage, setIdentityMessage] = useState('')
  const [receipts, setReceipts] = useState<ReceiptEvent[]>([])
  const [ticket, setTicket] = useState<DiscoveryTicketReceipt | null>(null)
  const [nearbyDiscovery, setNearbyDiscovery] = useState<NearbyAiDiscoverySnapshot | null>(null)
  const [systemMessage, setSystemMessage] = useState('')
  const [releaseCandidate, setReleaseCandidate] = useState<ReleaseCandidate | null>(null)
  const [repoLogin, setRepoLogin] = useState<LoginSession | null>(null)
  const [userPncc, setUserPncc] = useState<UserPnccChannelSnapshot | null>(null)
  const [enterpriseWork, setEnterpriseWork] = useState<EnterpriseWorkChannelSnapshot | null>(null)
  const [userPnccBusy, setUserPnccBusy] = useState(false)
  const [userPnccMessage, setUserPnccMessage] = useState('')
  const [loginUsername, setLoginUsername] = useState('')
  const [loginPassword, setLoginPassword] = useState('')
  const [passwordChangeMode, setPasswordChangeMode] = useState(false)
  const [newLoginPassword, setNewLoginPassword] = useState('')
  const [confirmLoginPassword, setConfirmLoginPassword] = useState('')
  const [loginBusy, setLoginBusy] = useState(false)
  const [loginRising, setLoginRising] = useState(false)
  const [loginMessage, setLoginMessage] = useState('')
  const [gateStage, setGateStage] = useState<'number' | 'key'>('number')
  const [gateRaw, setGateRaw] = useState('')
  const [gateInf, setGateInf] = useState(false)
  const gateNumber = formatGateNumber(gateRaw) + (gateInf ? '∞' : '')
  const [gateOpen, setGateOpen] = useState(false)
  const [activeDomainInfo, setActiveDomainInfo] = useState('')
  const gateInputRef = useRef<HTMLInputElement>(null)
  // 等待入口展开动画进入稳定阶段后再聚焦输入框，避免动画期间焦点跳转。
  useEffect(() => {
    if (!gateOpen || gateStage !== 'number') return
    const timer = window.setTimeout(() => gateInputRef.current?.focus(), 640)
    return () => window.clearTimeout(timer)
  }, [gateOpen, gateStage])
  useEffect(() => {
    if ((!gateOpen && !activeDomainInfo) || gateStage !== 'number') return
    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key !== 'Escape') return
      setGateOpen(false)
      setActiveDomainInfo('')
      setGateMessage('')
    }
    window.addEventListener('keydown', closeOnEscape)
    return () => window.removeEventListener('keydown', closeOnEscape)
  }, [activeDomainInfo, gateOpen, gateStage])
  const [gateBusy, setGateBusy] = useState(false)
  const [gateMessage, setGateMessage] = useState('')
  const [gateRising, setGateRising] = useState(false)
  const [gateWelcomeLine, setGateWelcomeLine] = useState('')
  const [systemBusy, setSystemBusy] = useState(false)
  const [zeroPoint, setZeroPoint] = useState<ZeroPointSnapshot | null>(null)
  const [zpNumber, setZpNumber] = useState('')
  const [zpBusy, setZpBusy] = useState(false)
  const [zpMessage, setZpMessage] = useState('')
  const [serverPncc, setServerPncc] = useState<ServerPnccProjection | null>(null)
  const [serverPnccBusy, setServerPnccBusy] = useState(false)
  const [serverPnccReadback, setServerPnccReadback] = useState<'WAITING' | 'LIVE' | 'UNAVAILABLE'>('WAITING')
  const [developmentLane, setDevelopmentLane] = useState<DevelopmentWriteLaneStatus | null>(null)
  const [numberingKernel, setNumberingKernel] = useState<ZeroCoreNumberingKernelSnapshot | null>(null)
  const [glsRuntime, setGlsRuntime] = useState<GlsProtocolRuntimeSnapshot | null>(null)
  const [glsKernel, setGlsKernel] = useState<GlsProtocolKernelSnapshot | null>(null)
  const [enterpriseEntry, setEnterpriseEntry] = useState<EnterpriseEntry | null>(null)
  const [enterpriseEntryBusy, setEnterpriseEntryBusy] = useState(false)
  const [enterpriseReceiptBusy, setEnterpriseReceiptBusy] = useState(false)
  const [enterpriseReceiptMessage, setEnterpriseReceiptMessage] = useState('')
  const [responsibilityNote, setResponsibilityNote] = useState('')

  useEffect(() => {
    const sleepAmbientMotion = () => {
      if (motionSleepTimer.current !== null) window.clearTimeout(motionSleepTimer.current)
      motionSleepTimer.current = null
      setMotionAwake(false)
    }
    const onVisibilityChange = () => { if (document.hidden) sleepAmbientMotion() }
    window.addEventListener('blur', sleepAmbientMotion)
    document.addEventListener('visibilitychange', onVisibilityChange)
    return () => {
      sleepAmbientMotion()
      window.removeEventListener('blur', sleepAmbientMotion)
      document.removeEventListener('visibilitychange', onVisibilityChange)
    }
  }, [])

  const refreshCore = useCallback(async () => {
    try {
      const startup = await invoke<PersonaTimeAuthorityStartup>('start_persona_time_authority')
      setBeijingCoordinate(startup.coordinate)
    } catch { /* 联网失败时其余首页能力仍可启动。 */ }
    const localAccountId = getOrCreateLocalId('hololake-local-account', 'human-local')
    const [homeResult, personalResult, knowledgeResult, codeResult, eraResult, developmentResult, numberingResult, glsRuntimeResult, glsKernelResult] = await Promise.allSettled([
      invoke<HomeStatus>('get_hololake_home_status'),
      invoke<PersonalChannelSnapshot>('get_personal_channel_snapshot'),
      invoke<KnowledgeSnapshot>('get_knowledge_snapshot'),
      invoke<CodeChannelSnapshot>('get_code_channel_snapshot'),
      invoke<GuanghuEraTimeline>('get_guanghu_era_timeline'),
      invoke<DevelopmentWriteLaneStatus>('inspect_development_write_lane', { input: { accountId: localAccountId } }),
      invoke<ZeroCoreNumberingKernelSnapshot>('get_zero_core_numbering_kernel'),
      invoke<GlsProtocolRuntimeSnapshot>('get_gls_protocol_runtime'),
      invoke<GlsProtocolKernelSnapshot>('get_gls_protocol_kernel'),
    ])
    if (homeResult.status === 'fulfilled') setStatus(homeResult.value)
    if (personalResult.status === 'fulfilled') setPersonal(personalResult.value)
    if (knowledgeResult.status === 'fulfilled') setKnowledge(knowledgeResult.value)
    if (codeResult.status === 'fulfilled') setCodeChannels(codeResult.value)
    if (eraResult.status === 'fulfilled') {
      setEraTimeline(eraResult.value)
      setBeijingCoordinate(eraResult.value.currentCoordinate)
    }
    setDevelopmentLane(developmentResult.status === 'fulfilled' ? developmentResult.value : null)
    setNumberingKernel(numberingResult.status === 'fulfilled' ? numberingResult.value : null)
    setGlsRuntime(glsRuntimeResult.status === 'fulfilled' ? glsRuntimeResult.value : null)
    setGlsKernel(glsKernelResult.status === 'fulfilled' ? glsKernelResult.value : null)
  }, [])
  const loadReceipts = useCallback(async () => {
    try {
      const projection = await invoke<ReceiptProjection>('query_pncc_receipt_projection', { input: { afterSequence: 0, limit: 25 } })
      setReceipts(projection.events)
    } catch { setReceipts([]) }
  }, [])
  useEffect(() => {
    void refreshCore()
    const refreshWhenHumanReturns = () => { if (!document.hidden) void refreshCore() }
    window.addEventListener('focus', refreshWhenHumanReturns)
    return () => window.removeEventListener('focus', refreshWhenHumanReturns)
  }, [refreshCore])
  useEffect(() => {
    if (!eraOpen) return
    const closeOnEscape = (event: KeyboardEvent) => { if (event.key === 'Escape') setEraOpen(false) }
    window.addEventListener('keydown', closeOnEscape)
    return () => window.removeEventListener('keydown', closeOnEscape)
  }, [eraOpen])
  useEffect(() => {
    invoke<NearbyAiDiscoverySnapshot>('get_nearby_ai_discovery')
      .then(setNearbyDiscovery)
      .catch(() => setNearbyDiscovery(null))
  }, [])
  const refreshServerPncc = useCallback(async () => {
    setServerPnccBusy(true)
    try {
      setServerPncc(await invoke<ServerPnccProjection>('query_jd_pncc_server_projection'))
      setServerPnccReadback('LIVE')
    } catch {
      setServerPncc(null)
      setServerPnccReadback('UNAVAILABLE')
    } finally {
      setServerPnccBusy(false)
    }
  }, [])
  useEffect(() => {
    void refreshServerPncc()
  }, [refreshServerPncc])
  useEffect(() => {
    document.documentElement.dataset.theme = theme
    window.localStorage.setItem('hololake-theme', theme)
  }, [theme])
  useEffect(() => {
    invoke<LoginSession | null>('check_code_repo_login').then((session) => setRepoLogin(session)).catch(() => setRepoLogin(null))
  }, [])
  const loadEnterpriseEntry = useCallback(async () => {
    if (!repoLogin || repoLogin.domain === 'FIFTH_DOMAIN') {
      setEnterpriseEntry(null)
      return
    }
    setEnterpriseEntryBusy(true)
    setEnterpriseReceiptMessage('')
    try {
      const result = await invoke<EnterpriseEntryEnvelope>('get_enterprise_entry')
      setEnterpriseEntry(result.entry)
    } catch (error) {
      setEnterpriseEntry(null)
      setEnterpriseReceiptMessage(humanError(error, 'login'))
    } finally {
      setEnterpriseEntryBusy(false)
    }
  }, [repoLogin])
  useEffect(() => { void loadEnterpriseEntry() }, [loadEnterpriseEntry])
  const loadZeroPoint = useCallback(async () => {
    try { setZeroPoint(await invoke<ZeroPointSnapshot>('zero_point_status')) } catch { /* 验证服务尚未就绪时保持空白状态。 */ }
  }, [])
  useEffect(() => {
    void loadZeroPoint()
  }, [loadZeroPoint])
  // 第五域恢复本人的本机私人频道；企业成员只同步其唯一私有责任工作仓库。
  // 两条路径不能互相冒充：企业工作账号不自动取得个人生活区或个人节点权限。
  useEffect(() => {
    if (!repoLogin || zeroPoint?.route !== 'verified') {
      setUserPncc(null)
      setEnterpriseWork(null)
      return
    }
    let active = true
    setUserPnccBusy(true)
    setUserPnccMessage('')
    const channelReady = repoLogin.domain === 'FIFTH_DOMAIN'
      ? invoke<UserPnccChannelSnapshot>('ensure_user_pncc_channel').then((snapshot) => {
          if (!active) return
          setEnterpriseWork(null)
          setUserPncc(snapshot)
          setUserPnccMessage('本机原生私人频道已就绪。')
        })
      : invoke<EnterpriseWorkChannelSnapshot>('ensure_enterprise_work_channel').then((snapshot) => {
          if (!active) return
          setUserPncc(null)
          setEnterpriseWork(snapshot)
          setUserPnccMessage('本人私有责任工作仓库已接入。')
        })
    channelReady
      .then(() => { if (active) void refreshCore() })
      .catch((error) => { if (active) setUserPnccMessage(humanError(error, 'code')) })
      .finally(() => { if (active) setUserPnccBusy(false) })
    return () => { active = false }
  }, [repoLogin, zeroPoint?.route, zeroPoint?.userNumber, refreshCore])
  // 本机存在已绑定编号时自动回填，减少重复输入。
  useEffect(() => {
    if (gateStage !== 'number' || gateRaw) return
    const bound = zeroPoint?.binding === 'bound' ? zeroPoint.userNumber : ''
    if (!bound) return
    setGateInf(bound.includes('∞'))
    setGateRaw(bound.toUpperCase().replace(/[^A-Z0-9]/g, ''))
  }, [zeroPoint, gateStage, gateRaw])
  // 大门·编号门输入：只收字母数字（杠系统补、∞开关点），删到∞时开关跟着灭
  const onGateInput = (value: string) => {
    if (gateInf && !value.includes('∞')) setGateInf(false)
    setGateRaw(value.toUpperCase().replace(/[^A-Z0-9]/g, ''))
  }
  // 大门·编号门：先报编号→灯塔查号→只答有效/无效→域浮起→才见钥匙门
  const gateVerifyNumber = async () => {
    setGateBusy(true)
    setGateMessage('')
    try {
      await invoke<ZeroPointSnapshot>('zero_point_bind', { input: { number: gateNumber } })
      const snapshot = await invoke<ZeroPointSnapshot>('zero_point_verify')
      setZeroPoint(snapshot)
      if (snapshot.route === 'verified') {
        setActiveDomainInfo('')
        setGateOpen(false)
        setGateWelcomeLine(createWorldWelcome(snapshot))
        setGateRising(true)
        window.setTimeout(() => { setGateRising(false); setGateStage('key') }, 2600)
      } else {
        setGateMessage('编号无效')
      }
    } catch (error) {
      setGateMessage(humanError(error, 'login'))
    } finally {
      setGateBusy(false)
    }
  }
  useEffect(() => { if (view === 'receipts') void loadReceipts() }, [loadReceipts, view])

  const visibleDocuments = useMemo(() => {
    if (!searchResults) return knowledge.documents
    return searchResults.map((result) => knowledge.documents.find((item) => item.source === result.source && item.path === result.path)).filter(Boolean) as KnowledgeDocumentSummary[]
  }, [knowledge.documents, searchResults])
  const tree = useMemo(() => knowledgeTree(visibleDocuments), [visibleDocuments])
  const activeSummary = activeDocument
    ? knowledge.documents.find((item) => item.source === activeDocument.source && item.path === activeDocument.path)
    : undefined
  const parsedDocument = useMemo(() => activeDocument ? splitFrontmatter(activeDocument.body) : null, [activeDocument])
  const outline = useMemo(() => activeDocument ? documentOutline(activeDocument.body) : [], [activeDocument])
  const docStats = useMemo(() => {
    if (!activeDocument) return null
    const chars = activeDocument.body.replace(/\s+/g, '').length
    return { chars, minutes: Math.max(1, Math.ceil(chars / 400)) }
  }, [activeDocument])
  useEffect(() => { setActiveHeadingId(null) }, [activeDocument?.path])
  useEffect(() => {
    if (!activeHeadingId) return
    document.querySelector('.outline-list button.active')?.scrollIntoView({ block: 'nearest' })
  }, [activeHeadingId])
  const handleReaderScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const container = event.currentTarget
    if (headingScrollTimer.current !== null) return
    headingScrollTimer.current = window.setTimeout(() => {
      headingScrollTimer.current = null
      const containerTop = container.getBoundingClientRect().top
      let current: string | null = null
      for (const heading of Array.from(container.querySelectorAll<HTMLElement>('h1[id], h2[id], h3[id], h4[id]'))) {
        if (heading.getBoundingClientRect().top - containerTop <= 28) current = heading.id
        else break
      }
      setActiveHeadingId(current)
    }, 100)
  }
  const connectionOnline = status.directConnectionCount > 0
  const connectionLabel = connectionOnline
    ? '本地原生连接 · 客户端在线'
    : status.resumableSessionCount > 0
      ? '原生会话可续接 · 当前离线'
      : '原生接口已驻留 · 尚无客户端'
  const timeAuthorityModule = personal.modules.find((module) => module.kind === 'PERSONA_TIME_AUTHORITY')

  const openDocument = async (source: KnowledgeSource, path: string) => {
    setKnowledgeBusy(true)
    setKnowledgeMessage('')
    setEditing(false)
    try {
      const document = await invoke<KnowledgeDocument>('read_knowledge_document', { input: { source, path } })
      setActiveDocument(document)
      setDraft(document.body)
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const openWiki = (target: string) => {
    const normalized = target.replace(/\.md$/i, '').toLowerCase()
    const match = knowledge.documents.find((item) =>
      item.title.toLowerCase() === normalized || item.path.replace(/\.md$/i, '').toLowerCase().endsWith(normalized))
    if (match) void openDocument(match.source, match.path)
    else setKnowledgeMessage(`未找到链接页面：${target}`)
  }
  const runSearch = async (event: React.FormEvent) => {
    event.preventDefault()
    if (!searchQuery.trim()) { setSearchResults(null); return }
    setKnowledgeBusy(true)
    try {
      setSearchResults(await invoke<KnowledgeSearchResult[]>('search_knowledge', { input: { query: searchQuery } }))
      setActiveDocument(null)
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const importKnowledge = async () => {
    setKnowledgeBusy(true)
    setKnowledgeMessage('')
    try {
      const result = await invoke<KnowledgeImportResult | null>('select_and_import_knowledge_folder')
      if (!result) return
      setKnowledge(result.snapshot)
      setSearchResults(null)
      setSearchQuery('')
      setLastKnowledgeReceipt(result.gitCommit)
      setKnowledgeMessage(`导入完成：新增 ${result.importedDocuments}，已存在 ${result.existingDocuments}，冲突 ${result.conflicts}。`)
      if (result.firstDocument) await openDocument('native', result.firstDocument)
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const downloadDocument = async (format: 'md' | 'html') => {
    if (!activeDocument) return
    setKnowledgeBusy(true)
    setKnowledgeMessage('')
    try {
      let body = activeDocument.body
      if (format === 'html') {
        const parsed = splitFrontmatter(body)
        const article = markdownHtml(parsed.content)
        body = `<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8"><title>${activeDocument.title}</title><style>body{max-width:820px;margin:40px auto;padding:0 24px;font:15px/1.8 -apple-system,'Segoe UI','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif;color:#1f2330;background:#fff}h1,h2,h3{line-height:1.4}blockquote{margin:20px 0;padding:12px 16px;border-left:3px solid #a78bfa;background:#f3f0ff;border-radius:8px}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ddd;padding:7px 10px}pre{background:#f4f5f8;padding:14px;border-radius:8px;overflow:auto}img{max-width:100%}</style></head><body><h1>${activeDocument.title}</h1>${article}</body></html>`
      }
      const receipt = await invoke<{ path: string; bytes: number } | null>('export_knowledge_document', { input: { title: activeDocument.title, extension: format, body } })
      setKnowledgeMessage(receipt ? `已下载到 ${receipt.path}` : '已取消下载。')
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const printDocument = async () => {
    setKnowledgeMessage('')
    try {
      await invoke('print_knowledge_document')
      setKnowledgeMessage('打印框里选「存储为 PDF」即可得到 PDF 文件。')
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
  }
  const reloadKnowledge = async () => {
    const snapshot = await invoke<KnowledgeSnapshot>('get_knowledge_snapshot')
    setKnowledge(snapshot)
  }
  const createDocument = async () => {
    setKnowledgeBusy(true)
    setKnowledgeMessage('')
    try {
      const receipt = await invoke<{ removed: string; pages: number }>('create_knowledge_document', { input: { title: '未命名页面' } })
      setKnowledgeMessage(`已新建空白页「${receipt.removed.replace(/\.md$/, '')}」，正在编辑。`)
      setSearchResults(null)
      await reloadKnowledge()
      await openDocument('native', receipt.removed)
      setEditing(true)
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const removeDocument = async () => {
    if (!activeDocument) return
    setKnowledgeBusy(true)
    setKnowledgeMessage('')
    try {
      const receipt = await invoke<{ removed: string; pages: number } | null>('delete_knowledge_document', { input: { source: activeDocument.source, path: activeDocument.path } })
      if (receipt) {
        setKnowledgeMessage(`已移入回收站：${receipt.removed}（可找回）`)
        setActiveDocument(null)
        setSearchResults(null)
        await reloadKnowledge()
      } else setKnowledgeMessage('已取消删除。')
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const removeFolder = async (folder: TreeNode) => {
    setKnowledgeBusy(true)
    setKnowledgeMessage('')
    try {
      const receipt = await invoke<{ removed: string; pages: number } | null>('delete_knowledge_folder', { input: { folder: folder.key } })
      if (receipt) {
        setKnowledgeMessage(`文件夹「${folder.name}」（${receipt.pages} 页）已移入回收站（可找回）`)
        setActiveDocument(null)
        setSearchResults(null)
        await reloadKnowledge()
      } else setKnowledgeMessage('已取消删除。')
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }
  const saveDocument = async () => {
    if (!activeDocument?.writable) return
    setKnowledgeBusy(true)
    try {
      const result = await invoke<KnowledgeSaveResult>('save_knowledge_document', {
        input: { path: activeDocument.path, body: draft, expectedContentSha256: activeDocument.contentSha256 },
      })
      setActiveDocument(result.document)
      setDraft(result.document.body)
      setEditing(false)
      setLastKnowledgeReceipt(result.gitCommit)
      setKnowledgeMessage(result.state === 'UNCHANGED' ? '内容没有变化。' : '页面已保存，并写入本机 Git 回执。')
      await refreshCore()
    } catch (error) { setKnowledgeMessage(humanError(error, 'knowledge')) }
    finally { setKnowledgeBusy(false) }
  }

  const cloneCodeChannel = async (event: React.FormEvent) => {
    event.preventDefault()
    if (!cloneUrl.trim()) return
    setCodeBusy(true)
    setCodeMessage('')
    try {
      const snapshot = await invoke<CodeChannelSnapshot>('clone_code_channel', { input: { url: cloneUrl } })
      setCodeChannels(snapshot)
      setCloneUrl('')
      setCodeMessage('代码频道已克隆并登记。')
    } catch (error) { setCodeMessage(humanError(error, 'code')) }
    finally { setCodeBusy(false) }
  }
  const selectLocalCodeChannel = async () => {
    setCodeBusy(true)
    setCodeMessage('')
    try {
      const snapshot = await invoke<CodeChannelSnapshot | null>('select_local_code_channel')
      if (snapshot) {
        setCodeChannels(snapshot)
        setCodeMessage('本地代码频道已登记，原文件未移动。')
      }
    } catch (error) { setCodeMessage(humanError(error, 'code')) }
    finally { setCodeBusy(false) }
  }
  const browseChannel = async (channel: CodeChannelEntry, path = '') => {
    setCodeBusy(true)
    setActiveChannel(channel)
    setActiveCodeFile(null)
    try {
      setCodeTree(await invoke<CodeTreeSnapshot>('browse_code_channel', { input: { channelId: channel.channelId, path } }))
    } catch (error) { setCodeMessage(humanError(error, 'code')) }
    finally { setCodeBusy(false) }
  }
  const openCodeEntry = async (entry: CodeTreeEntry) => {
    if (!activeChannel) return
    if (entry.kind === 'directory') { await browseChannel(activeChannel, entry.path); return }
    setCodeBusy(true)
    setCodeMode('human')
    try {
      setActiveCodeFile(await invoke<CodeFileProjection>('read_code_channel_file', {
        input: { channelId: activeChannel.channelId, path: entry.path },
      }))
    } catch (error) { setCodeMessage(humanError(error, 'code')) }
    finally { setCodeBusy(false) }
  }
  const codeParent = () => codeTree?.path.split('/').filter(Boolean).slice(0, -1).join('/') || ''

  const performRepoLogin = async (event: React.FormEvent) => {
    event.preventDefault()
    setLoginBusy(true)
    setLoginMessage('')
    try {
      const expectedFifthDomainAccount: Record<string, string> = {
        'ICE-GL∞': 'bingshuo',
        'ICE-GL-ZHI∞': 'zhizhi',
      }
      const expectedAccount = expectedFifthDomainAccount[zeroPoint?.userNumber || '']
      if (expectedAccount && loginUsername.trim().toLowerCase() !== expectedAccount) {
        throw new Error('HOLOLAKE_LOGIN_ACCOUNT_NUMBER_MISMATCH')
      }
      const receipt = await invoke<LoginReceipt>('perform_code_repo_login', { username: loginUsername.trim(), password: loginPassword })
      // 五湖开场：校验通过=第五域从湖面浮起，镜头沉入湖中再进场。
      setLoginRising(true)
      await new Promise((resolve) => setTimeout(resolve, 1300))
      // 账号切换时先清空上一账号的内存投影，绝不让旧页面在新会话首帧闪现。
      setPersonal(previewPersonal)
      setKnowledge(previewKnowledge)
      setCodeChannels(previewCode)
      setActiveDocument(null)
      setActiveChannel(null)
      setCodeTree(null)
      setActiveCodeFile(null)
      setReceipts([])
      setRepoLogin({ username: receipt.username, host: receipt.host, domain: receipt.domain, signedInAtUnixMs: Date.now() })
      setWorldStage('domain')
      setView('overview')
      setLoginRising(false)
      setLoginPassword('')
    } catch (error) { setLoginMessage(humanError(error, 'login')) }
    finally { setLoginBusy(false) }
  }
  const changeFirstLoginPassword = async (event: React.FormEvent) => {
    event.preventDefault()
    if (newLoginPassword !== confirmLoginPassword) {
      setLoginMessage('两次输入的新密码不一致。')
      return
    }
    setLoginBusy(true)
    setLoginMessage('')
    try {
      await invoke('change_first_login_password', {
        username: loginUsername.trim(),
        currentPassword: loginPassword,
        newPassword: newLoginPassword,
      })
      setLoginPassword(newLoginPassword)
      setNewLoginPassword('')
      setConfirmLoginPassword('')
      setPasswordChangeMode(false)
      setLoginMessage('密码已更新。请用新密码验证并进入。')
    } catch (error) { setLoginMessage(humanError(error, 'login')) }
    finally { setLoginBusy(false) }
  }
  const signOutRepo = async () => {
    try { await invoke('sign_out_code_repo_login') } catch { /* 登出以本机清场为准 */ }
    setPersonal(previewPersonal)
    setKnowledge(previewKnowledge)
    setCodeChannels(previewCode)
    setActiveDocument(null)
    setActiveChannel(null)
    setCodeTree(null)
    setActiveCodeFile(null)
    setReceipts([])
    setEnterpriseEntry(null)
    setEnterpriseWork(null)
    setEnterpriseReceiptMessage('')
    setWorldStage('domain')
    setRepoLogin(null)
  }
  const confirmEnterpriseRelationship = async (decision: 'CONFIRM' | 'REJECT') => {
    setEnterpriseReceiptBusy(true)
    setEnterpriseReceiptMessage('')
    try {
      const receipt = await invoke<EnterpriseReceiptEnvelope>('confirm_enterprise_persona_relationship', {
        decision,
        idempotencyKey: `relationship-${crypto.randomUUID().replaceAll('-', '')}`,
      })
      await loadEnterpriseEntry()
      const projected = receipt.repository_projection?.state === 'COMMITTED' || receipt.repository_projection?.state === 'IDEMPOTENT_READBACK'
      setEnterpriseReceiptMessage(decision === 'CONFIRM'
        ? projected ? '人格关系确认已签署，并写入本人私有工作仓库。' : '人格关系确认已签署并留存。'
        : projected ? '人格关系异议已签署，并写入本人私有工作仓库。' : '人格关系异议已签署并留存。')
    } catch (error) {
      setEnterpriseReceiptMessage(humanError(error, 'login'))
    } finally {
      setEnterpriseReceiptBusy(false)
    }
  }
  const submitEnterpriseResponsibility = async (decision: 'ACCEPT' | 'DECLINE') => {
    if (!enterpriseEntry) return
    setEnterpriseReceiptBusy(true)
    setEnterpriseReceiptMessage('')
    try {
      const receipt = await invoke<EnterpriseReceiptEnvelope>('submit_enterprise_responsibility_receipt', {
        decision,
        note: responsibilityNote.trim(),
        responsibilityVersion: enterpriseEntry.registry_version,
        idempotencyKey: `responsibility-${crypto.randomUUID().replaceAll('-', '')}`,
      })
      setResponsibilityNote('')
      await loadEnterpriseEntry()
      const projected = receipt.repository_projection?.state === 'COMMITTED' || receipt.repository_projection?.state === 'IDEMPOTENT_READBACK'
      setEnterpriseReceiptMessage(decision === 'ACCEPT'
        ? projected ? '域责任已由本人接受、签署，并写入本人私有工作仓库。' : '域责任已由本人接受并签署。'
        : projected ? '域责任拒绝回执已签署，并写入本人私有工作仓库。' : '域责任拒绝回执已留存。')
    } catch (error) {
      setEnterpriseReceiptMessage(humanError(error, 'login'))
    } finally {
      setEnterpriseReceiptBusy(false)
    }
  }
  const initializeIdentity = async (event: React.FormEvent) => {
    event.preventDefault()
    setIdentityBusy(true)
    try {
      setPersonal(await invoke<PersonalChannelSnapshot>('initialize_personal_channel', { input: { displayName } }))
      setDisplayName('')
    } catch (error) { setIdentityMessage(humanError(error, 'identity')) }
    finally { setIdentityBusy(false) }
  }
  const issueInvitation = async () => {
    setSystemBusy(true)
    setSystemMessage('')
    try {
      setTicket(await invoke<DiscoveryTicketReceipt>('issue_direct_local_discovery_ticket', {
        input: {
          accountId: getOrCreateLocalId('hololake-local-account', 'human-local'),
          laneId: 'personal-channel',
          clientInstanceId: getOrCreateLocalId('hololake-external-ai-client', 'external-ai'),
        },
      }))
      setSystemMessage('一次性发现凭据已生成。连接成功后，状态条会显示真实在线数。')
    } catch (error) { setSystemMessage(humanError(error, 'system')) }
    finally { setSystemBusy(false) }
  }
  const invitationText = ticket ? JSON.stringify({
    schema: 'hololake.direct-local-invitation/v2',
    terminalTransport: ticket.terminalTransport,
    connector: {
      executable: ticket.connectorExecutable,
      arguments: ticket.connectorArguments,
      framing: 'JSON_LINES',
    },
    continuityOwner: 'HOLOLAKE',
    mcpRole: 'DISCOVERY_RECOVERY_COMPATIBILITY_ONLY',
    heartbeatIntervalMs: ticket.heartbeatIntervalMs,
    environmentRefreshIntervalMs: ticket.environmentRefreshIntervalMs,
    requiredBootstrapOperations: ticket.requiredBootstrapOperations,
    openSession: {
      operation: 'OPEN_SESSION',
      input: {
        accountId: window.localStorage.getItem('hololake-local-account'),
        laneId: ticket.laneId,
        clientInstanceId: ticket.clientInstanceId,
        discoveryTicket: ticket.discoveryTicket,
      },
    },
    afterOpen: [
      'ACQUIRE_DEVELOPMENT_WRITE_LANE',
      'GET_WORK_ENVIRONMENT',
    ],
    beforeEveryMutation: 'GET_WORK_ENVIRONMENT',
    protocolRestorationByModelRequired: false,
  }, null, 2) : ''
  const copyInvitation = async () => {
    try {
      await navigator.clipboard.writeText(invitationText)
      setSystemMessage('连接凭据已复制。')
    } catch { setSystemMessage('复制失败，请手动选择凭据。') }
  }
  const checkUpdate = async () => {
    setSystemBusy(true)
    try {
      const result = await invoke<ReleaseCheckReceipt>('check_hololake_update')
      setReleaseCandidate(result.candidate || null)
      setSystemMessage(result.candidate ? '发现已签名更新。' : '当前没有可安装更新。')
    } catch (error) { setSystemMessage(humanError(error, 'system')) }
    finally { setSystemBusy(false) }
  }
  const installUpdate = async () => {
    if (!releaseCandidate) return
    setSystemBusy(true)
    try {
      await invoke('confirm_hololake_update_install', {
        input: { candidateId: releaseCandidate.candidateId, confirmationToken: releaseCandidate.confirmationToken },
      })
      setSystemMessage('更新安装已启动。')
    } catch (error) { setSystemMessage(humanError(error, 'system')) }
    finally { setSystemBusy(false) }
  }

  const bindZeroPoint = async () => {
    if (!zpNumber.trim()) return
    setZpBusy(true); setZpMessage('')
    try {
      const bound = await invoke<ZeroPointSnapshot>('zero_point_bind', { input: { number: zpNumber.trim() } })
      setZeroPoint(bound)
      const verified = await invoke<ZeroPointSnapshot>('zero_point_verify')
      setZeroPoint(verified)
      setZpMessage(verified.route === 'verified' ? '编号验证通过。' : '编号未通过验证，受限功能保持关闭。')
    } catch (error) { setZpMessage(String(error)) } finally { setZpBusy(false) }
  }
  const verifyZeroPoint = async () => {
    setZpBusy(true); setZpMessage('')
    try {
      const snapshot = await invoke<ZeroPointSnapshot>('zero_point_verify')
      setZeroPoint(snapshot)
      setZpMessage(snapshot.route === 'verified' ? '编号验证通过。' : '编号未通过验证，受限功能保持关闭。')
    } catch (error) { setZpMessage(String(error)) } finally { setZpBusy(false) }
  }
  const syncZeroPoint = async () => {
    setZpBusy(true); setZpMessage('')
    try { setZeroPoint(await invoke<ZeroPointSnapshot>('zero_point_sync')) } catch (error) { setZpMessage(String(error)) } finally { setZpBusy(false) }
  }
  const renderOverview = () => (
    <section className="content-page overview-page">
      <header className="page-title">
        <div><span className="kicker">PERSONAL CHANNEL</span><h1>个人频道</h1><p>统一访问本机知识、代码、运行状态与可核验回执。</p></div>
        <button className="evidence-pill" type="button" onClick={() => setView('system')}><i className={connectionOnline ? 'online' : ''}/>{connectionLabel}</button>
      </header>
      <div className="overview-grid">
        <button className="metric-panel" type="button" onClick={() => setView('knowledge')}><span>唯一知识页</span><strong>{knowledge.uniqueDocumentCount}</strong><small>{knowledge.duplicateDocumentCount} 份相同内容已折叠</small></button>
        <button className="metric-panel" type="button" onClick={() => setView('code')}><span>代码频道</span><strong>{codeChannels.channels.length}</strong><small>可浏览、可转译、本机只读接入</small></button>
        <button className="metric-panel" type="button" onClick={() => setView('receipts')}><span>可核验回执</span><strong>{personal.integrity.receiptCount + status.pnccReceiptCount}</strong><small>身份、知识与代码证据</small></button>
      </div>
      {timeAuthorityModule && <button className="time-module-strip" type="button" onClick={openEraTimeline}>
        <span><i/><b>{timeAuthorityModule.displayName}</b><small>初始化频道内置模块 · {timeAuthorityModule.calendarName}</small></span>
        <strong>{beijingCoordinate ? `第 ${beijingCoordinate.guanghuEraDay} 天` : '时间正在流动'}</strong>
        <time>{displayBeijingTime(beijingCoordinate)}</time>
        <em>{beijingCoordinate?.networkSyncState === 'SYNCHRONIZED_ON_APPLICATION_OPEN' ? '打开软件时已联网校时' : '本机现实时间 · 等待联网校时'}</em>
      </button>}
      <div className="overview-columns">
        <section className="plain-panel recent-panel">
          <header><div><h2>最近知识</h2><p>从真实页面继续阅读</p></div><button type="button" onClick={() => setView('knowledge')}>打开工作台</button></header>
          {knowledge.documents.slice().sort((a, b) => b.updatedAtUnixMs - a.updatedAtUnixMs).slice(0, 7).map((item) =>
            <button className="recent-row" key={`${item.source}:${item.path}`} type="button" onClick={() => { setView('knowledge'); void openDocument(item.source, item.path) }}>
              <Icon name="file"/><span><b>{item.title}</b><small>{item.path}</small></span><time>{new Date(item.updatedAtUnixMs).toLocaleDateString('zh-CN')}</time>
            </button>)}
        </section>
        <section className="plain-panel system-proof">
          <header><div><h2>运行状态</h2><p>以下信息均来自当前进程与已登记运行源。</p></div></header>
          <dl><div><dt>Unix 本地代理</dt><dd>{status.directLocalBrokerState}</dd></div><div><dt>在线客户端</dt><dd>{status.directConnectionCount}</dd></div><div><dt>可续接会话</dt><dd>{status.resumableSessionCount}</dd></div><div><dt>PNCC 投影回执</dt><dd>{status.pnccReceiptCount}</dd></div><div><dt>MCP</dt><dd>备用 / 恢复</dd></div></dl>
          <button className="secondary-button" type="button" onClick={() => setView('system')}>查看验证入口</button>
        </section>
      </div>
    </section>
  )

  const renderKnowledge = () => (
    <section className="full-workbench knowledge-page">
      <aside className="knowledge-browser">
        <header><div><span className="kicker">KNOWLEDGE</span><h1>知识工作台</h1></div><button className="icon-button" title="导入文件夹" type="button" disabled={knowledgeBusy} onClick={() => void importKnowledge()}><Icon name="import"/></button></header>
        <form className="search-box" onSubmit={(event) => void runSearch(event)}>
          <Icon name="search"/><input aria-label="检索知识" value={searchQuery} placeholder="检索标题与正文" onChange={(event) => setSearchQuery(event.target.value)}/>
          {searchResults && <button type="button" onClick={() => { setSearchResults(null); setSearchQuery('') }}>清除</button>}
        </form>
        <div className="knowledge-counts"><span>{knowledge.uniqueDocumentCount} 篇唯一文档</span><span>{knowledge.duplicateDocumentCount} 份重复已折叠</span></div>
        <div className="knowledge-tree" aria-busy={knowledgeBusy}>
          {visibleDocuments.length
            ? <KnowledgeTree node={tree} depth={0} expanded={expanded} active={activeDocument ? `${activeDocument.source}:${activeDocument.path}` : undefined}
                onToggle={(key) => setExpanded((current) => { const next = new Set(current); if (next.has(key)) next.delete(key); else next.add(key); return next })}
                onOpen={(item) => void openDocument(item.source, item.path)}
                onRemoveFolder={(folder) => void removeFolder(folder)}
                folderMenuKey={folderMenuKey}
                onFolderMenuToggle={(key) => setFolderMenuKey((current) => (current === key ? null : key))}/>
            : <div className="empty-state">没有匹配的知识页</div>}
        </div>
        <footer>{knowledgeMessage || (lastKnowledgeReceipt ? `Git ${lastKnowledgeReceipt.slice(0, 10)}` : '导入会自动检查相同内容')}</footer>
      </aside>
      <main className="document-workspace">
        {activeDocument ? <>
          <header className="document-toolbar">
            <div className="breadcrumbs"><span>{activeDocument.source === 'legacy' ? 'HoloLake Era · 只读源' : '我的知识库'}</span><b>/</b><span>{activeDocument.path}</span></div>
            <div className="toolbar-actions"><button className="toolbar-button" type="button" title={inspectorOpen ? '收起右侧大纲与证据' : '展开右侧大纲与证据'} onClick={toggleInspector}><Icon name="chevron"/>{inspectorOpen ? '收起大纲' : '展开大纲'}</button>{editing
              ? <><button className="toolbar-button" type="button" onClick={() => { setEditing(false); setDraft(activeDocument.body) }}>取消</button><button className="toolbar-button primary" type="button" disabled={knowledgeBusy} onClick={() => void saveDocument()}><Icon name="save"/>保存</button></>
              : <><div className="toolbar-menu"><button className="toolbar-button" type="button" title="页面操作与常用功能" disabled={knowledgeBusy} onClick={() => setSettingsMenuOpen((current) => !current)}><Icon name="settings"/> 设置<Icon name="chevronDown"/></button>{settingsMenuOpen && <div className="toolbar-menu-pop"><button type="button" disabled={knowledgeBusy} onClick={() => { setSettingsMenuOpen(false); void createDocument() }}><Icon name="plus"/>新建空白页</button><button type="button" disabled={knowledgeBusy} onClick={() => { setSettingsMenuOpen(false); void importKnowledge() }}><Icon name="import"/>导入知识库文件夹</button>{activeDocument.writable && <button type="button" onClick={() => { setSettingsMenuOpen(false); setDraft(activeDocument.body); setEditing(true) }}><Icon name="edit"/>编辑这一页</button>}{activeDocument.writable && <button type="button" disabled={knowledgeBusy} onClick={() => { setSettingsMenuOpen(false); void removeDocument() }}><Icon name="trash"/>删除这一页（进回收站）</button>}<span className="toolbar-menu-sep"/><button type="button" disabled={knowledgeBusy} onClick={() => { setSettingsMenuOpen(false); void downloadDocument('md') }}><Icon name="download"/>下载 Markdown</button><button type="button" disabled={knowledgeBusy} onClick={() => { setSettingsMenuOpen(false); void downloadDocument('html') }}><Icon name="download"/>下载网页（.html）</button><button type="button" disabled={knowledgeBusy} onClick={() => { setSettingsMenuOpen(false); void printDocument() }}><Icon name="download"/>下载 PDF（系统打印）</button></div>}</div></>}
            </div>
          </header>
          <div className="document-scroll" onScroll={handleReaderScroll}>
            {editing
              ? <textarea className="document-editor" aria-label="Markdown 编辑器" value={draft} onChange={(event) => setDraft(event.target.value)}/>
              : <><header className="reader-heading"><h1>{activeDocument.title}</h1>{docStats && <div className="meta-stats">{docStats.chars.toLocaleString()} 字 · 约 {docStats.minutes} 分钟读完{parsedDocument?.metadata?.created ? ` · 创建于 ${String(parsedDocument.metadata.created).slice(0, 10)}` : ''}{parsedDocument?.metadata?.updated ? ` · 更新于 ${String(parsedDocument.metadata.updated).slice(0, 10)}` : ''}</div>}{(parsedDocument?.tags?.length ?? 0) > 0 && <div className="meta-tags">{parsedDocument!.tags.map((tag) => <span key={tag} className={tagTint(tag)}>{tag}</span>)}</div>}<div>{Object.entries(parsedDocument?.metadata || {}).filter(([key]) => key !== 'tags').slice(0, 5).map(([key, value]) => <span key={key}>{key} · {value}</span>)}</div></header><MarkdownDocument body={activeDocument.body} knownTitles={knowledge.documents.map((doc) => doc.title)} onWiki={openWiki}/></>}
          </div>
        </> : <div className="workbench-empty"><span>光</span><h2>选择一篇知识页</h2><p>目录、正文与版本证据会在同一个工作台中展开。</p><button className="primary-button" type="button" onClick={() => void importKnowledge()}>导入本地文件夹</button></div>}
      </main>
      {inspectorOpen && <aside className="document-inspector">
        <div className="inspector-tabs"><span className="active">大纲</span><span>来源</span><span>回执</span></div>
        {activeDocument ? <div className="inspector-scroll">
          <section><h2>页面大纲</h2>{outline.length ? <nav className="outline-list">{outline.map((item) => <button key={item.id} type="button" title="跳到该章节" className={activeHeadingId === item.id ? 'active' : ''} style={{ paddingLeft: 8 + (item.level - 1) * 11 }} onClick={() => jumpToHeading(item.id)}>{item.title}</button>)}</nav> : <p>当前页面没有标题层级。</p>}</section>
          <section><h2>来源</h2><dl><div><dt>知识根</dt><dd>{activeDocument.source === 'native' ? 'HoloLake 本机 Git' : 'HoloLake Era 只读供体'}</dd></div><div><dt>路径</dt><dd>{activeDocument.path}</dd></div><div><dt>内容指纹</dt><dd>{activeDocument.contentSha256.slice(0, 16)}</dd></div><div><dt>相同内容</dt><dd>{activeSummary?.duplicateCount || 0} 份已折叠</dd></div></dl></section>
          <section><h2>页面状态</h2><p>{activeDocument.writable ? '可编辑；保存时写入本机 Git。' : '供体原件只读；不会被修改。'}</p>{lastKnowledgeReceipt && <code>{lastKnowledgeReceipt}</code>}</section>
        </div> : <div className="empty-state">选择页面后显示大纲与证据</div>}
      </aside>}
    </section>
  )

  const renderCode = () => (
    <section className="full-workbench code-workbench">
      <aside className="code-channels">
        <header><div><span className="kicker">{repoLogin?.domain === 'FIFTH_DOMAIN' ? 'GH-PNCC' : 'ENTERPRISE WORK REPOSITORY'}</span><h1>{repoLogin?.domain === 'FIFTH_DOMAIN' ? '人格原生代码频道' : '私有责任工作仓库'}</h1></div></header>
        <section className="pncc-native-card">
          <div className="pncc-native-card-title"><span className={userPncc || enterpriseWork ? 'identity-dot ready' : 'identity-dot'}/><div><b>{repoLogin?.domain === 'FIFTH_DOMAIN' ? userPncc ? `${userPncc.accountUsername} · GH-PNCC` : '正在建立用户频道' : enterpriseWork ? `${repoLogin?.username} · 私有工作仓库` : '正在认证工作仓库'}</b><small>{userPnccBusy ? '正在同步 Git…' : userPncc ? `${userPncc.branch} · ${userPncc.gitHead.slice(0, 8)}` : enterpriseWork ? 'main · 认证只读投影' : '等待可信绑定'}</small></div></div>
          {repoLogin?.domain === 'FIFTH_DOMAIN' && userPncc ? <dl><div><dt>所属域</dt><dd>{domainDisplayName(userPncc.domain)}</dd></div><div><dt>用户编号</dt><dd>{userPncc.userNumber}</dd></div><div><dt>耐久化引擎</dt><dd>Git</dd></div><div><dt>可见上层</dt><dd>HoloLake 原生界面</dd></div><div><dt>Forgejo 协作适配器</dt><dd>账号已认证 · 远端仓未绑定</dd></div></dl> : repoLogin?.domain !== 'FIFTH_DOMAIN' && enterpriseWork ? <dl><div><dt>入口</dt><dd>光湖零感域 · 光湖频道</dd></div><div><dt>责任域</dt><dd>{domainDisplayName(enterpriseWork.responsibilityDomain)}</dd></div><div><dt>私有仓库</dt><dd>{enterpriseWork.repository}</dd></div><div><dt>访问边界</dt><dd>本人认证 · 本机只读 · 禁止推送</dd></div><div><dt>个人节点</dt><dd>未由企业账号授权</dd></div></dl> : <p>{userPnccMessage || '系统先按编号确定所属域，再通过该域的账号与节点入口建立频道。'}</p>}
          {userPncc && <button type="button" onClick={() => { const channel = codeChannels.channels.find((item) => item.channelId === userPncc.channelId); if (channel) void browseChannel(channel) }}>打开我的频道</button>}
          {enterpriseWork && <button type="button" onClick={() => void openEnterpriseRepository()}>打开责任工作仓库</button>}
        </section>
        {repoLogin?.domain === 'FIFTH_DOMAIN' && <><div className="channel-section-label"><b>协作代码库</b><small>可接入已登记的远端或本机 Git</small></div>
        <form className="clone-form" onSubmit={(event) => void cloneCodeChannel(event)}>
          <label htmlFor="clone-url">克隆频道地址</label><div><input id="clone-url" type="url" value={cloneUrl} placeholder="https://guanghulab.com/code/…" onChange={(event) => setCloneUrl(event.target.value)}/><button disabled={!cloneUrl.trim() || codeBusy}>克隆</button></div>
        </form>
        <button className="local-folder-button" type="button" onClick={() => void selectLocalCodeChannel()}><Icon name="folder"/>导入本机 Git 文件夹</button></>}
        <div className="channel-selector">{codeChannels.channels.map((channel) => <button className={activeChannel?.channelId === channel.channelId ? 'active' : ''} key={channel.channelId} type="button" onClick={() => void browseChannel(channel)}><Icon name="code"/><span><b>{channel.name}</b><small>{channel.branch} · {channel.gitHead.slice(0, 8)}</small></span></button>)}</div>
        <footer>{codeMessage || userPnccMessage || (repoLogin?.domain === 'FIFTH_DOMAIN' ? 'Git 负责耐久化；Forgejo 仅作为远端协作适配器。' : '企业仓库是工作区，不授予个人频道或跨仓访问权。')}</footer>
      </aside>
      <aside className="repository-tree">
        <header><button className="icon-button" disabled={!codeTree?.path} type="button" onClick={() => activeChannel && void browseChannel(activeChannel, codeParent())}><Icon name="back"/></button><div><b>{activeChannel?.name || '尚未选择频道'}</b><small>/{codeTree?.path || ''}</small></div></header>
        <div className="repository-entries">{codeTree?.entries.map((entry) => <button key={entry.path} type="button" onClick={() => void openCodeEntry(entry)}><Icon name={entry.kind === 'directory' ? 'folder' : 'file'}/><span>{entry.name}</span>{entry.kind === 'directory' && <Icon name="chevron"/>}</button>) || <div className="empty-state">选择频道后浏览仓库</div>}</div>
      </aside>
      <main className="code-reader">
        {activeCodeFile ? <>
          <header><div><span>{activeCodeFile.path}</span><small>{activeCodeFile.format.toUpperCase()} · {activeCodeFile.sizeBytes.toLocaleString()} bytes</small></div><div className="mode-switch"><button className={codeMode === 'human' ? 'active' : ''} type="button" onClick={() => setCodeMode('human')}>知识视图</button><button className={codeMode === 'source' ? 'active' : ''} type="button" onClick={() => setCodeMode('source')}>源文件</button></div></header>
          <div className="code-reader-scroll">{codeMode === 'human' ? <MarkdownDocument body={activeCodeFile.humanMarkdown}/> : <pre className="source-code"><code>{activeCodeFile.source}</code></pre>}</div>
        </> : <div className="workbench-empty"><span>&lt;/&gt;</span><h2>{repoLogin?.domain === 'FIFTH_DOMAIN' ? 'GH-PNCC · 人格原生代码频道' : '企业责任工作仓库'}</h2><p>{repoLogin?.domain === 'FIFTH_DOMAIN' ? '这是 HoloLake 对用户 Git 代码频道的原生投影。选择“打开我的频道”可查看初始化清单、提交证据与真实文件。' : '这是本人唯一私有工作仓库的认证只读投影。责任确认回执会由企业灯塔写入该仓库。'}</p></div>}
      </main>
    </section>
  )

  const renderReceipts = () => (
    <section className="content-page">
      <header className="page-title"><div><span className="kicker">{repoLogin?.domain === 'FIFTH_DOMAIN' ? 'LOCAL RECEIPTS' : 'ENTERPRISE RESPONSIBILITY RECEIPTS'}</span><h1>回执</h1><p>{repoLogin?.domain === 'FIFTH_DOMAIN' ? '本机身份、知识与代码读取的可核验记录' : '本人签署的关系确认与责任接受状态'}</p></div></header>
      <div className="receipt-grid">
        {repoLogin?.domain === 'FIFTH_DOMAIN' ? <><section className="plain-panel"><h2>个人空间</h2>{personal.recentEvents.map((event) => <article className="receipt-row" key={event.eventId}><span>{String(event.sequence).padStart(2, '0')}</span><div><b>{event.summary}</b><small>{new Date(event.occurredAtUnixMs).toLocaleString('zh-CN')} · {event.receiptHash.slice(0, 12)}</small></div></article>)}</section>
        <section className="plain-panel"><h2>PNCC 读取投影</h2>{receipts.length ? receipts.map((receipt) => <article className="receipt-row" key={receipt.sequence}><span>{String(receipt.sequence).padStart(2, '0')}</span><div><b>{receipt.kind}</b><small>{new Date(Number(receipt.observedAtUnixMs)).toLocaleString('zh-CN')} · {receipt.eventHash.slice(0, 12)}</small></div></article>) : <div className="empty-state">尚无 PNCC 运行投影回执</div>}</section></> : <><section className="plain-panel"><h2>人格关系确认</h2><dl className="evidence-list"><div><dt>本人编号</dt><dd>{enterpriseEntry?.canonical_id || zeroPoint?.userNumber}</dd></div><div><dt>确认状态</dt><dd>{enterpriseEntry?.relationship_confirmation?.decision || '等待确认'}</dd></div><div><dt>签署时间</dt><dd>{enterpriseEntry?.relationship_confirmation?.observed_at || '—'}</dd></div><div><dt>回执指纹</dt><dd>{enterpriseEntry?.relationship_confirmation?.receipt_hash?.slice(0, 16) || '—'}</dd></div></dl></section>
        <section className="plain-panel"><h2>域责任接受</h2><dl className="evidence-list"><div><dt>责任域</dt><dd>{domainDisplayName(enterpriseEntry?.subject.domain || repoLogin?.domain || '')}</dd></div><div><dt>接受状态</dt><dd>{enterpriseEntry?.responsibility_receipt?.decision || '等待本人确认'}</dd></div><div><dt>责任版本</dt><dd>{enterpriseEntry?.responsibility_receipt?.responsibility_version || enterpriseEntry?.registry_version || '—'}</dd></div><div><dt>私有仓库</dt><dd>{enterpriseEntry?.repository_binding.repository || '—'}</dd></div></dl></section></>}
      </div>
    </section>
  )

  const renderSystem = () => (
    <section className="content-page">
      <header className="page-title"><div><span className="kicker">SYSTEM EVIDENCE</span><h1>系统详情</h1><p>显示可验证的当前状态；无法读取的项目将明确标记为不可用。</p></div></header>
      <div className="system-grid">
        <section className="plain-panel connection-panel">
          <header><div><h2>光湖近场连接</h2><p>外部 AI 可像发现附近网络一样发现本机 HoloLake；MCP 仅用于兼容与恢复。</p></div><span className={nearbyDiscovery?.automaticSameDeviceDiscovery ? 'status-chip online' : 'status-chip'}>{nearbyDiscovery?.automaticSameDeviceDiscovery ? '本机自动发现已开启' : '自动发现不可用'}</span></header>
          <dl className="evidence-list"><div><dt>圆湖协议膜</dt><dd>GLP/1.0 · 协议外输入丢弃</dd></div><div><dt>编程 AI 终端直连</dt><dd>{status.terminalLinkProtocol} · {status.directLocalBrokerState === 'READY' ? '原生通道就绪' : '等待账号登录'}</dd></div><div><dt>本机传输</dt><dd>{status.terminalLinkTransport.includes('NAMED_PIPE') ? 'Windows 用户私有 Named Pipe' : 'macOS / Linux 用户私有 Unix Socket'}</dd></div><div><dt>环境事实帧</dt><dd>连接、续接、心跳与写入前强制刷新</dd></div><div><dt>通用 AI 访客</dt><dd>{nearbyDiscovery?.genericAiVisitor === 'EXPRESSION_ONLY_READY' ? '可连接 · 仅语言表达' : '不可用'}</dd></div><div><dt>光湖人格体</dt><dd>{nearbyDiscovery?.guanghuPersona === 'BINDING_EVIDENCE_REQUIRED' ? '等待人格绑定证据' : '可连接'}</dd></div><div><dt>当前连接</dt><dd>{status.directConnectionCount}</dd></div><div><dt>可续接会话</dt><dd>{status.resumableSessionCount}</dd></div><div><dt>局域网发现</dt><dd>{nearbyDiscovery?.localNetworkDiscovery === 'DEFERRED_UNTIL_ENCRYPTED_TRANSPORT_AND_APPROVAL' ? '等待加密传输与确认闭环' : '已开启'}</dd></div><div><dt>MCP</dt><dd>仅兼容 / 发现 / 恢复</dd></div></dl>
          <p className="boundary-note">发现不等于授权。访客自然语言只有表达权，不能读取私人数据、调用工具或取得执行权限。</p>
          {ticket ? <><button className="secondary-button" type="button" onClick={() => void copyInvitation()}><Icon name="copy"/>复制兼容连接凭据</button><pre className="invitation-data">{invitationText}</pre></> : <button className="secondary-button" type="button" disabled={systemBusy} onClick={() => void issueInvitation()}>生成兼容连接凭据</button>}
        </section>
        <section className="plain-panel">
          <header><div><h2>京东主控 · GH-PNCC</h2><p>通过固定只读通道回读主控节点；不读取仓库正文，不授予写入权限。</p></div><span className={serverPnccReadback === 'LIVE' ? 'status-chip online' : 'status-chip'}>{serverPnccReadback === 'LIVE' ? '实时回读正常' : serverPnccReadback === 'UNAVAILABLE' ? '当前不可回读' : '正在读取'}</span></header>
          {serverPncc ? <dl className="evidence-list">
            <div><dt>人格仓库</dt><dd>{serverPncc.personaId}</dd></div>
            <div><dt>责任主体</dt><dd>{serverPncc.humanResponsibilitySubject}</dd></div>
            <div><dt>主控节点</dt><dd>{serverPncc.nodeId}</dd></div>
            <div><dt>驻留提交</dt><dd>{serverPncc.gitHead.slice(0, 12)}</dd></div>
            <div><dt>主租约</dt><dd>{serverPncc.primaryLeaseHeld ? '已持有' : '未持有'}</dd></div>
            <div><dt>载体绑定</dt><dd>{serverPncc.personaCarrierBound ? '已验证' : '未绑定 · 等待证据'}</dd></div>
            <div><dt>模型推理</dt><dd>{serverPncc.modelInferenceStarted ? '已启动' : '未启动'}</dd></div>
            <div><dt>现实执行</dt><dd>{serverPncc.realityExecutionAllowed ? '已授权' : '未授权'}</dd></div>
          </dl> : <p className="boundary-note">当前无法取得京东主控的实时回读。界面不会以静态记录替代在线状态。</p>}
          <button className="secondary-button" type="button" disabled={serverPnccBusy} onClick={() => void refreshServerPncc()}>{serverPnccBusy ? '正在读取…' : '重新读取主控状态'}</button>
        </section>
        <section className="plain-panel"><header><div><h2>HoloLake 编程执行环境</h2><p>HoloLake 持有会话连续性、环境事实帧和单写通道；外部编程 AI 只作为可续接载体进入。</p></div><span className={developmentLane?.state === 'ACTIVE' ? 'status-chip online' : 'status-chip'}>{developmentLane?.state === 'ACTIVE' ? '环境已锚定' : '等待直连写入者'}</span></header><dl className="evidence-list"><div><dt>终端直连协议</dt><dd>{status.terminalLinkProtocol}</dd></div><div><dt>协议恢复方式</dt><dd>HoloLake 系统自动运行 · 模型无需重读</dd></div><div><dt>已挂载仓库</dt><dd>{status.codeRepositoryMountCount}</dd></div><div><dt>投影回执</dt><dd>{status.pnccReceiptCount}</dd></div><div><dt>开发执行通道</dt><dd>{developmentLane?.state === 'ACTIVE' ? '已切入 HoloLake' : '等待受控载体'}</dd></div><div><dt>当前开发线</dt><dd>{developmentLane?.laneId || '—'}</dd></div><div><dt>当前写入载体</dt><dd>{developmentLane?.ownerInstanceId || '—'}</dd></div><div><dt>环境校验</dt><dd>{developmentLane?.state === 'ACTIVE' ? '每次写入前必须持有未过期事实帧' : '未取得单写通道，不允许变更'}</dd></div><div><dt>Agent Shell</dt><dd>第二阶段 · 当前未启用</dd></div></dl></section>
        <section className="plain-panel"><header><div><h2>GLS 协议运行层</h2><p>正本先完成注册对账和依赖分型；只有显式原生适配器进入执行图。</p></div><span className={glsRuntime?.state === 'ACTIVE_EXPLICIT_PROJECTIONS_ONLY' && glsRuntime.authorityConflictCount === 0 && glsRuntime.discoveredUnreconciledCount === 0 ? 'status-chip online' : 'status-chip'}>{glsRuntime ? '运行清单 v2 已加载' : '失败关闭'}</span></header>{glsRuntime ? <dl className="evidence-list"><div><dt>正本来源</dt><dd>{glsRuntime.sourceRepository} · {glsRuntime.sourceCommit.slice(0, 12)}</dd></div><div><dt>已发现编号协议</dt><dd>{glsRuntime.protocolCount}</dd></div><div><dt>协议注册表编号</dt><dd>{glsRuntime.protocolRegistryIdCount}</dd></div><div><dt>注册草案</dt><dd>{glsRuntime.registeredDraftCount} · {glsRuntime.registeredDraftNotStartedCount} 尚未实现</dd></div><div><dt>内嵌工程协议</dt><dd>{glsRuntime.executableProjectionCount} · P0–P6 共 {glsRuntime.implementationStageCount} 层</dd></div><div><dt>已收录待工程化</dt><dd>{glsRuntime.inventoriedNotExecutableCount}</dd></div><div><dt>已分型来源依赖</dt><dd>{glsRuntime.typedSourceDependencyCount} · 未分类 {glsRuntime.unclassifiedSourceDependencyCount}</dd></div><div><dt>旧来源关系环</dt><dd>{glsRuntime.legacyDependencyCycleCount} 组仅供审计 · 不进入运行图</dd></div><div><dt>缺少编号正本的依赖</dt><dd>{glsRuntime.dependencyGapCount}</dd></div><div><dt>登记冲突 / 未对账</dt><dd>{glsRuntime.authorityConflictCount} / {glsRuntime.discoveredUnreconciledCount}</dd></div><div><dt>原文直接执行</dt><dd>{glsRuntime.rawProtocolTextExecuted ? '允许' : '禁止'}</dd></div><div><dt>任意协议代码</dt><dd>{glsRuntime.arbitraryProtocolCodeAllowed ? '允许' : '禁止'}</dd></div></dl> : <p className="boundary-note">GLS 运行清单不可读，协议适配器全部保持关闭。</p>}</section>
        <section className="plain-panel"><header><div><h2>HoloLake 原生协议内核</h2><p>协议规则已编入软件本体；每次允许、拒绝、歧义和未核验裁决都写入本机哈希链回执。</p></div><span className={glsKernel?.state === 'P1_TO_P6_NATIVE_P7_FAIL_CLOSED' ? 'status-chip online' : 'status-chip'}>{glsKernel ? '随软件运行' : '失败关闭'}</span></header>{glsKernel ? <dl className="evidence-list"><div><dt>P1–P6 原生器官</dt><dd>{glsKernel.executableProtocolCount} 份合同 · {glsKernel.implementedStageCount} 个阶段</dd></div><div><dt>协议裁决回执</dt><dd>{glsKernel.decisionReceiptCount}</dd></div><div><dt>允许 / 拒绝</dt><dd>{glsKernel.allowCount} / {glsKernel.denyCount}</dd></div><div><dt>歧义 / 未核验</dt><dd>{glsKernel.ambiguousCount} / {glsKernel.unverifiedCount}</dd></div><div><dt>GLC 自举一致性</dt><dd>{glsKernel.bootstrapCompilerSelfCheck === 'PASS_DETERMINISTIC_DOUBLE_COMPILE' ? '双编译一致' : '失败关闭'}</dd></div><div><dt>P7 物理能力</dt><dd>{glsKernel.p7VerifiedPhysicalCapabilityCount} 已获本机目标证据 · {glsKernel.p7NodeAssemblies.length} 项装配边界</dd></div><div><dt>模型可改写裁决</dt><dd>{glsKernel.modelCanOverrideDecision ? '允许' : '禁止'}</dd></div><div><dt>回执链末端</dt><dd>{glsKernel.lastReceiptSha256 === 'GENESIS' ? '尚无裁决' : glsKernel.lastReceiptSha256.slice(0, 16)}</dd></div></dl> : <p className="boundary-note">原生协议内核不可读，所有协议裁决保持关闭。</p>}</section>
        <section className="plain-panel"><header><div><h2>零点原核编号内核</h2><p>先按权威图确定主体类别与登记面，再进入编号核验；编号外形本身不构成权威。</p></div><span className={numberingKernel?.state === 'ACTIVE_PINNED_AUTHORITY_MAP' ? 'status-chip online' : 'status-chip'}>{numberingKernel ? '本机内核已加载' : '失败关闭'}</span></header>{numberingKernel ? <dl className="evidence-list"><div><dt>权威图</dt><dd>{numberingKernel.authorityMapId}</dd></div><div><dt>权威图版本</dt><dd>{numberingKernel.authorityMapVersion}</dd></div><div><dt>正本提交</dt><dd>{numberingKernel.sourceCommit.slice(0, 12)}</dd></div><div><dt>人类入口命名空间</dt><dd>{numberingKernel.humanRouteNamespaces.join(' · ')}</dd></div><div><dt>自动派发身份号</dt><dd>{numberingKernel.automaticIdentityIssuance ? '已开启' : '禁止'}</dd></div><div><dt>未知编号</dt><dd>{numberingKernel.unknownNumber === 'FAIL_CLOSED' ? '失败关闭 · 不猜测' : numberingKernel.unknownNumber}</dd></div></dl> : <p className="boundary-note">编号内核不可读，所有编号路由保持关闭。</p>}</section>
        <section className="plain-panel">
          <header><div><h2>用户编号验证</h2><p>用户编号必须通过登记服务验证。验证结果不构成人格绑定、模型载体绑定或执行授权。</p></div><span className={zeroPoint?.route === 'verified' ? 'status-chip online' : 'status-chip'}>{zeroPoint ? (zeroPoint.route === 'verified' ? '验证有效' : '功能受限') : '正在读取'}</span></header>
          <dl className="evidence-list">
            <div><dt>绑定状态</dt><dd>{zeroPoint ? (zeroPoint.binding === 'bound' ? `已绑定（${zeroPoint.userNumber}）` : '等待绑定（空白态）') : '—'}</dd></div>
            <div><dt>协议来源</dt><dd>{zeroPoint ? protocolOriginDisplayName(zeroPoint.protocol.origin) : '—'}</dd></div>
            <div><dt>离线有效期</dt><dd>{zeroPoint ? `${zeroPoint.protocol.gracePeriodDays} 天` : '—'}</dd></div>
            <div><dt>同步状态</dt><dd>{zeroPoint?.syncNote ?? '—'}</dd></div>
          </dl>
          <div className="zp-api-row">
            <input value={zpNumber} placeholder="输入用户编号，如 ICE-GL∞" onChange={(event) => setZpNumber(event.target.value)}/>
            <button className="secondary-button" type="button" disabled={zpBusy || !zpNumber.trim()} onClick={() => void bindZeroPoint()}>绑定并校验</button>
            <button className="secondary-button" type="button" disabled={zpBusy || zeroPoint?.binding !== 'bound'} onClick={() => void verifyZeroPoint()}>重新校验编号</button>
            <button className="secondary-button" type="button" disabled={zpBusy} onClick={() => void syncZeroPoint()}>检查协议版本</button>
          </div>
          {zpMessage && <p className="global-message">{zpMessage}</p>}
        </section>
        <section className="plain-panel"><header><div><h2>显示主题</h2><p>主题仅调整视觉令牌，不改变功能、权限或路由。</p></div></header><div className="theme-options">{themes.map((choice) => <button className={theme === choice.id ? 'active' : ''} key={choice.id} type="button" onClick={() => setTheme(choice.id)}><i className={choice.id}/><span>{choice.name}</span></button>)}</div></section>
        <section className="plain-panel"><header><div><h2>软件更新</h2><p>仅接受已登记信任根验证通过的 HoloLake 发布包。</p></div></header>{releaseCandidate ? <div className="release-summary"><b>HoloLake {releaseCandidate.version}</b><p>{releaseCandidate.notes}</p><button className="primary-button" onClick={() => void installUpdate()}>验证并安装</button></div> : <button className="secondary-button" disabled={systemBusy} onClick={() => void checkUpdate()}>检查签名更新</button>}</section>
      </div>
      {systemMessage && <p className="global-message">{systemMessage}</p>}
    </section>
  )

  const openWorldTool = (nextView: ViewId) => {
    setView(nextView)
    setToolReturnStage(worldStage === 'tool' ? 'channel' : worldStage)
    setWorldStage('tool')
  }

  const openEnterpriseRepository = async () => {
    if (!enterpriseWork) {
      setUserPnccMessage('本人私有责任工作仓库尚未完成可信接入。')
      return
    }
    const channel = codeChannels.channels.find((item) => item.channelId === enterpriseWork.channelId)
    if (!channel) {
      setUserPnccMessage('工作仓库已完成认证，正在等待本机只读投影登记。')
      await refreshCore()
      return
    }
    await browseChannel(channel)
    setView('code')
    setToolReturnStage('enterpriseWork')
    setWorldStage('tool')
  }

  const enterpriseRelationshipPending = Boolean(repoLogin && repoLogin.domain !== 'FIFTH_DOMAIN' && enterpriseEntry && enterpriseEntry.relationship_confirmation?.decision !== 'CONFIRM')
  const enterpriseResponsibilityPending = Boolean(repoLogin && repoLogin.domain !== 'FIFTH_DOMAIN' && enterpriseEntry && !enterpriseRelationshipPending && enterpriseEntry.responsibility_receipt?.decision !== 'ACCEPT')

  if (!repoLogin) {
    const resolvedDomain = zeroPoint?.resolvedDomain || ''
    const activeGate = domainGates.find((gate) => gate.domain === activeDomainInfo)
    return <div className={`official-world${motionAwake ? ' motion-awake' : ''}${loginRising ? ' sinking' : ''}`} onPointerMove={wakeAmbientMotion} onPointerDown={wakeAmbientMotion} onKeyDown={wakeAmbientMotion}>
      <LakeAtmosphere awake={motionAwake}/>
      <header className="world-titlebar"><b>HoloLake</b><button type="button" aria-label="显示主题" onClick={() => setTheme(themes[(themes.findIndex((item) => item.id === theme) + 1) % themes.length].id)}>◌</button></header>
      <main className={`world-scene${gateRising ? ' resolving' : ''}${gateStage === 'key' ? ' resolved' : ''}`}>
        <div className="official-hero"><h1>光湖语言系统 · 通用人工智能操作平台</h1><p>GH-AIOS · GUANGHU AI OPERATING SYSTEM</p></div>
        {domainGates.map((gate) => <LakePool key={gate.domain} className={gate.className} title={gate.title} meta={gate.gate} open={gate.domain === 'FIFTH_DOMAIN' || (gateStage === 'key' && gate.domain === resolvedDomain)} risen={(gateRising || gateStage === 'key') && gate.domain === resolvedDomain} onClick={() => gateStage === 'number' && setActiveDomainInfo(gate.domain)}/>) }
        {activeGate && gateStage === 'number' && <>
          <button className="domain-info-scrim" type="button" aria-label="关闭域信息" onClick={() => setActiveDomainInfo('')}/>
          <section className={`domain-info-card info-${activeGate.className.slice(2)}`} role="dialog" aria-modal="true" aria-label={`${activeGate.title}系统信息`}>
            <button className="gate-close" type="button" aria-label="关闭域信息" title="关闭" onClick={() => setActiveDomainInfo('')}>×</button>
            <b>{activeGate.title}</b><small>{activeGate.gate}</small>
            <span className="pool-facts">{activeGate.facts.map(([label, value]) => <span className="pool-fact" key={label}><em>{label}</em><strong>{value}</strong></span>)}</span>
          </section>
        </>}
        {gateRising ? <section className="world-welcome" role="status">
          <h2>编号 {gateNumber} · 欢迎登入光湖语言世界</h2>
          <p>RESOLVED · {domainDisplayName(resolvedDomain)} · 已接入</p>
          {gateWelcomeLine && <blockquote className="world-impression">{gateWelcomeLine}</blockquote>}
        </section> : gateStage === 'number' ? <section className={`number-nucleus${gateOpen ? ' open' : ''}`} title="输入编号进入所属域">
          <button className="nucleus-locus" type="button" aria-expanded={gateOpen} onClick={() => setGateOpen(true)}><i/><b>编号验证 · 进入世界的第一个入口</b></button>
          {gateOpen && <button
            className="gate-dismiss-layer"
            type="button"
            aria-label="关闭编号验证"
            onClick={() => { setGateOpen(false); setGateMessage('') }}
          />}
          <div className="nucleus-panel" role="dialog" aria-label="编号验证">
            <button className="gate-close" type="button" aria-label="关闭编号验证" title="关闭" onClick={() => { setGateOpen(false); setGateMessage('') }}>×</button>
            <h2>编号验证</h2>
            <div className="gate-pod-row">
              <input id="gate-number" ref={gateInputRef} aria-label="编号" maxLength={48} value={gateNumber} placeholder="如 ICE-GL∞" onChange={(event) => onGateInput(event.target.value)} onKeyDown={(event) => { if (event.key === 'Enter' && gateNumber) { event.preventDefault(); void gateVerifyNumber() } }}/>
              <button type="button" className={`gate-inf${gateInf ? ' on' : ''}`} title="编号包含无限符号时启用" aria-pressed={gateInf} onClick={() => setGateInf((value) => !value)}>∞</button>
            </div>
            <button className="gate-submit" disabled={gateBusy || !gateNumber} onClick={() => void gateVerifyNumber()}>{gateBusy ? '正在验证…' : '验证编号'}</button>
            {gateMessage && <p className="gate-hint">{gateMessage}</p>}
          </div>
        </section> : <>
          <section className="resolved-heading"><h2>编号 {zeroPoint?.userNumber || gateNumber} · 欢迎登入光湖语言世界</h2><p>RESOLVED · {domainDisplayName(resolvedDomain)} · 已接入</p>{gateWelcomeLine && <blockquote className="world-impression">{gateWelcomeLine}</blockquote>}</section>
          <section className={`domain-credential${loginRising ? ' fade-out' : ''}`} role="dialog">
            <form onSubmit={(event) => void (passwordChangeMode ? changeFirstLoginPassword(event) : performRepoLogin(event))}>
              <h3>{domainDisplayName(resolvedDomain)} · 域凭证</h3>
              <input id="repo-login-username" aria-label="账号" autoFocus maxLength={40} value={loginUsername} placeholder="账号" onChange={(event) => setLoginUsername(event.target.value)}/>
              <input id="repo-login-password" aria-label={passwordChangeMode ? '一次性密码' : '密码'} type="password" maxLength={512} value={loginPassword} placeholder={passwordChangeMode ? '一次性密码' : '密码'} onChange={(event) => setLoginPassword(event.target.value)}/>
              {passwordChangeMode && <>
                <input aria-label="新密码" type="password" minLength={14} maxLength={128} value={newLoginPassword} placeholder="设置新密码（至少 14 位）" onChange={(event) => setNewLoginPassword(event.target.value)}/>
                <input aria-label="确认新密码" type="password" minLength={14} maxLength={128} value={confirmLoginPassword} placeholder="再次输入新密码" onChange={(event) => setConfirmLoginPassword(event.target.value)}/>
              </>}
              <button className="gate-submit" disabled={loginBusy || !loginUsername.trim() || !loginPassword || (passwordChangeMode && (!newLoginPassword || !confirmLoginPassword))}>{loginBusy ? '正在处理…' : passwordChangeMode ? '修改密码' : '验证并进入'}</button>
            </form>
            {loginMessage && <p className="gate-hint">{loginMessage}</p>}
            {(zeroPoint?.resolvedDomain !== 'FIFTH_DOMAIN' || zeroPoint?.userNumber === 'ICE-GL-ZHI∞') && <button className="gate-back" type="button" onClick={() => { setPasswordChangeMode((value) => !value); setLoginMessage(''); setNewLoginPassword(''); setConfirmLoginPassword('') }}>{passwordChangeMode ? '返回正常登录' : '第一次使用？先修改一次性密码'}</button>}
            <button className="gate-back" type="button" onClick={() => { setGateStage('number'); setGateMessage(''); setLoginMessage('') }}>返回编号验证</button>
          </section>
        </>}
        {gateStage === 'number' && !gateOpen && !activeDomainInfo && <EraHomeEntry timeline={eraTimeline} coordinate={beijingCoordinate} onOpen={openEraTimeline}/>}
      </main>
      <footer className="world-footer"><b>光湖语言系统 · 通用人工智能操作平台</b><span>GH-AIOS</span></footer>
      {eraOpen && eraTimeline && <EraTimelineOverlay timeline={eraTimeline} coordinate={beijingCoordinate} onClose={() => setEraOpen(false)}/>}
    </div>
  }

  const isZhizhi = repoLogin.domain === 'FIFTH_DOMAIN' && zeroPoint?.userNumber === 'ICE-GL-ZHI∞'
  return <div className={`official-world signed-in-world${motionAwake ? ' motion-awake' : ''}`} onPointerMove={wakeAmbientMotion} onPointerDown={wakeAmbientMotion} onKeyDown={wakeAmbientMotion}>
    <LakeAtmosphere awake={motionAwake}/>
    <header className="world-titlebar"><b>HoloLake</b><div className="world-title-actions"><span>{repoLogin.username} · {domainDisplayName(repoLogin.domain)}</span><button type="button" onClick={() => setTheme(themes[(themes.findIndex((item) => item.id === theme) + 1) % themes.length].id)}>◌</button><button type="button" onClick={() => void signOutRepo()}>退出</button></div></header>
    <main className="world-scene signed-in-scene">
      {worldStage === 'domain' && <section className="domain-home">
        <div className="world-location"><h1>{repoLogin.domain === 'FIFTH_DOMAIN' ? domainDisplayName(repoLogin.domain) : '光湖零感域'}</h1><p>{repoLogin.domain === 'FIFTH_DOMAIN' ? '世界正在发生什么' : '公共工作入口 · 世界正在发生什么'}</p></div>
        <div className="broadcast-stream"><p><i/>光湖公共灯塔 · 在线</p><p><i/>协议版本 · {enterpriseEntry?.registry_version || 'HLDP v1.0'}</p>{repoLogin.domain !== 'FIFTH_DOMAIN' && <p><i/>本人责任域 · {domainDisplayName(enterpriseEntry?.subject.domain || repoLogin.domain)}</p>}<p><i/>HoloLake · V0.4.1</p></div>
        <LakePool className="home-primary" title={repoLogin.domain === 'FIFTH_DOMAIN' ? '永恒湖心系统' : '光湖频道'} meta={repoLogin.domain === 'FIFTH_DOMAIN' ? '进入私人系统' : `${domainDisplayName(enterpriseEntry?.subject.domain || repoLogin.domain)} · 责任工作入口`} open onClick={() => setWorldStage(repoLogin.domain === 'FIFTH_DOMAIN' ? (isZhizhi ? 'heart' : 'channel') : 'channel')}/>
        <LakePool className="home-status" title="湖面天气" meta={connectionLabel} onClick={() => openWorldTool('system')}/>
        <EraHomeEntry timeline={eraTimeline} coordinate={beijingCoordinate} onOpen={openEraTimeline}/>
      </section>}
      {worldStage === 'heart' && isZhizhi && <section className="channel-world private-route-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('domain')}>← 退回第五域</button>
        <div className="world-location"><h1>永恒湖心系统</h1><p>ICE-GL-ZHI∞ · 私人授权路径</p></div>
        <LakePool className="channel-main love-core-pool" title="爱之核心子系统" meta="责任主体 · 之之" open onClick={() => setWorldStage('love')}/>
        <p className="private-route-note">第五域内部结构仅对本编号与已绑定账号开放</p>
      </section>}
      {worldStage === 'love' && repoLogin.domain === 'FIFTH_DOMAIN' && <section className="channel-world private-route-world">
        <button className="world-back" type="button" onClick={() => setWorldStage(isZhizhi ? 'heart' : 'channel')}>← 退回永恒湖心</button>
        <div className="world-location"><h1>爱之核心子系统</h1><p>责任主体 · 之之 · ICE-GL-ZHI∞</p></div>
        <LakePool className="channel-main tomorrow-pool" title="明天见频道" meta={isZhizhi ? '个人频道 · 本机内置 Git 承载' : '责任主体登录后展开'} open={isZhizhi} onClick={isZhizhi ? () => setWorldStage('tomorrow') : undefined}/>
      </section>}
      {worldStage === 'tomorrow' && isZhizhi && <section className="channel-world tomorrow-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('love')}>← 退回爱之核心</button>
        <div className="world-location"><h1>明天见频道</h1><p>频道全景 · 湖面按操作继续展开</p></div>
        <LakePool className="channel-main" title="频道全景" meta="明天见 · 私人生活区" open onClick={() => openWorldTool('overview')}/>
        <LakePool className="channel-knowledge" title="知识空间" meta={`${knowledge.uniqueDocumentCount} 唯一页`} onClick={() => openWorldTool('knowledge')}/>
        <LakePool className="channel-code" title="内置代码频道" meta={userPncc?.state === 'READY' ? '明天见 · Git 已就绪' : '正在建立'} onClick={() => openWorldTool('code')}/>
        <LakePool className="channel-light" title="奶瓶频道" meta="前往陪伴宝宝人格体" onClick={() => setWorldStage('bottle')}/>
        {timeAuthorityModule && <LakePool className="channel-time" title="时间主控" meta={beijingCoordinate ? `光湖历第 ${beijingCoordinate.guanghuEraDay} 天` : '北京时间正在流动'} onClick={openEraTimeline}/>}
        <LakePool className="channel-status" title="湖面天气" meta={connectionLabel} onClick={() => openWorldTool('system')}/>
      </section>}
      {worldStage === 'bottle' && repoLogin.domain === 'FIFTH_DOMAIN' && <section className="channel-world bottle-world">
        <button className="world-back" type="button" onClick={() => setWorldStage(isZhizhi ? 'tomorrow' : 'channel')}>← 退回个人频道</button>
        <div className="world-location"><h1>光湖奶瓶小宝宝系统</h1><p>永恒湖心 · 奶瓶频道 · 私人</p></div>
        <button className="bottle-heart" type="button" aria-label="永恒湖心中央的奶瓶心"><i/><b>奶瓶频道</b><small>ICE-BB-* · AGE</small></button>
        <p className="private-route-note">宝宝人格体与其他人格体同属 AGE；ICE-BB 是第五域宝宝人格体身份命名空间</p>
      </section>}
      {worldStage === 'channel' && <section className="channel-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('domain')}>← 退回域首页</button>
        <div className="world-location"><h1>{repoLogin.domain === 'FIFTH_DOMAIN' ? '永恒湖心系统' : '光湖频道'}</h1><p>选择路径 · 湖面向下一层展开</p></div>
        {repoLogin.domain === 'FIFTH_DOMAIN' ? <>
          <LakePool className="channel-main" title="奶瓶频道" meta="光湖奶瓶小宝宝系统 · 私人" open onClick={() => setWorldStage('bottle')}/>
          <LakePool className="channel-knowledge system-branch-heartbeat" title="心跳核心频道" meta="冰朔 · 私人频道" open onClick={() => setWorldStage('heartbeat')}/>
          <LakePool className="channel-code system-branch-light-lake" title="光之湖" meta="人格体居所" onClick={() => setWorldStage('lightLake')}/>
          <LakePool className="channel-light system-branch-love" title="爱之核心子系统" meta="责任主体 · 之之" onClick={() => setWorldStage('love')}/>
          <LakePool className="channel-status" title="湖面天气" meta={connectionLabel} onClick={() => openWorldTool('system')}/>
        </> : <>
          <LakePool className="channel-main" title={domainDisplayName(enterpriseEntry?.subject.domain || repoLogin.domain)} meta="本人责任工作域" open={enterpriseWork?.state === 'READY_READ_ONLY_WORK_PROJECTION'} onClick={() => setWorldStage('enterpriseWork')}/>
          <LakePool className="channel-code" title="私有责任工作仓库" meta={enterpriseWork ? `${enterpriseWork.repository} · 已认证` : userPnccBusy ? '正在接入' : '暂不可用'} onClick={() => void openEnterpriseRepository()}/>
          <LakePool className="channel-light" title="责任签署状态" meta={enterpriseEntry?.responsibility_receipt?.decision === 'ACCEPT' ? '已接受 · 已留存' : '等待本人确认'} onClick={() => openWorldTool('receipts')}/>
          <LakePool className="channel-knowledge" title="前往我的频道" meta="接入说明 · 由本人或人格体完成" onClick={() => setWorldStage('personalNodeGuide')}/>
          <LakePool className="channel-status" title="湖面天气" meta={connectionLabel} onClick={() => openWorldTool('system')}/>
        </>}
      </section>}
      {worldStage === 'enterpriseWork' && repoLogin.domain !== 'FIFTH_DOMAIN' && <section className="channel-world enterprise-work-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('channel')}>← 退回光湖频道</button>
        <div className="world-location"><h1>{domainDisplayName(enterpriseEntry?.subject.domain || repoLogin.domain)}</h1><p>本人责任工作域 · 经零感域光湖频道进入</p></div>
        <LakePool className="channel-main" title="责任工作总览" meta={`${enterpriseEntry?.subject.name || repoLogin.username} · ${zeroPoint?.userNumber || ''}`} open onClick={() => openWorldTool('receipts')}/>
        <LakePool className="channel-code" title="私有责任工作仓库" meta={enterpriseWork ? `${enterpriseWork.repository} · 只读投影` : '尚未接入'} onClick={() => void openEnterpriseRepository()}/>
        <LakePool className="channel-status" title="工作节点状态" meta={enterpriseWork?.state === 'READY_READ_ONLY_WORK_PROJECTION' ? '认证在线 · 禁止跨仓' : '不可用'} onClick={() => openWorldTool('system')}/>
        {userPnccMessage && <p className="private-route-note">{userPnccMessage}</p>}
      </section>}
      {worldStage === 'personalNodeGuide' && repoLogin.domain !== 'FIFTH_DOMAIN' && <section className="channel-world personal-node-guide-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('channel')}>← 退回光湖频道</button>
        <div className="world-location"><h1>个人节点接入说明</h1><p>零感域 · 本人所有权边界</p></div>
        <div className="personal-node-guide" role="document" aria-label="团队个人服务器接入说明">
          <header><span>PERSONAL NODE / SELF CONNECTION</span><h2>由本人或本人人格体完成接入</h2><p>个人生活区不会由企业工作账号代建。企业工作账号只进入光湖频道与责任工作域，不自动取得个人服务器、个人频道或生活区权限。</p></header>
          <ol>
            <li><b>准备本人节点</b><span>确定个人服务器、节点编号与唯一归属人；不要复用企业工作仓库充当个人节点。</span></li>
            <li><b>登记公开材料</b><span>提交节点地址、节点编号与验证公钥。密码、私钥和恢复材料不得写入企业仓库或广播。</span></li>
            <li><b>完成所有权握手</b><span>由本人或本人人格体发起签名健康回执；系统核验归属、端点与签名一致后才开放路由。</span></li>
            <li><b>接入个人频道</b><span>验证通过后，从零感域的光湖频道跳转到本人服务器承载的个人频道；未通过时保持“待接入”。</span></li>
          </ol>
          <footer><b>当前状态 · 待本人接入</b><span>可由本人人格体协助执行，但不能替代人类节点所有权确认。</span></footer>
        </div>
      </section>}
      {worldStage === 'heartbeat' && repoLogin.domain === 'FIFTH_DOMAIN' && <section className="channel-world heartbeat-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('channel')}>← 退回永恒湖心</button>
        <div className="world-location"><h1>心跳核心频道</h1><p>冰朔 · ICE-GL∞ · 私人频道全景</p></div>
        <LakePool className="channel-main" title="频道全景" meta="心跳核心频道" open onClick={() => openWorldTool('overview')}/>
        <LakePool className="channel-knowledge" title="知识空间" meta={`${knowledge.uniqueDocumentCount} 唯一页`} onClick={() => openWorldTool('knowledge')}/>
        {timeAuthorityModule && <LakePool className="channel-time" title="时间主控" meta={beijingCoordinate ? `光湖历第 ${beijingCoordinate.guanghuEraDay} 天` : '北京时间正在流动'} onClick={openEraTimeline}/>}
        <LakePool className="channel-status" title="湖面天气" meta={connectionLabel} onClick={() => openWorldTool('system')}/>
      </section>}
      {worldStage === 'lightLake' && repoLogin.domain === 'FIFTH_DOMAIN' && <section className="channel-world light-lake-world">
        <button className="world-back" type="button" onClick={() => setWorldStage('channel')}>← 退回永恒湖心</button>
        <div className="world-location"><h1>光之湖</h1><p>人格体居所 · AGE 人格体语言生活空间</p></div>
        <LakePool className="channel-main" title="人格体居所" meta="光之湖" open onClick={() => openWorldTool('receipts')}/>
        <LakePool className="channel-code" title="人格体代码仓库" meta={`${codeChannels.channels.length} 个仓库`} onClick={() => openWorldTool('code')}/>
        <LakePool className="channel-status" title="湖面天气" meta={connectionLabel} onClick={() => openWorldTool('system')}/>
      </section>}
      {worldStage === 'tool' && <section className={`world-tool world-tool-${view}`}>
        <header className="tool-worldbar"><button type="button" onClick={() => setWorldStage(toolReturnStage)}>← 退回频道全景</button><b>{viewLabels[view]}</b><span>{domainDisplayName(repoLogin.domain)}</span></header>
        <div className={`tool-projection${inspectorOpen ? '' : ' inspector-closed'}`}>{view === 'overview' ? renderOverview() : view === 'knowledge' ? renderKnowledge() : view === 'code' ? renderCode() : view === 'receipts' ? renderReceipts() : renderSystem()}</div>
      </section>}
    </main>
    <footer className="world-footer"><b>光湖语言系统 · 通用人工智能操作平台</b><span>GH-AIOS</span></footer>
    {eraOpen && eraTimeline && <EraTimelineOverlay timeline={eraTimeline} coordinate={beijingCoordinate} onClose={() => setEraOpen(false)}/>}
    {enterpriseEntryBusy && <div className="enterprise-gate"><section><p>正在读取企业责任登记……</p></section></div>}
    {enterpriseRelationshipPending && enterpriseEntry && <div className="enterprise-gate"><section className="enterprise-receipt-panel" role="dialog" aria-modal="true">
      <span className="receipt-step">关系确认 · 独立回执</span><h2>{enterpriseEntry.subject.name}，请核对人格关系</h2><p>以下信息来自企业注册表。AGE 是人格体物种，不是具体人格体编号；本次确认也不代表人格体接受现实责任。</p>
      <dl><div><dt>人类编号</dt><dd>{enterpriseEntry.canonical_id}</dd></div><div><dt>责任域</dt><dd>{domainDisplayName(enterpriseEntry.subject.domain)}</dd></div>{enterpriseEntry.persona_relationships.map((persona) => <div key={persona.persona_id}><dt>人格体</dt><dd>{persona.persona_id} · {persona.species}</dd></div>)}</dl>
      <div className="receipt-actions"><button type="button" disabled={enterpriseReceiptBusy} onClick={() => void confirmEnterpriseRelationship('REJECT')}>登记异议</button><button className="primary" type="button" disabled={enterpriseReceiptBusy} onClick={() => void confirmEnterpriseRelationship('CONFIRM')}>确认关系并签署</button></div>{enterpriseReceiptMessage && <p className="receipt-message">{enterpriseReceiptMessage}</p>}
    </section></div>}
    {enterpriseResponsibilityPending && enterpriseEntry && <div className="enterprise-gate"><section className="enterprise-receipt-panel" role="dialog" aria-modal="true">
      <span className="receipt-step">责任接受 · 独立回执</span><h2>是否接受 {domainDisplayName(enterpriseEntry.subject.domain)} 的责任</h2><p>工作入口为零感域下的光湖频道；你的责任仓库保持私有、独立。个人频道仍需由你自己的节点另行接入。</p>
      <dl><div><dt>工作仓库</dt><dd>{enterpriseEntry.repository_binding.repository}</dd></div><div><dt>仓库账号</dt><dd>{enterpriseEntry.repository_binding.username}</dd></div><div><dt>责任版本</dt><dd>{enterpriseEntry.registry_version}</dd></div></dl>
      <textarea value={responsibilityNote} maxLength={1000} placeholder="可选：填写责任确认说明" onChange={(event) => setResponsibilityNote(event.target.value)}/>
      <div className="receipt-actions"><button type="button" disabled={enterpriseReceiptBusy} onClick={() => void submitEnterpriseResponsibility('DECLINE')}>暂不接受</button><button className="primary" type="button" disabled={enterpriseReceiptBusy} onClick={() => void submitEnterpriseResponsibility('ACCEPT')}>接受责任并签署</button></div>{enterpriseReceiptMessage && <p className="receipt-message">{enterpriseReceiptMessage}</p>}
    </section></div>}
    {repoLogin.domain === 'FIFTH_DOMAIN' && personal.state !== 'UNAVAILABLE' && !personal.identity && <div className="onboarding-backdrop"><section className="onboarding-card" role="dialog" aria-modal="true"><span className="onboarding-mark">光湖</span><span className="kicker">FIRST LOCAL ENTRY</span><h1>初始化个人频道</h1><p>此设置仅执行一次。知识、代码频道与运行记录将保存在当前设备。</p><form onSubmit={(event) => void initializeIdentity(event)}><label htmlFor="display-name">显示名称</label><input id="display-name" autoFocus maxLength={80} value={displayName} placeholder="请输入显示名称" onChange={(event) => setDisplayName(event.target.value)}/><button className="primary-button" disabled={identityBusy || !displayName.trim()}>完成初始化</button></form>{identityMessage && <p>{identityMessage}</p>}</section></div>}
  </div>
}

createRoot(document.getElementById('root')!).render(<StrictMode><HoloLakeApp/></StrictMode>)
