import Link from "next/link";
import { fetchFeed, fetchRepoStats } from "@/lib/github";
import { getDispatch, getEnv } from "@/lib/kv";
import { getFacts } from "@/lib/facts";
import { Ticker } from "@/components/ticker";
import { StatGrid } from "@/components/stat-grid";
import { FeedCard } from "@/components/feed-card";
import { Seal } from "@/components/seal";
import { MermaidDiagram } from "@/components/mermaid-diagram";
import type { CuratedDispatch, FeedItem, RepoStats } from "@/lib/types";
import { GITEE_ENABLED } from "@/lib/i18n/config";

export const revalidate = 1800;

const FALLBACK_STATS: RepoStats = {
  stars: 0,
  forks: 0,
  openIssues: 0,
  openPulls: 0,
  contributors: 91,
  fetchedAt: new Date().toISOString(),
};

const FALLBACK_DISPATCH_EN: CuratedDispatch = {
  generatedAt: new Date().toISOString(),
  headline: "A small, focused terminal agent — quietly shipping",
  summary:
    "DeepSeek TUI is an open-source coding agent that runs in your terminal, talks to the DeepSeek V4 family, and behaves itself around your filesystem. The dispatch below is regenerated by DeepSeek V4-Flash on a six-hour cron — you'll see actual repo movement here once the cron runs.",
  highlights: [
    { title: "Read the install guide", href: "/install", tag: "shipped", blurb: "Per-OS instructions for Cargo, npm, the Homebrew tap, and release binaries." },
    { title: "Browse open issues", href: "https://github.com/Hmbown/deepseek-tui/issues", tag: "opened", blurb: "Triaged on GitHub — start with anything labelled 'good first issue'." },
    { title: "Review the roadmap", href: "/roadmap", tag: "discussion", blurb: "What's confirmed, what's being weighed, what's been ruled out." },
  ],
  movers: [],
};

const FALLBACK_DISPATCH_ZH: CuratedDispatch = {
  generatedAt: new Date().toISOString(),
  headline: "一个专注的终端智能体——安静迭代中",
  summary:
    "DeepSeek TUI 是一款开源终端编程智能体，运行在你的终端中，接入 DeepSeek V4 系列模型，对文件系统操作保持克制。以下「今日要闻」由 DeepSeek V4-Flash 每六小时自动生成——仓库有新动态时会实时更新。",
  highlights: [
    { title: "阅读安装指南", href: "/zh/install", tag: "shipped", blurb: "覆盖 macOS、Linux、Windows，支持 Cargo、npm、Homebrew tap 及发布页二进制。" },
    { title: "浏览开放议题", href: "https://github.com/Hmbown/deepseek-tui/issues", tag: "opened", blurb: "在 GitHub 上查看——从标记为 good first issue 的议题开始。" },
    { title: "查看路线图", href: "/zh/roadmap", tag: "discussion", blurb: "已确认、审议中、以及已排除的功能规划。" },
  ],
  movers: [],
};

export default async function HomePage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  const isZh = locale === "zh";
  const env = await getEnv();
  const facts = await getFacts();

  let stats: RepoStats = FALLBACK_STATS;
  let feed: FeedItem[] = [];
  let dispatch: CuratedDispatch = isZh ? FALLBACK_DISPATCH_ZH : FALLBACK_DISPATCH_EN;

  try {
    [stats, feed] = await Promise.all([
      fetchRepoStats(env.GITHUB_TOKEN),
      fetchFeed(env.GITHUB_TOKEN, 12),
    ]);
  } catch (e) {
    console.error("github fetch failed", e);
  }

  try {
    const cached = await getDispatch();
    if (cached) dispatch = cached;
  } catch {
    /* keep fallback */
  }

  return (
    <>
      <Ticker items={feed} />

      {/* HERO */}
      <section className="relative overflow-hidden">
        <div className="margin-glyph right-[-2rem] top-[2rem] hidden lg:block">深</div>

        <div className="mx-auto max-w-[1400px] px-4 sm:px-6 pt-10 sm:pt-14 pb-12 grid lg:grid-cols-12 gap-10">
          <div className="lg:col-span-8">
            <div className="flex items-center gap-2 sm:gap-3 mb-6 flex-wrap">
              <span className="pill pill-hot">v4 · 1M context</span>
              <span className="pill pill-ghost">MIT licensed</span>
            </div>

            <h1 className="font-display tracking-crisp">
              {isZh
                ? "一个住在终端里的编程智能体。"
                : "A coding agent that lives in your terminal."}
            </h1>

            <p className="mt-6 text-lg text-ink-soft leading-relaxed max-w-2xl">
              <span className="font-cjk text-indigo font-semibold">深度求索</span> ·{" "}
              <strong>DeepSeek TUI</strong>{" "}
              {isZh
                ? "是一款基于 DeepSeek V4 系列的开源命令行智能体。它编辑文件、执行 Shell、调用 MCP 服务器，并尊重你的沙箱边界。"
                : "is an open-source command-line agent built on the DeepSeek V4 family. It edits files, runs shells, calls MCP servers, and respects your sandbox."}
            </p>

            <div className="mt-8 flex flex-wrap items-stretch sm:items-center gap-3">
              <Link
                href={isZh ? "/zh/install" : "/install"}
                className="flex-1 sm:flex-none text-center px-5 py-3 bg-ink text-paper font-mono text-sm uppercase tracking-wider hover:bg-indigo transition-colors"
              >
                {isZh ? "立即安装 →" : "Install →"}
              </Link>
              <Link
                href="https://github.com/Hmbown/deepseek-tui"
                className="flex-1 sm:flex-none text-center px-5 py-3 hairline-t hairline-b hairline-l hairline-r font-mono text-sm uppercase tracking-wider hover:bg-paper-deep transition-colors"
              >
                ★ Star on GitHub
              </Link>
              <Link
                href={isZh ? "/zh/docs" : "/docs"}
                className="px-5 py-3 font-mono text-sm uppercase tracking-wider text-ink-mute hover:text-indigo transition-colors"
              >
                {isZh ? "阅读文档" : "Read the docs"}
              </Link>
              <Link
                href="https://buymeacoffee.com/hmbown"
                className="px-5 py-3 font-mono text-sm uppercase tracking-wider text-ink-mute hover:text-indigo transition-colors"
              >
                {isZh ? "支持项目 ↗" : "Support ↗"}
              </Link>
            </div>

            {/* Trust signals */}
            <div className="mt-6 flex items-center gap-4 text-xs font-mono text-ink-mute flex-wrap">
              {isZh ? (
                <span>独立维护者 Hmbown{GITEE_ENABLED && <> · <a href="https://gitee.com/Hmbown/deepseek-tui" className="text-indigo hover:underline">Gitee 镜像</a></>}</span>
              ) : (
                <span>Maintained by Hmbown</span>
              )}
            </div>
          </div>

          {/* hero side: cargo install card */}
          <div className="lg:col-span-4">
            <div className="hairline-t hairline-b hairline-l hairline-r bg-paper p-5 relative">
              <div className="absolute -top-3 left-4 bg-paper px-2 eyebrow">
                {isZh ? "开始使用 · 一行安装" : "get started · 开始使用"}
              </div>
              <pre className="code-block mt-2">
                {isZh ? (
                  <>
                    <span className="comment"># 安装</span>{"\n"}
                    <span className="prompt">$</span> cargo install deepseek-tui-cli --locked{"\n"}
                    <span className="prompt">$</span> deepseek{"\n"}
                    <br />
                    <span className="comment"># 已安装？更新到最新版</span>{"\n"}
                    <span className="prompt">$</span> deepseek update{"\n"}
                    <br />
                    <span className="comment"># 首次运行会自动创建 <span className="key">~/.deepseek/</span></span>
                  </>
                ) : (
                  <>
                    <span className="comment"># install</span>{"\n"}
                    <span className="prompt">$</span> cargo install deepseek-tui-cli --locked{"\n"}
                    <span className="prompt">$</span> deepseek{"\n"}
                    <br />
                    <span className="comment"># already installed? pull the latest</span>{"\n"}
                    <span className="prompt">$</span> deepseek update{"\n"}
                    <br />
                    <span className="comment"># first run sets up <span className="key">~/.deepseek/</span></span>
                  </>
                )}
              </pre>
              <div className="mt-3 flex items-center justify-between text-[0.7rem] font-mono text-ink-mute">
                <span>{isZh ? "需要 Rust 1.88+ · 没有 Rust? 见其他方式" : "requires Rust 1.88+ · no Rust? see other ways"}</span>
                <Link href={isZh ? "/zh/install" : "/install"} className="text-indigo hover:underline">{isZh ? "其他方式 →" : "other ways →"}</Link>
              </div>
            </div>
          </div>
        </div>
      </section>

      <StatGrid stats={stats} />

      {/* TODAY'S DISPATCH */}
      <section className="mx-auto max-w-[1400px] px-6 py-16">
        <div className="flex items-end justify-between mb-6 hairline-b pb-4">
          <div>
            <div className="eyebrow mb-2">{isZh ? "今日要闻" : "Today's Dispatch · 今日要闻"}</div>
            <h2 className="font-display tabular text-ink-mute font-mono text-base">
              {new Date(dispatch.generatedAt).toISOString().slice(0, 10)}
            </h2>
          </div>
          <div className="text-right">
            <div className="eyebrow">{isZh ? "由 … 编辑" : "Curated by"}</div>
            <div className="font-mono text-sm">DeepSeek V4-Flash · 6h cron</div>
          </div>
        </div>

        <div className="grid lg:grid-cols-12 gap-10">
          {/* editorial */}
          <div className="lg:col-span-7">
            <article className="space-y-5">
              <h3 className="font-display text-3xl leading-tight">
                {isZh && dispatch.headlineZh ? dispatch.headlineZh : dispatch.headline}
              </h3>
              <p className={`${isZh ? "text-ink-soft leading-[1.9] tracking-wide text-[1.02rem]" : "text-ink-soft leading-relaxed text-[1.02rem]"}`}>
                {isZh && dispatch.summaryZh ? dispatch.summaryZh : dispatch.summary}
              </p>

              <div className="hairline-t pt-5">
                <div className="eyebrow mb-3">{isZh ? "要点" : "Highlights · 要点"}</div>
                <ul className="divide-y divide-paper-line/40 hairline-t hairline-b">
                  {(isZh && dispatch.highlightsZh ? dispatch.highlightsZh : dispatch.highlights).map((h, i) => (
                    <li key={i} className="py-3 flex items-start gap-4">
                      <span className="font-mono text-[0.7rem] text-indigo uppercase tracking-widest pt-1 w-20 shrink-0">
                        {h.tag}
                      </span>
                      <div className="flex-1">
                        <Link href={h.href} className="body-link font-display text-lg leading-snug">
                          {h.title}
                        </Link>
                        <p className={`text-sm text-ink-soft mt-1 ${isZh ? "leading-[1.8]" : ""}`}>{h.blurb}</p>
                      </div>
                    </li>
                  ))}
                </ul>
              </div>

              {(isZh && dispatch.moversZh ? dispatch.moversZh : dispatch.movers).length > 0 && (
                <div className="pt-2">
                  <div className="eyebrow mb-3">{isZh ? "进展" : "Movers · 进展"}</div>
                  <ul className="space-y-2">
                    {(isZh && dispatch.moversZh ? dispatch.moversZh : dispatch.movers).map((m) => (
                      <li key={m.number} className="flex items-baseline gap-3 text-sm">
                        <span className="font-mono text-indigo tabular">#{m.number}</span>
                        <Link href={m.href} className="font-medium hover:text-indigo">{m.title}</Link>
                        <span className="text-ink-mute">— {m.reason}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </article>
          </div>

          {/* recent activity column */}
          <aside className="lg:col-span-5">
            <div className="hairline-t hairline-b hairline-l hairline-r bg-paper">
              <div className="bg-ink text-paper px-4 py-2 flex items-center justify-between">
                <div className="font-cjk text-sm tracking-wider">{isZh ? "最新活动" : "最新活动 · Recent activity"}</div>
                <Link href={isZh ? "/zh/feed" : "/feed"} className="font-mono text-[0.7rem] uppercase tracking-wider hover:text-indigo">
                  {isZh ? "全部 →" : "All →"}
                </Link>
              </div>
              <div className="px-4">
                {feed.slice(0, 5).map((item) => (
                  <FeedCard key={item.url} item={item} />
                ))}
                {feed.length === 0 && (
                  <div className="py-8 text-center text-sm text-ink-mute font-mono">
                    {isZh ? "暂无数据 · feed not loaded" : "feed not yet loaded · 暂无数据"}
                  </div>
                )}
              </div>
            </div>
          </aside>
        </div>
      </section>

      {/* WHAT IT IS — 3 column */}
      <section className="bg-paper-deep hairline-t hairline-b">
        <div className="mx-auto max-w-[1400px] px-6 py-16">
          <div className="flex items-baseline gap-4 mb-8 hairline-b pb-4">
            <Seal char="是" />
            <h2 className="font-display">
              {isZh ? "它到底是什么" : "What it actually is"}
            </h2>
          </div>

          <div className="grid md:grid-cols-3 gap-0 col-rule hairline-t hairline-b">
            {isZh ? (
              <>
                <div className="p-6">
                  <div className="eyebrow mb-3">01 · 终端智能体</div>
                  <h3 className="font-display text-xl mb-3">编程智能体，不是聊天框</h3>
                  <p className="text-sm text-ink-soft leading-[1.9]">
                    与 Claude Code、Codex CLI 相同的循环。读、改、跑测试、汇报。
                  </p>
                </div>
                <div className="p-6">
                  <div className="eyebrow mb-3">02 · 沙箱保护</div>
                  <h3 className="font-display text-xl mb-3">三种模式，一套审批</h3>
                  <p className="text-sm text-ink-soft leading-[1.9]">
                    Plan 只读调查，Agent 按需审批，YOLO 自动批准。沙箱：seatbelt (macOS)、landlock (Linux)；Windows 受限令牌。
                  </p>
                </div>
                <div className="p-6">
                  <div className="eyebrow mb-3">03 · 模型自由</div>
                  <h3 className="font-display text-xl mb-3">默认 {facts.defaultModel ?? "DeepSeek V4"}</h3>
                  <p className="text-sm text-ink-soft leading-[1.9]">
                    内建 {facts.providers.length} 个提供商。<code className="inline">deepseek auth set --provider …</code> 切换。
                  </p>
                </div>
              </>
            ) : (
              <>
                <div className="p-6">
                  <div className="eyebrow mb-3">01 · 终端智能体</div>
                  <h3 className="font-display text-xl mb-3">A coding agent, not a chat box</h3>
                  <p className="text-sm text-ink-soft leading-relaxed">
                    Same loop as Claude Code or Codex CLI. It reads, edits, runs tests, reports back.
                  </p>
                </div>
                <div className="p-6">
                  <div className="eyebrow mb-3">02 · 沙箱保护</div>
                  <h3 className="font-display text-xl mb-3">Three modes, one approval system</h3>
                  <p className="text-sm text-ink-soft leading-relaxed">
                    Plan reads, Agent requests approval for risky ops, YOLO auto-approves. Sandboxed via seatbelt (macOS), landlock (Linux); Windows restricted tokens.
                  </p>
                </div>
                <div className="p-6">
                  <div className="eyebrow mb-3">03 · 模型自由</div>
                  <h3 className="font-display text-xl mb-3">{facts.defaultModel ?? "DeepSeek V4"} by default</h3>
                  <p className="text-sm text-ink-soft leading-relaxed">
                    {facts.providers.length} built-in providers. Swap with <code className="inline">deepseek auth set --provider …</code>.
                  </p>
                </div>
              </>
            )}
          </div>
        </div>
      </section>

      {/* HOW IT WORKS — mermaid diagram (replaces brittle ASCII art that
           misaligned under CJK monospace, per dhh's note) */}
      <section className="mx-auto max-w-[1400px] px-6 py-16">
        <div className="flex items-baseline gap-4 mb-8 hairline-b pb-4">
          <Seal char="作" />
          <h2 className="font-display">
            {isZh ? "运作方式" : "How it works"}
          </h2>
        </div>

        <div className="hairline-t hairline-b hairline-l hairline-r bg-paper p-4 sm:p-8">
          <MermaidDiagram
            label={isZh ? "DeepSeek TUI 运作方式示意图" : "DeepSeek TUI architecture diagram"}
            chart={
              isZh
                ? `flowchart TD
    A["用户输入<br/>(TUI · ratatui)"] -->|Op channel| B["Engine<br/>turn loop + tools"]
    B -->|HTTPS / SSE| C["DeepSeek API<br/>V4 family"]
    C -->|stream events| B
    B -->|tool call| T["read_file · edit_file · grep<br/>apply_patch · exec_shell<br/>mcp_&lt;server&gt;_&lt;tool&gt;"]
    T -->|approval Y/N| P["审批对话框<br/>approval dialog"]
    P --> B
    T -->|exec| S["沙箱<br/>seatbelt · landlock · win32"]
    classDef accent fill:#e9eefe,stroke:#0e0e10,stroke-width:1px;
    classDef api fill:#0e0e10,stroke:#0e0e10,color:#ffffff;
    class C api;
    class T,P,S accent;`
                : `flowchart TD
    A["You type<br/>(TUI · ratatui)"] -->|Op channel| B["Engine<br/>turn loop + tools"]
    B -->|HTTPS / SSE| C["DeepSeek API<br/>V4 family"]
    C -->|stream events| B
    B -->|tool call| T["read_file · edit_file · grep<br/>apply_patch · exec_shell<br/>mcp_&lt;server&gt;_&lt;tool&gt;"]
    T -->|approval Y/N| P["Approval<br/>dialog"]
    P --> B
    T -->|exec| S["Sandbox<br/>seatbelt · landlock · win32"]
    classDef accent fill:#e9eefe,stroke:#0e0e10,stroke-width:1px;
    classDef api fill:#0e0e10,stroke:#0e0e10,color:#ffffff;
    class C api;
    class T,P,S accent;`
            }
          />
        </div>

        <p className="mt-3 text-xs font-mono text-ink-mute">
          {isZh
            ? "示意图使用 Mermaid 标准格式渲染。"
            : "Rendered with Mermaid standard syntax."}
        </p>
      </section>

      {/* JOIN IN */}
      <section className="bg-ink text-paper">
        <div className="mx-auto max-w-[1400px] px-6 py-16 grid lg:grid-cols-12 gap-10">
          <div className="lg:col-span-5">
            <div className="eyebrow text-paper-deep/70 mb-3">{isZh ? "加入" : "Join in"}</div>
            <h2 className="font-display text-paper text-4xl leading-tight">
              {isZh ? "这是一个小项目。你的每个补丁都很重要。" : "This is a small project. Your patch matters."}
            </h2>
            <p className={`mt-5 text-paper-deep/80 ${isZh ? "leading-[1.9]" : "leading-relaxed"}`}>
              {isZh
                ? "无 CLA，无赞助商锁定。维护者亲自阅读每一条内容。议题在公开环境下分类。版本从 main 分支发布。"
                : "No CLA. No sponsor lockouts. The maintainer reads everything personally. Issues triaged in the open. Releases cut from main."}
            </p>
          </div>

          <div className="lg:col-span-7 grid sm:grid-cols-3 gap-px bg-paper/15">
            {(isZh
              ? [
                  { t: "提交议题", cn: "提 Bug 或功能建议", d: "Bug 报告、功能需求，或一个好问题。", href: "https://github.com/Hmbown/deepseek-tui/issues/new/choose" },
                  { t: "提交 PR", cn: "贡献代码", d: "Fork、分支、conventional commit、提交 PR。", href: "/zh/contribute" },
                  { t: "发起讨论", cn: "参与设计", d: "路线图、架构设计、任何非 Bug 的话题。", href: "https://github.com/Hmbown/deepseek-tui/discussions" },
                ]
              : [
                  { t: "Open an issue", cn: "提议题", d: "Bug, feature, or just a sharp question.", href: "https://github.com/Hmbown/deepseek-tui/issues/new/choose" },
                  { t: "Send a PR", cn: "提交合并", d: "Fork, branch, conventional commit, open PR.", href: "/contribute" },
                  { t: "Start a discussion", cn: "发起讨论", d: "Roadmap, design, anything that's not a bug.", href: "https://github.com/Hmbown/deepseek-tui/discussions" },
                ]
            ).map((c) => (
              <Link
                key={c.t}
                href={c.href}
                className="bg-ink p-6 hover:bg-indigo group transition-colors"
              >
                <div className="font-cjk text-sm text-indigo group-hover:text-paper transition-colors mb-2">
                  {c.cn}
                </div>
                <div className="font-display text-xl mb-2">{c.t}</div>
                <div className="text-sm text-paper-deep/80 group-hover:text-paper">{c.d}</div>
                <div className="mt-4 font-mono text-[0.7rem] uppercase tracking-widest text-paper-deep/60 group-hover:text-paper">
                  {isZh ? "前往 →" : "Go →"}
                </div>
              </Link>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}
