package io.github.shirainbown.sharelink.download;

/**
 * Renders the self-contained HTML pages for the public download flow (no external CSS/JS
 * dependencies). All dynamic values are HTML-escaped before being embedded.
 */
public final class DownloadPageRenderer {

    private DownloadPageRenderer() {
    }

    public static String renderDownloadPage(String slug, String displayName,
                                            String description, boolean requireEmailVerify) {
        return DOWNLOAD_PAGE
            .replace("__TITLE__", escapeHtml(displayName))
            .replace("__SLUG__", escapeHtml(slug))
            .replace("__DISPLAY_NAME__", escapeHtml(displayName))
            .replace("__DESCRIPTION__", description == null ? "" : escapeHtml(description))
            .replace("__REQUIRE_VERIFY__", String.valueOf(requireEmailVerify));
    }

    public static String renderNotFoundPage(String slug) {
        return renderErrorPage(404, "下载资源不存在或已停用");
    }

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

    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 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);
          }
        """;

    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>
        <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);

    private static final String DOWNLOAD_PAGE = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>__TITLE__ - 资源下载</title>
        <style>
        __SHARED_STYLE__
          .icon-wrap {
            width: 72px; height: 72px; margin: 0 auto 4px; border-radius: 20px;
            background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);
            display: flex; align-items: center; justify-content: center;
          }
          .icon-wrap svg { width: 36px; height: 36px; }
          h1 {
            margin-top: 18px; font-size: 21px; font-weight: 600; color: #111827;
            line-height: 1.4; word-break: break-word;
          }
          .desc {
            margin-top: 10px; color: #6b7280; font-size: 14px; line-height: 1.8;
            white-space: pre-wrap; word-break: break-word;
          }
          .desc:empty { display: none; }
          .section { margin-top: 26px; }
          .section .fields { display: flex; flex-direction: column; gap: 10px; }
          input {
            width: 100%; padding: 11px 14px; border: 1px solid #d1d5db;
            border-radius: 10px; font-size: 14px; outline: none; background: #fff;
            transition: border-color .15s, box-shadow .15s;
          }
          input:focus { border-color: #4f46e5; box-shadow: 0 0 0 3px rgba(79,70,229,.12); }
          .code-row { display: flex; gap: 10px; }
          .code-row input { flex: 1; min-width: 0; }
          .code-row button {
            flex-shrink: 0; padding: 0 16px; border: 1px solid #4f46e5;
            background: #fff; color: #4f46e5; border-radius: 10px; font-size: 13px;
            font-weight: 500; cursor: pointer; white-space: nowrap;
            transition: background .15s, color .15s;
          }
          .code-row button:hover:not(:disabled) { background: #eef2ff; }
          .code-row button:disabled { border-color: #d1d5db; color: #9ca3af; cursor: not-allowed; }
          #download-btn {
            width: 100%; margin-top: 26px; padding: 13px 0; border: none;
            border-radius: 12px; color: #fff; font-size: 15px; font-weight: 600;
            cursor: pointer; letter-spacing: .05em;
            background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
            box-shadow: 0 4px 14px -2px rgba(79,70,229,.45);
            transition: transform .12s, box-shadow .15s, opacity .15s;
          }
          #download-btn:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 6px 18px -2px rgba(79,70,229,.5);
          }
          #download-btn:active:not(:disabled) { transform: translateY(0); }
          #download-btn:disabled { opacity: .55; cursor: not-allowed; box-shadow: none; }
          .tip {
            margin-top: 14px; font-size: 13px; color: #059669; display: flex;
            align-items: center; justify-content: center; gap: 5px;
          }
          .msg { margin-top: 16px; font-size: 13px; line-height: 1.6; min-height: 20px; }
          .msg.error { color: #dc2626; }
          .msg.info { color: #059669; }
          .footer {
            margin-top: 22px; font-size: 12px; color: #9ca3af;
          }
        </style>
        </head>
        <body>
        <div id="app" data-slug="__SLUG__" data-require-verify="__REQUIRE_VERIFY__">
          <div class="card">
            <div class="icon-wrap">
              <svg viewBox="0 0 24 24" fill="none" stroke="#4f46e5" stroke-width="1.8"
                   stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="7 10 12 15 17 10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
            </div>
            <h1>__DISPLAY_NAME__</h1>
            <p class="desc">__DESCRIPTION__</p>
            <div id="verify-section" class="section" hidden>
              <div class="fields">
                <input id="email" type="email" placeholder="请输入邮箱地址" autocomplete="email">
                <div class="code-row">
                  <input id="code" type="text" placeholder="验证码" maxlength="6"
                         autocomplete="off" inputmode="numeric">
                  <button id="send-btn" type="button">发送验证码</button>
                </div>
              </div>
              <p id="verified-tip" class="tip" hidden>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" stroke-width="2.5" stroke-linecap="round"
                     stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                该邮箱已完成验证，可直接下载。
              </p>
            </div>
            <button id="download-btn" type="button">立即下载</button>
            <p id="msg" class="msg"></p>
            <p class="footer">安全下载 · 由 Sharelink 提供</p>
          </div>
        </div>
        <script>
        (function () {
          var app = document.getElementById('app');
          var slug = app.dataset.slug;
          var requireVerify = app.dataset.requireVerify === 'true';
          var API = '/apis/api.sharelink.halo.run/v1alpha1';
          var msg = document.getElementById('msg');
          var downloadBtn = document.getElementById('download-btn');

          function showMsg(text, isError) {
            msg.textContent = text || '';
            msg.className = 'msg ' + (isError ? 'error' : 'info');
          }

          function postJson(url, body) {
            return fetch(url, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(body)
            }).then(function (resp) {
              return resp.json().catch(function () { return null; }).then(function (data) {
                if (!resp.ok) {
                  var detail = data && (data.detail || data.title)
                    ? (data.detail || data.title) : ('请求失败 (' + resp.status + ')');
                  throw new Error(detail);
                }
                return data;
              });
            });
          }

          var emailInput = document.getElementById('email');
          var codeInput = document.getElementById('code');
          var sendBtn = document.getElementById('send-btn');
          var verifiedTip = document.getElementById('verified-tip');
          var emailVerified = false;

          if (requireVerify) {
            document.getElementById('verify-section').hidden = false;

            var checkTimer = null;
            emailInput.addEventListener('input', function () {
              emailVerified = false;
              verifiedTip.hidden = true;
              clearTimeout(checkTimer);
              var email = emailInput.value.trim();
              if (!email || email.indexOf('@') < 0) { return; }
              checkTimer = setTimeout(function () {
                postJson(API + '/email-verify/-/check', { email: email })
                  .then(function (res) {
                    if (res.verified) {
                      emailVerified = true;
                      verifiedTip.hidden = false;
                    }
                  })
                  .catch(function () { /* 忽略，回退到验证码流程 */ });
              }, 500);
            });

            sendBtn.addEventListener('click', function () {
              var email = emailInput.value.trim();
              if (!email) { showMsg('请先输入邮箱地址', true); return; }
              sendBtn.disabled = true;
              postJson(API + '/email-verify/-/send', { email: email })
                .then(function (res) {
                  showMsg('验证码已发送，请查收邮件（' + res.expireMinutes + ' 分钟内有效）', false);
                  startCountdown(res.resendAfterSeconds || 60);
                })
                .catch(function (e) {
                  showMsg(e.message, true);
                  sendBtn.disabled = false;
                });
            });

            function startCountdown(seconds) {
              var remaining = seconds;
              sendBtn.disabled = true;
              sendBtn.textContent = remaining + ' 秒后重发';
              var timer = setInterval(function () {
                remaining -= 1;
                if (remaining <= 0) {
                  clearInterval(timer);
                  sendBtn.disabled = false;
                  sendBtn.textContent = '发送验证码';
                } else {
                  sendBtn.textContent = remaining + ' 秒后重发';
                }
              }, 1000);
            }
          }

          downloadBtn.addEventListener('click', function () {
            showMsg('', false);
            var body = { slug: slug };
            if (requireVerify) {
              var email = emailInput.value.trim();
              if (!email) { showMsg('请输入邮箱地址', true); return; }
              body.email = email;
              if (!emailVerified) {
                var code = codeInput.value.trim();
                if (!code) {
                  showMsg('请输入邮箱验证码；若该邮箱之前已验证过，可直接下载', true);
                  return;
                }
                body.code = code;
              }
            }
            downloadBtn.disabled = true;
            postJson(API + '/downloads/-/token', body)
              .then(function (res) {
                showMsg('开始下载…', false);
                window.location.href = res.fileUrl;
                setTimeout(function () { downloadBtn.disabled = false; }, 3000);
              })
              .catch(function (e) {
                showMsg(e.message, true);
                downloadBtn.disabled = false;
              });
          });
        })();
        </script>
        </body>
        </html>
        """.replace("__SHARED_STYLE__", SHARED_STYLE);
}
