import Link from "next/link";
import { requireCloudViewer } from "../../cloud-auth";
import { DashboardShell, PageHeading, StatusPill } from "../../components/Shells";
import {
  getDashboardSnapshot,
  getOrCreateAccount,
  listAccountDeletionRequests,
} from "@/db/repository";
import { AccountDeletionAction } from "./AccountLifecycleActions";

export const dynamic = "force-dynamic";

export default async function SecurityPage() {
  const viewer = await requireCloudViewer("/dashboard/security");
  const account = await getOrCreateAccount(viewer);
  const [snapshot, deletionRequests] = await Promise.all([
    getDashboardSnapshot(account),
    listAccountDeletionRequests(account.id),
  ]);
  return (
    <DashboardShell viewer={viewer} active="/dashboard/security" serviceStatus={snapshot.serviceStatus}>
      <div className="cloud-page">
        <PageHeading eyebrow="SECURITY / 安全与设备" title="把身份、设备和内容边界分开。" description="用户、手机、主机和管理员使用不同身份；控制平面不把登录成功当作跨租户授权。" />
        <div className="security-grid">
          <section className="panel security-card"><span className="card-index">01</span><StatusPill tone="good">当前身份</StatusPill><h2>{viewer.email}</h2><p>{viewer.isLocalDemo ? "本地开发演示身份；部署后不会存在。" : "由 Sites 的 ChatGPT 登录识别；正式公共身份提供商仍需上线前确认。"}</p></section>
          <section className="panel security-card"><span className="card-index">02</span><StatusPill tone={snapshot.connection.state === "ready" ? "good" : "warn"}>租户状态</StatusPill><h2>{snapshot.tenant?.slug}</h2><p>共享 Relay 状态为 {snapshot.connection.state}，授权 revision 为 {snapshot.connection.authorizationRevision}。账号登录不会自动创建任何 phone → device grant。</p></section>
          <section className="panel security-card"><span className="card-index">03</span><StatusPill tone="danger">证据待补</StatusPill><h2>sealed attachments</h2><p>命令与附件必须在真实中继、重试、日志和备份上完成端到端验证后，才会显示“已密封”。</p></section>
        </div>
        <section className="panel full-panel"><div className="panel-heading"><div><span>账户动作</span><h2>必须保留的安全出口</h2></div></div><div className="safety-actions"><article><strong>撤销主机令牌</strong><p>已可从主机列表撤销；令牌立即失效并释放槽位，不受未来计费状态阻止。</p><Link className="button button-secondary" href="/dashboard/hosts">管理主机</Link></article><article><strong>导出账户数据</strong><p>下载 Cloud 控制平面保存的账户、主机、权益、运行态和反馈。原生会话仍需从本地主机导出。</p><a className="button button-secondary" href="/api/account/export" download>下载 JSON 导出</a></article><article className="account-lifecycle-card"><strong>注销与删除请求</strong><p>先记录可撤回申请；租户卷、备份和法定保留例外仍需人工核对，未核对前不会伪装成已经删除。</p><AccountDeletionAction requests={deletionRequests} /></article></div></section>
        <div className="inline-callout"><div><strong>想先理解为什么不写“零知识”？</strong><p>托管 PWA 本身是可变代码，这也是信任模型的一部分。</p></div><Link className="button button-secondary" href="/trust">查看完整边界</Link></div>
      </div>
    </DashboardShell>
  );
}
