package io.github.shirainbown.sharelink.download;

/**
 * Shared building blocks for the self-contained public pages (download page and
 * protected-link gate page): common CSS, HTML escaping and the generic error page.
 */
public final class PublicPageRenderer {

    private PublicPageRenderer() {
    }

    public static final String SHARED_STYLE = """
          * { margin: 0; padding: 0; box-sizing: border-box; }
          [hidden] { display: none !important; }
          body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
                         "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
            min-height: 100vh; display: flex; align-items: center; justify-content: center;
            padding: 24px 16px; color: #1f2937;
            background: linear-gradient(160deg, #eef2ff 0%, #f5f7fb 45%, #eef7f4 100%);
          }
          #app { width: 100%; max-width: 440px; }
          .card {
            background: #fff; border-radius: 20px; width: 100%; max-width: 440px;
            min-height: 520px; padding: 40px 36px 32px; text-align: center;
            display: flex; flex-direction: column; justify-content: center;
            box-shadow: 0 1px 2px rgba(16,24,40,.04),
                        0 12px 32px -8px rgba(16,24,40,.12);
            border: 1px solid rgba(226,232,240,.8);
          }
        """;

    public static String renderErrorPage(int status, String message, String title) {
        return ERROR_PAGE
            .replace("__STATUS__", String.valueOf(status))
            .replace("__TITLE__", escapeHtml(title))
            .replace("__MESSAGE__", escapeHtml(message));
    }

    public static String escapeHtml(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\"", "&quot;")
            .replace("'", "&#39;");
    }

    private static final String ERROR_PAGE = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>__STATUS__ - __TITLE__</title>
        <style>
        __SHARED_STYLE__
          .status-badge {
            width: 64px; height: 64px; margin: 0 auto; border-radius: 50%;
            background: #fef2f2; color: #dc2626;
            display: flex; align-items: center; justify-content: center;
            font-size: 20px; font-weight: 700;
          }
          .msg { margin-top: 18px; color: #4b5563; font-size: 15px; line-height: 1.7; }
        </style>
        </head>
        <body>
          <div class="card">
            <div class="status-badge">__STATUS__</div>
            <p class="msg">__MESSAGE__</p>
          </div>
        </body>
        </html>
        """.replace("__SHARED_STYLE__", SHARED_STYLE);
}
