// download-page.jsx - standalone download and changelog page.

const DEFAULT_RELEASE_INFO = {
  current: {
    version: "v0.1.3",
    channel: "公测版",
    date: "2024-05-28",
    summary: "本次更新进一步提升了长篇写作体验与稳定性，并增强了本地保存与恢复能力。",
    sections: [
      {
        title: "新增",
        items: [
          "本地项目保存：支持完整离线编辑与本地备份。",
          "自动恢复：在异常退出后可恢复未保存的编辑内容。",
          "桌面下载中心：内置下载与安装管理，更新更便捷。",
        ],
      },
      {
        title: "优化",
        items: [
          "大纲切换速度：大幅提升大纲视图与文档之间的切换效率。",
          "设置面板加载体验：优化加载流程，开启设置更顺畅。",
          "长篇工程稳定性：优化内存占用，提升超长文档编辑稳定性。",
        ],
      },
      {
        title: "修复",
        items: [
          "修复部分情况下同步失败的问题。",
          "修复 Windows 安装路径包含特殊字符时的安装问题。",
          "修复在部分字体缺失时，段落显示异常的问题。",
        ],
      },
    ],
  },
  history: [
    { version: "v0.7.9", tag: "稳定版", date: "2024-04-16", note: "优化导出体验，修复部分已知问题。" },
    { version: "v0.7.8", tag: "稳定版", date: "2024-03-21", note: "改进多端同步稳定性，优化编辑器性能。" },
    { version: "v0.7.6", tag: "稳定版", date: "2024-02-02", note: "新增夜间模式，改进大纲与卡片视图。" },
  ],
  releases: [
    { os: "Windows", name: "x64 安装包", size: "296 MB", ext: "exe", href: "https://novel-studio-releases-1345572211.cos.ap-shanghai.myqcloud.com/desktop/Novel-Studio-Setup-0.1.3-x64.exe" },
  ],
  plannedPlatforms: [
    { os: "macOS", note: "桌面端规划中，优先补齐签名、公证与自动更新链路。" },
    { os: "Linux", note: "桌面端规划中，后续按 AppImage / 包管理分发节奏推进。" },
  ],
  releaseAllHref: "/download/#changelog",
};

function normalizeReleaseInfo(payload) {
  const info = payload && typeof payload === "object" ? payload : {};
  return {
    current: {
      ...DEFAULT_RELEASE_INFO.current,
      ...(info.current || {}),
      sections: Array.isArray(info.current?.sections) && info.current.sections.length > 0
        ? info.current.sections
        : DEFAULT_RELEASE_INFO.current.sections,
    },
    history: Array.isArray(info.history) && info.history.length > 0
      ? info.history
      : DEFAULT_RELEASE_INFO.history,
    releases: Array.isArray(info.releases) && info.releases.length > 0
      ? info.releases
      : DEFAULT_RELEASE_INFO.releases,
    plannedPlatforms: Array.isArray(info.plannedPlatforms)
      ? info.plannedPlatforms
      : DEFAULT_RELEASE_INFO.plannedPlatforms,
    releaseAllHref: info.releaseAllHref || DEFAULT_RELEASE_INFO.releaseAllHref,
  };
}

function ChangeLogDrawer({ open, onClose, releaseInfo }) {
  const current = releaseInfo.current;
  React.useEffect(() => {
    if (!open) return undefined;
    const onKeyDown = (event) => {
      if (event.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKeyDown);
    document.body.classList.add("changelog-open");
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.classList.remove("changelog-open");
    };
  }, [open, onClose]);

  return (
    <div className="changelog-layer" data-open={open ? "1" : "0"} aria-hidden={!open}>
      <button className="changelog-backdrop" type="button" onClick={onClose} tabIndex={open ? 0 : -1} aria-label="关闭更新日志" />
      <aside className="changelog-panel" role="dialog" aria-modal="true" aria-labelledby="changelog-title">
        <button className="changelog-close" type="button" onClick={onClose} aria-label="关闭更新日志">
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        </button>

        <header className="changelog-panel__head">
          <h2 id="changelog-title">更新日志</h2>
          <p>笔随 Novel Studio 的版本更新记录</p>
        </header>

        <section className="changelog-current" aria-labelledby="current-release-title">
          <div className="release-meta-row">
            <span>当前版本</span>
            <time>{current.date}</time>
          </div>
          <h3 id="current-release-title">
            {current.version} · {current.channel}
          </h3>
          <p>{current.summary}</p>

          <div className="change-section-list">
            {current.sections.map((section) => (
              <article className="change-section" key={section.title}>
                <h4>{section.title}</h4>
                <ul>
                  {section.items.map((item) => <li key={item}>{item}</li>)}
                </ul>
              </article>
            ))}
          </div>
        </section>

        <section className="changelog-history" aria-labelledby="history-title">
          <h3 id="history-title">版本历史</h3>
          <div className="history-list">
            {releaseInfo.history.map((entry) => (
              <a className="history-row" href="/download/" key={entry.version}>
                <span>
                  <strong>{entry.version} · {entry.tag}</strong>
                  <em>{entry.note}</em>
                </span>
                <time>{entry.date}</time>
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M9 5l7 7-7 7" />
                </svg>
              </a>
            ))}
          </div>
          <a className="release-page-link" href={releaseInfo.releaseAllHref}>
            查看下载与更新中心
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M5 12h14M13 6l6 6-6 6" />
            </svg>
          </a>
        </section>
      </aside>
    </div>
  );
}

function Trait({ label, text, icon }) {
  return (
    <div className="download-trait">
      <span aria-hidden="true">{icon}</span>
      <strong>{label}</strong>
      <em>{text}</em>
    </div>
  );
}

function DownloadPage() {
  const copy = (window.COPY || {}).zh;
  const [changelogOpen, setChangelogOpen] = React.useState(false);
  const [releaseInfo, setReleaseInfo] = React.useState(DEFAULT_RELEASE_INFO);

  React.useEffect(() => {
    let cancelled = false;
    fetch("/release-info.json", { cache: "no-store" })
      .then((response) => (response.ok ? response.json() : null))
      .then((data) => {
        if (!cancelled && data) setReleaseInfo(normalizeReleaseInfo(data));
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, []);

  if (!copy) return <div style={{ padding: 40 }}>Loading...</div>;
  const current = releaseInfo.current;
  const desktopReleaseHead = `桌面客户端 · ${current.version}`;
  const releaseCards = releaseInfo.releases.length > 0
    ? releaseInfo.releases
    : copy.cta.releases;
  const primaryDownloadHref = releaseCards[0]?.href || "/download/#desktop";
  const latestPreviewSections = current.sections.map((section) => ({
    ...section,
    previewItems: section.items.slice(0, 2),
    hiddenCount: Math.max(0, section.items.length - 2),
  }));

  return (
    <div className="download-page-shell">
      <Nav copy={copy} />

      <main className="download-main">
        <section className="download-hero" aria-labelledby="download-title">
          <div className="download-hero__copy">
            <span className="download-kicker">下载与开始</span>
            <h1 id="download-title">把笔随放到你的桌面。</h1>
            <p>
              Web 版可以立即打开；桌面客户端适合长期写作，支持完整离线、本地保存和更稳定的长篇工程管理。
            </p>
            <div className="download-actions">
              <a className="btn btn-primary" href={primaryDownloadHref}>下载桌面版&nbsp; {current.version}</a>
              <a className="btn btn-ghost" href="/app/">打开 Web 版</a>
            </div>
            <div className="download-traits" aria-label="桌面版能力">
              <Trait icon="▢" label="本地保存" text="工程数据安全存储在本地" />
              <Trait icon="↗" label="离线可用" text="无网络也能安心写作" />
              <Trait icon="◎" label="多端同步" text="多设备间安全同步工程" />
            </div>
          </div>

          <aside className="download-status" aria-label="当前状态">
            <span className="status-ribbon" aria-hidden="true">只</span>
            <h2>当前状态</h2>
            <div className="status-divider" />
            <strong>公测阶段</strong>
            <p>当前为公测版本，推荐使用桌面端进行长篇创作。正式版发布前，授权方式与下载流程可能会调整。</p>
            <div className="status-latest">
              <span>最新更新：</span>
              <b>{current.version}</b>
              <button type="button" onClick={() => setChangelogOpen(true)}>
                查看更新日志
                <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M5 12h14M13 6l6 6-6 6" />
                </svg>
              </button>
            </div>
          </aside>
        </section>

        <section className="download-section download-desktop" id="desktop" aria-labelledby="desktop-title">
          <div className="download-section__bar">
            <div>
              <h2 id="desktop-title">{desktopReleaseHead}</h2>
              <p>支持完整离线、稳定长篇工程管理，推荐用于长期写作。</p>
            </div>
            <div className="download-tabs" aria-label="下载说明">
              <a href="#desktop">推荐版本</a>
              <a href="#requirements">系统要求</a>
              <a href="#install">安装说明</a>
            </div>
          </div>

          <div className="rel-grid">
            {releaseCards.map((release, index) => (
              <ReleaseCard rel={release} key={index} />
            ))}
          </div>

          {releaseInfo.plannedPlatforms.length > 0 && (
            <div className="download-planned" aria-label="规划中的桌面平台">
              {releaseInfo.plannedPlatforms.map((platform) => (
                <article key={platform.os}>
                  <span>{platform.os}</span>
                  <strong>规划中</strong>
                  <p>{platform.note}</p>
                </article>
              ))}
            </div>
          )}

          <div className="download-support">
            <article id="requirements">
              <span>系统要求</span>
              <p>Windows 10/11、macOS 12+ 或主流 Linux 桌面环境；推荐 8GB 以上内存，用于长篇工程与本地素材管理。</p>
            </article>
            <article id="install">
              <span>安装说明</span>
              <p>公测包可能出现系统安全提示；请从本站或 GitHub Release 获取安装包。正式版发布前会继续完善签名与自动更新流程。</p>
            </article>
          </div>
        </section>

        <section className="download-section download-changelog" id="changelog" aria-labelledby="recent-title">
          <div className="download-section__bar">
            <div>
              <span className="download-kicker">最近更新</span>
              <h2 id="recent-title">最近更新 · Changelog</h2>
            </div>
          </div>

          <div className="changelog-preview">
            <article className="latest-release">
              <div className="latest-release__version">
                <strong>{current.version}</strong>
                <span>最新</span>
                <time>{current.date}</time>
              </div>
              <div className="latest-release__body">
                <p className="latest-release__summary">{current.summary}</p>
                <div className="latest-release__groups">
                {latestPreviewSections.map((section) => (
                  <div className="latest-release__group" key={section.title}>
                    <h3>
                      {section.title}
                      <span>{section.items.length}</span>
                    </h3>
                    <ul>
                      {section.previewItems.map((item) => <li key={item}>{item}</li>)}
                    </ul>
                    {section.hiddenCount > 0 && (
                      <button className="latest-release__more" type="button" onClick={() => setChangelogOpen(true)}>
                        还有 {section.hiddenCount} 条，查看完整
                      </button>
                    )}
                  </div>
                ))}
                </div>
              </div>
            </article>

            <aside className="history-preview" aria-label="历史版本">
              {releaseInfo.history.map((entry) => (
                <button type="button" key={entry.version} onClick={() => setChangelogOpen(true)}>
                  <strong>{entry.version}</strong>
                  <span>{entry.note}</span>
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              ))}
              <button className="history-preview__all" type="button" onClick={() => setChangelogOpen(true)}>
                查看完整更新日志
                <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M5 12h14M13 6l6 6-6 6" />
                </svg>
              </button>
            </aside>
          </div>
        </section>

        <section className="download-section download-plans" id="plans" aria-labelledby="plans-title">
          <div className="download-section__head">
            <span className="download-kicker">版本与授权</span>
            <h2 id="plans-title">先写起来，再决定怎么拥有它。</h2>
            <p>这一页以后会承接定价说明；现在先把公测期的能力边界讲清楚。</p>
          </div>

          <div className="plan-strip">
            <article>
              <span>试用</span>
              <h3>Web 快速打开</h3>
              <p>适合先体验正文、设定台和示例工程，不需要先安装客户端。</p>
            </article>
            <article>
              <span>桌面</span>
              <h3>本地优先写作</h3>
              <p>适合长期项目，离线可用，稿件和设定优先保存在自己的机器上。</p>
            </article>
            <article>
              <span>Pro / BYOK</span>
              <h3>Agent 与同步增强</h3>
              <p>后续放置 Agent 额度、自带模型 Key、多端同步和授权说明。</p>
            </article>
          </div>
        </section>
      </main>

      <Footer copy={copy} />
      <ChangeLogDrawer open={changelogOpen} onClose={() => setChangelogOpen(false)} releaseInfo={releaseInfo} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<DownloadPage />);
