const { escapeHtml } = require('../utils/html');

// 生成 GitHub Pages 的 404 回跳页：将 /<id> 形式的路径深链接转换为 /?page=<id>
function generate404Html(config) {
  const siteTitle =
    config && config.site && typeof config.site.title === 'string' ? config.site.title : 'MeNav';
  const safeTitle = escapeHtml(siteTitle);

  return `<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="robots" content="noindex" />
    <title>${safeTitle} - 页面未找到</title>
    <style>
      body {
        margin: 0;
        padding: 40px 16px;
        font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue',
          Arial, 'Noto Sans', 'Liberation Sans', sans-serif;
        background: #0b1020;
        color: #e6e6e6;
      }
      .container {
        max-width: 760px;
        margin: 0 auto;
      }
      h1 {
        margin: 0 0 12px;
        font-size: 22px;
      }
      p {
        margin: 8px 0;
        line-height: 1.6;
        color: rgba(230, 230, 230, 0.9);
      }
      a {
        color: #74c0fc;
      }
      code {
        background: rgba(255, 255, 255, 0.08);
        padding: 2px 6px;
        border-radius: 4px;
      }
    </style>
    <script>
      (function () {
        try {
          var l = window.location;
          var pathname = l.pathname || '';
          var segments = pathname.split('/').filter(Boolean);

          // 用户站点：/<id>
          // 仓库站点：/<repo>/<id>
          var repoBase = '';
          var pageId = '';
          if (segments.length === 1) {
            pageId = segments[0];
          } else if (segments.length === 2) {
            repoBase = '/' + segments[0];
            pageId = segments[1];
          } else {
            repoBase = segments.length > 1 ? '/' + segments[0] : '';
            pageId = segments.length ? segments[segments.length - 1] : '';
          }

          if (!pageId) {
            l.replace(repoBase + '/');
            return;
          }

          var target = repoBase + '/?page=' + encodeURIComponent(pageId) + (l.hash || '');
          l.replace(target);
        } catch (e) {
          // 兜底：回到首页
          window.location.replace('./');
        }
      })();
    </script>
  </head>
  <body>
    <div class="container">
      <h1>页面未找到</h1>
      <p>若你访问的是“页面路径深链接”，系统将自动回跳到 <code>?page=</code> 形式的可用地址。</p>
      <p><a href="./">返回首页</a></p>
    </div>
  </body>
</html>
`;
}

module.exports = {
  generate404Html,
};
