"use client"

import * as React from "react"
import {
  AlertTriangle,
  ArrowDownRight,
  ArrowRight,
  ArrowUpRight,
  BarChart3,
  BadgeCheck,
  Bell,
  CalendarDays,
  CheckCircle2,
  ChevronRight,
  CircleDot,
  ClipboardCheck,
  Database,
  Download,
  FileJson,
  FileSpreadsheet,
  FileText,
  Flame,
  GitCompareArrows,
  Info,
  ListChecks,
  MessageSquareText,
  RefreshCw,
  Search,
  ShieldAlert,
  Sigma,
  Swords,
  Target,
  Workflow,
} from "lucide-react"
import { toast } from "sonner"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Progress } from "@/components/ui/progress"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarRail,
  SidebarTrigger,
} from "@/components/ui/sidebar"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Toaster } from "@/components/ui/sonner"
import {
  actions,
  deliveryCompletion,
  deliveries,
  keywords,
  masterScores,
  metrics,
  navItems,
  platforms,
  reportContext,
  risks,
  trendData,
} from "./data"
import { DashboardModule } from "./dashboard-pages"
import { OperationsCenter, type OpsWorkspace } from "./operations-center"
import { AowangBrand, AowangCompanySignature } from "./brand-lockup"
import { LiveProjectReport } from "./live-project-report"

const navIcons = [
  BarChart3,
  GitCompareArrows,
  MessageSquareText,
  Swords,
  Flame,
  Workflow,
  FileText,
  Sigma,
  ShieldAlert,
  ListChecks,
]

type DetailState = {
  title: string
  subtitle?: string
  kind: "metric" | "platform" | "keyword" | "notice" | "health"
  payload?: Record<string, unknown>
} | null

type SearchResult = {
  type: string
  title: string
  description: string
  page: number
  detail?: DetailState
}

function formatNumber(value: number) {
  return Number.isInteger(value) ? value.toFixed(0) : value.toFixed(1)
}

function changeLabel(current: number, previous: number, direction: string) {
  const raw = current - previous
  const improved = direction === "down" ? raw < 0 : raw > 0
  const unit = direction === "down" ? "位" : "pp"
  return {
    text: `${raw > 0 ? "+" : ""}${formatNumber(raw)}${unit}`,
    improved,
  }
}

function downloadText(filename: string, content: string, type: string) {
  const blob = new Blob([content], { type })
  const url = URL.createObjectURL(blob)
  const link = document.createElement("a")
  link.href = url
  link.download = filename
  link.click()
  window.setTimeout(() => URL.revokeObjectURL(url), 300)
}

function csvCell(value: unknown) {
  return `"${String(value ?? "").replaceAll('"', '""')}"`
}

function StatusBadge({ value }: { value: string }) {
  const tone =
    value.includes("领先") || value.includes("稳定") || value.includes("完成")
      ? "status-positive"
      : value.includes("提升") || value.includes("关注") || value.includes("进行")
        ? "status-warning"
        : "status-neutral"
  return (
    <Badge variant="outline" className={tone}>
      {value}
    </Badge>
  )
}

function SectionHeading({
  eyebrow,
  title,
  description,
  action,
}: {
  eyebrow: string
  title: string
  description?: string
  action?: React.ReactNode
}) {
  return (
    <div className="section-heading">
      <div>
        <p>{eyebrow}</p>
        <h2>{title}</h2>
        {description ? <span>{description}</span> : null}
      </div>
      {action ? <div className="section-heading-action">{action}</div> : null}
    </div>
  )
}

function PageIntro({
  number,
  title,
  description,
  children,
}: {
  number: number
  title: string
  description: string
  children?: React.ReactNode
}) {
  return (
    <div className="page-intro">
      <div className="page-number">{String(number).padStart(2, "0")}</div>
      <div className="page-intro-copy">
        <p>AW GEO · CLIENT DELIVERY</p>
        <h1>{title}</h1>
        <span>{description}</span>
      </div>
      {children ? <div className="page-intro-action">{children}</div> : null}
    </div>
  )
}

function ScoreRing({ value, tone = "blue" }: { value: number; tone?: "blue" | "green" }) {
  return (
    <div
      className={`score-ring ${tone}`}
      style={{ "--score": `${value * 3.6}deg` } as React.CSSProperties}
      aria-label={`${formatNumber(value)}分`}
    >
      <div>
        <strong>{formatNumber(value)}</strong>
        <span>/ 100</span>
      </div>
    </div>
  )
}

function MasterScoreCard({
  score,
  onOpen,
}: {
  score: (typeof masterScores)[number]
  onOpen: () => void
}) {
  const delta = score.value - score.previous
  return (
    <button className="master-score-card" onClick={onOpen}>
      <span className="score-card-code" aria-hidden="true">
        {score.id === "visibility" ? "VIS / 01" : "HLT / 02"}
      </span>
      <ScoreRing value={score.value} tone={score.id === "health" ? "green" : "blue"} />
      <div className="master-score-copy">
        <div className="master-score-label">
          <span>{score.label}</span>
          <ChevronRight />
        </div>
        <p>{score.description}</p>
        <div className="score-deltas">
          <span className="positive-change">
            <ArrowUpRight /> 较上月 +{formatNumber(delta)}分
          </span>
          <span>较Baseline +{formatNumber(score.value - score.baseline)}分</span>
        </div>
      </div>
    </button>
  )
}

function MetricCard({
  metric,
  onOpen,
}: {
  metric: (typeof metrics)[number]
  onOpen: () => void
}) {
  const change = changeLabel(metric.current, metric.previous, metric.direction)
  return (
    <button className="metric-card" onClick={onOpen}>
      <div className="metric-card-top">
        <span>{metric.label}</span>
        <Info />
      </div>
      <div className="metric-value">
        {formatNumber(metric.current)}
        <small>{metric.unit}</small>
      </div>
      <div className="metric-card-bottom">
        <span className={change.improved ? "positive-change" : "negative-change"}>
          {change.improved ? <ArrowUpRight /> : <ArrowDownRight />}
          较上月 {change.text}
        </span>
        <span className="metric-baseline">基线 {formatNumber(metric.baseline)}{metric.unit}</span>
      </div>
      <p>{metric.question}</p>
    </button>
  )
}

function TrendChart() {
  const width = 780
  const height = 250
  const left = 44
  const right = 28
  const top = 20
  const bottom = 34
  const plotWidth = width - left - right
  const plotHeight = height - top - bottom
  const max = 60
  const points = trendData.map((item, index) => {
    const x = left + (index / (trendData.length - 1)) * plotWidth
    const y = top + (1 - item.visibility / max) * plotHeight
    return { ...item, x, y }
  })
  const line = points.map((point, index) => `${index ? "L" : "M"}${point.x},${point.y}`).join(" ")
  const area = `${line} L${points.at(-1)?.x},${top + plotHeight} L${points[0].x},${top + plotHeight} Z`

  return (
    <div className="trend-chart-wrap">
      <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="近6个月AI综合可见度趋势">
        <defs>
          <linearGradient id="chartArea" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#2563eb" stopOpacity="0.24" />
            <stop offset="100%" stopColor="#2563eb" stopOpacity="0" />
          </linearGradient>
        </defs>
        {[0, 20, 40, 60].map((tick) => {
          const y = top + (1 - tick / max) * plotHeight
          return (
            <g key={tick}>
              <line x1={left} x2={width - right} y1={y} y2={y} stroke="#e5eaf2" strokeDasharray="4 6" />
              <text x={left - 12} y={y + 4} textAnchor="end" className="chart-axis-label">
                {tick}
              </text>
            </g>
          )
        })}
        <path d={area} fill="url(#chartArea)" />
        <path d={line} fill="none" stroke="#2563eb" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
        {points.map((point) => (
          <g key={point.month}>
            <circle cx={point.x} cy={point.y} r="5" fill="#fff" stroke="#2563eb" strokeWidth="3" />
            <text x={point.x} y={height - 7} textAnchor="middle" className="chart-axis-label">
              {point.month}
            </text>
            {point.month === "8月" ? (
              <g>
                <rect x={point.x - 25} y={point.y - 35} width="50" height="24" rx="8" fill="#122b53" />
                <text x={point.x} y={point.y - 19} textAnchor="middle" className="chart-value-label">
                  {masterScores[0].value.toFixed(1)}
                </text>
              </g>
            ) : null}
          </g>
        ))}
      </svg>
    </div>
  )
}

function OverviewPage({
  goTo,
  setDetail,
}: {
  goTo: (page: number) => void
  setDetail: (detail: DetailState) => void
}) {
  return (
    <div className="page-stack">
      <PageIntro
        number={1}
        title="报告概览"
        description="先看两个总指标，再看底层指标、平台差异与本期重点。所有数字均可下钻到原始证据。"
      >
        <Badge variant="outline" className="version-badge">验收口径 V1.0</Badge>
      </PageIntro>

      <section className="project-hero">
        <div className="project-identity">
          <div className="client-mark">點</div>
          <div>
            <div className="hero-label">CURRENT PROJECT</div>
            <h2>{reportContext.project}</h2>
            <p>核心词「粤式茶楼」 · 1个核心词 + 5个核心衍生词 · 8个AI平台</p>
            <div className="project-signal-row">
              <span><CheckCircle2 />检测协议已锁定</span>
              <span><Database />688条有效记录</span>
              <span><ClipboardCheck />证据覆盖100%</span>
            </div>
          </div>
        </div>
        <div className="project-facts">
          <div><span>项目周期</span><strong>2026.05—2026.10</strong></div>
          <div><span>当前阶段</span><strong className="with-dot">月度复测</strong></div>
          <div><span>数据质量</span><strong>{reportContext.quality}%</strong></div>
        </div>
      </section>

      <section className="score-grid">
        {masterScores.map((score) => (
          <MasterScoreCard
            key={score.id}
            score={score}
            onOpen={() => setDetail({ title: score.label, subtitle: "总指标构成与计算过程", kind: "metric", payload: { id: score.id } })}
          />
        ))}
        <div className="acceptance-card">
          <div className="acceptance-card-head">
            <div><span>三层验收状态</span><strong>交付、效果、证据同步可验</strong></div>
            <ClipboardCheck />
          </div>
          <div className="acceptance-steps">
            <button onClick={() => goTo(6)}><span className="step-index">01</span><div><strong>交付完成度</strong><small>{deliveryCompletion}% · 按合格交付计</small></div><CheckCircle2 /></button>
            <button onClick={() => goTo(2)}><span className="step-index">02</span><div><strong>效果指标</strong><small>两项总指标均较基线改善</small></div><ArrowUpRight /></button>
            <button onClick={() => setDetail({ title: "原始证据覆盖", subtitle: "汇总数字的下钻完整性", kind: "health" })}><span className="step-index">03</span><div><strong>原始数据证据</strong><small>覆盖率 100% · 可复核</small></div><Database /></button>
          </div>
        </div>
      </section>

      <section className="content-card">
        <SectionHeading
          eyebrow="BOTTOM-LINE METRICS"
          title="底层指标表现"
          description="同一指标在全站只使用一个数据字段与一套口径"
          action={<Button variant="outline" size="sm" onClick={() => goTo(8)}>查看公式口径 <ArrowRight /></Button>}
        />
        <div className="metric-grid">
          {metrics.map((metric) => (
            <MetricCard key={metric.id} metric={metric} onOpen={() => setDetail({ title: metric.label, subtitle: metric.question, kind: "metric", payload: { id: metric.id } })} />
          ))}
        </div>
      </section>

      <section className="dashboard-grid dashboard-grid-main">
        <div className="content-card">
          <SectionHeading eyebrow="TREND" title="近6个月可见度趋势" description="AI综合可见度（0—100分）· 同口径月度快照" action={<Badge variant="outline" className="status-positive"><ArrowUpRight /> 较基线 +39.3分</Badge>} />
          <TrendChart />
          <div className="chart-footnote"><Info />AI综合可见度从2026年5月基线 11.75 分提升至 51.05 分；该指标不混入品牌健康指标。</div>
        </div>
        <div className="content-card priority-card">
          <SectionHeading eyebrow="THIS MONTH" title="本期核心结论" description="监测结果直接转化为行动" />
          <div className="insight-list">
            <button onClick={() => goTo(4)}><span className="insight-icon blue"><Swords /></span><div><strong>竞争位置升至第 2</strong><p>SOV 31%，与头部品牌相差 3pp</p></div><ChevronRight /></button>
            <button onClick={() => goTo(5)}><span className="insight-icon orange"><Target /></span><div><strong>两项高优先机会</strong><p>商务宴请与家庭聚餐需求升温但覆盖不足</p></div><ChevronRight /></button>
            <button onClick={() => goTo(9)}><span className="insight-icon red"><AlertTriangle /></span><div><strong>3项重点问题待跟踪</strong><p>平台短板、场景缺口与过时信息复测</p></div><ChevronRight /></button>
            <button onClick={() => goTo(7)}><span className="insight-icon green"><FileText /></span><div><strong>50篇内容完成交付</strong><p>44篇已索引，17篇检测到AI引用</p></div><ChevronRight /></button>
          </div>
        </div>
      </section>

      <section className="content-card">
        <SectionHeading eyebrow="PLATFORM PERFORMANCE" title="8大AI平台表现" description="点击平台查看提及、推荐、Top3、排名与原始回答" action={<Button variant="outline" size="sm" onClick={() => goTo(3)}>查看全部回答 <ArrowRight /></Button>} />
        <div className="table-shell">
          <Table>
            <TableHeader><TableRow><TableHead>AI平台</TableHead><TableHead>品牌提及率</TableHead><TableHead>推荐率</TableHead><TableHead>Top3率</TableHead><TableHead>平均位次</TableHead><TableHead>信息准确率</TableHead><TableHead>状态</TableHead></TableRow></TableHeader>
            <TableBody>
              {platforms.map((platform) => (
                <TableRow key={platform.name} className="clickable-row" onClick={() => setDetail({ title: platform.name, subtitle: "平台表现详情", kind: "platform", payload: platform })}>
                  <TableCell><strong>{platform.name}</strong></TableCell>
                  <TableCell><div className="table-progress"><span>{platform.mention}%</span><Progress value={platform.mention} aria-hidden="true" /></div></TableCell>
                  <TableCell>{platform.recommend}%</TableCell><TableCell>{platform.top3}%</TableCell><TableCell>{platform.rank}位</TableCell><TableCell>{platform.accuracy}%</TableCell><TableCell><StatusBadge value={platform.state} /></TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </section>

      <section className="dashboard-grid dashboard-grid-equal">
        <div className="content-card">
          <SectionHeading eyebrow="KEYWORD RANKING" title="核心词 1+5 表现" description="平均推荐位次，数值越低越好" />
          <div className="keyword-list">
            {keywords.map((keyword) => (
              <button key={keyword.name} onClick={() => setDetail({ title: keyword.name, subtitle: "核心词排名证据", kind: "keyword", payload: keyword })}>
                <div><strong>{keyword.name}</strong><span>{keyword.type}</span></div>
                <div className="rank-route"><span>{keyword.baseline}</span><ArrowRight /><span>{keyword.previous}</span><ArrowRight /><b>{keyword.current.toFixed(1)}</b></div>
                <StatusBadge value={keyword.state} />
              </button>
            ))}
          </div>
        </div>
        <div className="content-card">
          <SectionHeading eyebrow="EVIDENCE HEALTH" title="数据与证据健康" description="本期快照自动一致性检查" />
          <div className="health-score-line"><div><span>数据质量</span><strong>{reportContext.quality}%</strong></div><Progress value={reportContext.quality} /></div>
          <div className="health-checks">
            {[["有效检测记录", "688 / 688", "已覆盖"], ["原始回答留存", "688 / 688", "完整"], ["跨页口径一致", "12 / 12", "通过"], ["异常检测调用", "7次", "已排除"], ["快照版本", "2026.08-r3", "已锁定"]].map(([label, value, state]) => (
              <div key={label}><CheckCircle2 /><span>{label}</span><strong>{value}</strong><Badge variant="outline">{state}</Badge></div>
            ))}
          </div>
          <Button variant="outline" className="full-width-button" onClick={() => setDetail({ title: "数据状态与一致性检查", subtitle: "本期月度快照", kind: "health" })}>查看检查明细 <ArrowRight /></Button>
        </div>
      </section>
    </div>
  )
}

function DetailSheet({ detail, onOpenChange }: { detail: DetailState; onOpenChange: (open: boolean) => void }) {
  const metric = detail?.kind === "metric" ? metrics.find((item) => item.id === detail.payload?.id) : null
  const score = detail?.kind === "metric" ? masterScores.find((item) => item.id === detail.payload?.id) : null
  const platform = detail?.kind === "platform" ? detail.payload : null
  const keyword = detail?.kind === "keyword" ? detail.payload : null
  return (
    <Sheet open={Boolean(detail)} onOpenChange={onOpenChange}>
      <SheetContent className="detail-sheet sm:max-w-xl">
        <SheetHeader><SheetTitle>{detail?.title}</SheetTitle><SheetDescription>{detail?.subtitle}</SheetDescription></SheetHeader>
        <div className="detail-sheet-body">
          {score ? (
            <>
              <div className="detail-score"><ScoreRing value={score.value} tone={score.id === "health" ? "green" : "blue"} /><div><span>本月得分</span><strong>较上月 +{formatNumber(score.value - score.previous)}分</strong><p>{score.description}</p></div></div>
              {score.id === "visibility" ? (
                <div className="formula-block"><span>V1.0 标准公式</span><strong>提及率 × 25% + 推荐率 × 25% + Top3率 × 15% + 推荐位次得分 × 10% + 引用率 × 10% + AI推荐SOV × 15%</strong><code>68×25% + 52×25% + 38×15% + 82×10% + 25×10% + 31×15% = 51.05</code><small className="formula-audit-note">系统自动复算；V1.0原文示例结果51.85存在0.80分算术偏差。</small></div>
              ) : (
                <div className="formula-block"><span>V1.0 标准公式</span><strong>品牌信息准确率 × 60% + 内容中正率 × 40%</strong><code>92×60% + 94×40% = 92.8</code></div>
              )}
            </>
          ) : null}
          {metric ? (
            <>
              <div className="detail-kpi-row"><div><span>Baseline</span><strong>{metric.baseline}{metric.unit}</strong></div><ArrowRight/><div><span>上月</span><strong>{metric.previous}{metric.unit}</strong></div><ArrowRight/><div className="current"><span>本月</span><strong>{metric.current}{metric.unit}</strong></div></div>
              <div className="definition-card"><span>指标定义</span><p>{metric.definition}</p></div>
              {metric.id === "rank" ? <div className="formula-block"><span>推荐位次得分</span><strong>MAX〔0，（11 - 平均推荐位次）÷ 10 × 100〕</strong><code>平均位次 2.8 → 推荐位次得分 82分；未获得推荐位次时按0分计</code></div> : null}
              <div className="evidence-route"><span>证据链</span><div>Prompt编号 <ArrowRight/> AI平台 <ArrowRight/> 检测时间 <ArrowRight/> 完整回答 <ArrowRight/> 判定记录</div></div>
            </>
          ) : null}
          {platform ? (
            <>
              <div className="detail-metric-grid">{(["mention", "recommend", "top3", "accuracy"] as const).map((key) => <div key={key}><span>{{ mention: "提及率", recommend: "推荐率", top3: "Top3率", accuracy: "准确率" }[key]}</span><strong>{String(platform[key])}%</strong></div>)}</div>
              <div className="definition-card"><span>本期判断</span><p>平台平均推荐位次 {String(platform.rank)} 位，当前状态为「{String(platform.state)}」。点击03模块可继续下钻至该平台的Prompt与完整回答。</p></div>
            </>
          ) : null}
          {keyword ? (
            <><div className="detail-kpi-row"><div><span>Baseline</span><strong>{String(keyword.baseline)}位</strong></div><ArrowRight/><div><span>上月</span><strong>{String(keyword.previous)}位</strong></div><ArrowRight/><div className="current"><span>本月</span><strong>{String(keyword.current)}位</strong></div></div><div className="definition-card"><span>复测说明</span><p>使用固定Prompt池、固定平台与固定竞品集合复测。核心Prompt建议重复检测不少于3次，以降低生成式AI随机性。</p></div></>
          ) : null}
          {detail?.kind === "health" ? (
            <><div className="detail-metric-grid"><div><span>原始证据覆盖率</span><strong>100%</strong></div><div><span>数据质量</span><strong>98.7%</strong></div><div><span>异常调用</span><strong>7次</strong></div><div><span>快照版本</span><strong>r3</strong></div></div><div className="formula-block"><span>管理指标公式</span><strong>具有完整原始证据链的有效检测记录数 ÷ 纳入效果统计的有效检测记录数 × 100%</strong><code>688 ÷ 688 × 100% = 100%</code></div><div className="definition-card"><span>强制一致性规则</span><p>所有01—10模块读取同一份月度快照；失败、超时和无效输出单独记录，不进入有效回答分母。</p></div></>
          ) : null}
        </div>
      </SheetContent>
    </Sheet>
  )
}

export function GeoDeliveryApp({ surface = "console", projectSlug = "" }: { surface?: "console" | "report"; projectSlug?: string }) {
  const [activePage, setActivePage] = React.useState(1)
  const [searchOpen, setSearchOpen] = React.useState(false)
  const [search, setSearch] = React.useState("")
  const [notificationsOpen, setNotificationsOpen] = React.useState(false)
  const [detail, setDetail] = React.useState<DetailState>(null)
  const [opsWorkspace, setOpsWorkspace] = React.useState<OpsWorkspace | null>(null)
  const [opsLoading, setOpsLoading] = React.useState(true)
  const [selectedProjectId, setSelectedProjectId] = React.useState("")
  const activeItem = navItems[activePage - 1]
  const selectedProject = opsWorkspace?.projects.find((item) => item.id === selectedProjectId) ?? opsWorkspace?.projects[0]
  const isReferenceReport = selectedProject?.projectType === "reference"
  const selectedSnapshot = opsWorkspace?.snapshots.find((item) => item.projectId === selectedProject?.id && item.status === "published")
    ?? opsWorkspace?.snapshots.find((item) => item.projectId === selectedProject?.id)

  const refreshOps = React.useCallback(async () => {
    setOpsLoading(true)
    try {
      const response = await fetch("/api/ops", { headers: { accept: "application/json" } })
      const result = await response.json() as OpsWorkspace & { error?: string }
      if (!response.ok || !result.projects) throw new Error(result.error ?? "运营数据读取失败")
      setOpsWorkspace(result)
      setSelectedProjectId((current) => {
        const routed = projectSlug ? result.projects.find((item) => item.slug === projectSlug)?.id : ""
        if (routed) return routed
        return result.projects.some((item) => item.id === current) ? current : result.projects.find((item) => item.status === "active")?.id ?? ""
      })
    } catch {
      setOpsWorkspace(null)
    } finally {
      setOpsLoading(false)
    }
  }, [projectSlug])

  React.useEffect(() => {
    const restorePage = window.setTimeout(() => {
      const saved = Number(window.localStorage.getItem("aw-geo-active-page"))
      if (saved >= 1 && saved <= 10) setActivePage(saved)
    }, 0)
    const onKeyDown = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") { event.preventDefault(); setSearchOpen(true) }
      if (event.key === "Escape") setDetail(null)
    }
    window.addEventListener("keydown", onKeyDown)
    return () => {
      window.clearTimeout(restorePage)
      window.removeEventListener("keydown", onKeyDown)
    }
  }, [])

  React.useEffect(() => {
    const load = window.setTimeout(() => { void refreshOps() }, 0)
    return () => window.clearTimeout(load)
  }, [refreshOps])

  const goTo = React.useCallback((page: number) => {
    setActivePage(page)
    window.localStorage.setItem("aw-geo-active-page", String(page))
    window.scrollTo({ top: 0, behavior: "smooth" })
  }, [])

  const searchResults = React.useMemo<SearchResult[]>(() => {
    const base: SearchResult[] = [
      ...navItems.map((item) => ({ type: "页面", title: `${String(item.id).padStart(2, "0")} ${item.title}`, description: item.description, page: item.id })),
      ...metrics.map((metric) => ({ type: "指标", title: metric.label, description: metric.question, page: metric.id === "sov" ? 4 : 8, detail: { title: metric.label, subtitle: metric.question, kind: "metric" as const, payload: { id: metric.id } } })),
      ...keywords.map((keyword) => ({ type: "核心词", title: keyword.name, description: `${keyword.type} · 本月平均推荐位次 ${keyword.current}`, page: 2, detail: { title: keyword.name, subtitle: "核心词排名证据", kind: "keyword" as const, payload: keyword } })),
      ...deliveries.map((item) => ({ type: "交付内容", title: item.title, description: `${item.media} · ${item.index} · ${item.citation}`, page: 7 })),
      ...risks.map((item) => ({ type: "问题风险", title: `${item.id} ${item.name}`, description: `${item.status} · ${item.owner}`, page: 9 })),
      ...actions.map((item) => ({ type: "行动任务", title: `${item.priority} ${item.task}`, description: `${item.status} · ${item.progress}%`, page: 10 })),
    ]
    const query = search.trim().toLowerCase()
    if (!query) return base.slice(0, 8)
    return base.filter((item) => `${item.type}${item.title}${item.description}`.toLowerCase().includes(query)).slice(0, 16)
  }, [search])

  const selectSearchResult = (result: SearchResult) => {
    goTo(result.page); setSearchOpen(false); setSearch("")
    if (result.detail) window.setTimeout(() => setDetail(result.detail ?? null), 180)
  }

  const exportSnapshot = () => {
    downloadText("点都德_2026年8月_GEO数据快照.json", JSON.stringify({ standard: { metricStandardVersion: "GEO交付验收标准V1.0", calculationEngineVersion: "V8.1", moduleCount: 10, moduleConsistency: 100, validatedAt: "2026-09-01" }, reportContext, masterScores, metrics, platforms, keywords, deliveries, risks, actions }, null, 2), "application/json;charset=utf-8")
    toast.success("数据快照已导出")
  }

  const exportDelivery = () => {
    const columns = ["id", "title", "scene", "media", "level", "date", "index", "citation", "times", "ai", "question"] as const
    const csv = `\ufeff${columns.join(",")}\n${deliveries.map((row) => columns.map((column) => csvCell(row[column])).join(",")).join("\n")}`
    downloadText("点都德_2026年8月_交付内容清单.csv", csv, "text/csv;charset=utf-8")
    toast.success("交付清单已导出")
  }

  const openReport = React.useCallback((slug: string) => {
    if (!slug) return
    window.location.assign(`/report/${encodeURIComponent(slug)}`)
  }, [])

  if (surface === "console") {
    const fallback = opsWorkspace?.projects.find((item) => item.projectType === "reference") ?? opsWorkspace?.projects.find((item) => item.status === "active")
    return <div className="console-surface"><OperationsCenter workspace={opsWorkspace} loading={opsLoading} onWorkspaceChange={setOpsWorkspace} onRefresh={refreshOps} onReturn={() => fallback && openReport(fallback.slug)} onOpenReport={openReport}/><div className="console-company-footer"><AowangCompanySignature/><span>V8.1 · GEO DELIVERY & ACCEPTANCE OPERATING SYSTEM</span></div><Toaster richColors position="top-right" /></div>
  }

  return (
    <SidebarProvider defaultOpen style={{ "--sidebar-width": "272px", "--sidebar-width-icon": "72px" } as React.CSSProperties}>
      <Sidebar collapsible="icon" className="app-sidebar border-none">
        <SidebarHeader className="sidebar-brand-wrap"><AowangBrand/></SidebarHeader>
        <SidebarContent>
          <SidebarGroup><SidebarGroupLabel>GEO月度交付报告 · 01—10</SidebarGroupLabel><SidebarGroupContent><SidebarMenu className="sidebar-nav-list">
            {navItems.map((item, index) => { const Icon = navIcons[index]; return <SidebarMenuItem key={item.id}><SidebarMenuButton isActive={activePage === item.id} tooltip={`${String(item.id).padStart(2, "0")} ${item.title}`} onClick={() => goTo(item.id)} className="sidebar-nav-button"><span className="sidebar-number">{String(item.id).padStart(2, "0")}</span><Icon /><span>{item.title}</span></SidebarMenuButton></SidebarMenuItem> })}
          </SidebarMenu></SidebarGroupContent></SidebarGroup>
        </SidebarContent>
        <SidebarFooter className="sidebar-project-wrap"><div className="sidebar-project"><div className="sidebar-project-status"><CircleDot /><span>{isReferenceReport ? "标准验收样板 · V8.1" : selectedSnapshot?.status === "published" ? "正式发布报告" : "等待正式发布"}</span></div><strong>{selectedProject?.brandName ?? "项目加载中"}</strong><span>{selectedProject?.currentMonth ? `报告月份 ${selectedProject.currentMonth}` : "尚未生成月度快照"}</span></div></SidebarFooter>
        <SidebarRail />
      </Sidebar>

      <SidebarInset className="app-main">
        <header className="topbar">
          <div className="topbar-title"><SidebarTrigger className="sidebar-trigger" /><div><p>{String(activeItem.id).padStart(2, "0")} / 10 · CLIENT DELIVERY REPORT</p><h2>{activeItem.title}</h2></div><span className={`topbar-live ${selectedSnapshot?.status !== "published" ? "pending" : ""}`}><i />{isReferenceReport ? "标准验收样板 · V8.1" : selectedSnapshot?.status === "published" ? "已发布" : "待发布"}</span></div>
          <div className="topbar-actions">
            <Select value={selectedProject?.id ?? selectedProjectId} onValueChange={(value) => { const project = opsWorkspace?.projects.find((item) => item.id === value); if (project) openReport(project.slug) }}><SelectTrigger className="project-select" aria-label="选择项目"><Database /><SelectValue placeholder="选择项目"/></SelectTrigger><SelectContent>{opsWorkspace?.projects.filter((project) => project.status === "active" && (project.projectType === "reference" || project.publishedCount > 0)).map((project) => <SelectItem key={project.id} value={project.id}>{project.brandName} · {project.projectName}</SelectItem>)}</SelectContent></Select>
            {isReferenceReport ? <><Button variant="outline" className="search-trigger" onClick={() => setSearchOpen(true)}><Search /><span>全局搜索</span><kbd>Ctrl K</kbd></Button>
              <Select defaultValue="2026-08" onValueChange={() => toast.info("标准验收样板当前锁定2026年8月对照快照")}><SelectTrigger className="month-select" aria-label="选择汇报月份"><CalendarDays /><SelectValue /></SelectTrigger><SelectContent><SelectItem value="2026-08">2026年8月</SelectItem></SelectContent></Select>
              <Button variant="outline" size="icon" className="notification-button" onClick={() => setNotificationsOpen(true)} aria-label="打开通知"><Bell /><span>3</span></Button>
              <DropdownMenu><DropdownMenuTrigger asChild><Button className="export-button"><Download />导出<ChevronRight /></Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-64"><DropdownMenuLabel>导出标准验收样板</DropdownMenuLabel><DropdownMenuSeparator /><DropdownMenuItem onClick={exportSnapshot}><FileJson />数据快照 JSON</DropdownMenuItem><DropdownMenuItem onClick={exportDelivery}><FileSpreadsheet />交付清单 CSV</DropdownMenuItem><DropdownMenuItem onClick={() => { window.print(); toast.info("已打开打印 / PDF面板") }}><FileText />打印 / 另存为PDF</DropdownMenuItem></DropdownMenuContent></DropdownMenu></> : <Button className="export-button" onClick={() => { window.print(); toast.info("已打开打印 / PDF面板") }}><Download/>导出报告</Button>}
          </div>
        </header>

        <div className="context-strip">
          <div><span>客户主体</span><strong>{selectedProject?.clientName ?? "—"}</strong></div><div><span>汇报周期</span><strong>{isReferenceReport ? reportContext.reportMonth : selectedProject?.currentMonth ?? "待发布"}</strong></div><div><span>对比口径</span><strong>{isReferenceReport ? reportContext.baseline : selectedProject?.baselineMonth ?? "待配置"} / 上月 / 本月</strong></div><div><span>数据快照</span><strong>{isReferenceReport ? reportContext.snapshot : selectedSnapshot ? `${selectedSnapshot.reportMonth}-r${selectedSnapshot.version}` : "尚未生成"}</strong></div>
          <button onClick={() => isReferenceReport ? setDetail({ title: "数据状态与一致性检查", subtitle: "标准验收快照", kind: "health" }) : undefined}><span className="live-dot" />数据质量 {isReferenceReport ? `${reportContext.quality}%` : selectedSnapshot ? `${selectedSnapshot.qualityScore}%` : "待校验"}<ChevronRight /></button>
          <Badge variant="outline" className="readonly-badge"><BadgeCheck/>{isReferenceReport ? "标准验收样板 · 口径已校验" : selectedSnapshot?.status === "published" ? "正式发布" : "待发布"}</Badge>
        </div>

        <main className="dashboard-content">{selectedProject ? isReferenceReport ? activePage === 1 ? <OverviewPage goTo={goTo} setDetail={setDetail} /> : <DashboardModule key={activePage} page={activePage} goTo={goTo} /> : <LiveProjectReport projectSlug={selectedProject.slug} activePage={activePage}/> : <div className="live-report-loading"><Database/><strong>项目报告不存在或尚未发布</strong><span>请确认项目地址和查看权限。</span></div>}</main>
        <footer className="site-footer"><AowangCompanySignature/><span>报告口径 V1.0 · 引擎 V8.1 · {isReferenceReport ? "标准验收快照" : "正式发布快照"}</span></footer>
      </SidebarInset>

      <Dialog open={searchOpen} onOpenChange={setSearchOpen}>
        <DialogContent className="search-dialog sm:max-w-2xl"><DialogHeader><DialogTitle>全局搜索</DialogTitle><DialogDescription>搜索页面、指标、核心词、交付内容、问题风险与行动任务。</DialogDescription></DialogHeader><div className="search-input-wrap"><Search /><Input autoFocus value={search} onChange={(event) => setSearch(event.target.value)} placeholder="输入关键词，例如：推荐率、商务宴请、DeepSeek" /></div><div className="search-result-list">{searchResults.length ? searchResults.map((result, index) => <button key={`${result.type}-${result.title}-${index}`} onClick={() => selectSearchResult(result)}><Badge variant="outline">{result.type}</Badge><div><strong>{result.title}</strong><span>{result.description}</span></div><ChevronRight /></button>) : <div className="search-empty"><Search /><strong>未找到匹配结果</strong><span>尝试搜索“推荐率”或“商务宴请”</span></div>}</div></DialogContent>
      </Dialog>

      <Sheet open={notificationsOpen} onOpenChange={setNotificationsOpen}>
        <SheetContent className="notification-sheet sm:max-w-md"><SheetHeader><SheetTitle>项目通知</SheetTitle><SheetDescription>需要关注的复测、索引与行动任务。</SheetDescription></SheetHeader><div className="notification-list"><button onClick={() => { setNotificationsOpen(false); goTo(7) }}><span className="notice-icon orange"><RefreshCw /></span><div><strong>6篇内容仍待索引</strong><p>持续检测中 · 进入交付内容台账</p><small>15分钟前</small></div><ChevronRight /></button><button onClick={() => { setNotificationsOpen(false); goTo(9) }}><span className="notice-icon blue"><Database /></span><div><strong>R3 品牌过时信息将在7日后复测</strong><p>已完成事实源校准</p><small>2小时前</small></div><ChevronRight /></button><button onClick={() => { setNotificationsOpen(false); goTo(10) }}><span className="notice-icon red"><Target /></span><div><strong>2个P0任务正在执行</strong><p>商务宴请场景 / DeepSeek专项</p><small>今天 09:30</small></div><ChevronRight /></button></div></SheetContent>
      </Sheet>

      <DetailSheet detail={detail} onOpenChange={(open) => !open && setDetail(null)} />
      <Toaster richColors position="top-right" />
    </SidebarProvider>
  )
}

export default function Home() {
  return <GeoDeliveryApp surface="console" />
}
