package io.github.shirainbown.sharelink.download;

/**
 * Renders the self-contained gate page for protected links (no external CSS/JS
 * dependencies). All dynamic values are HTML-escaped before being embedded.
 */
public final class LinkPageRenderer {

    private LinkPageRenderer() {
    }

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

    public static String renderNotFoundPage(String slug) {
        return PublicPageRenderer.renderErrorPage(404, "链接不存在或已停用", "无法访问");
    }

    private static final String LINK_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; }
          #access-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;
          }
          #access-btn:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 6px 18px -2px rgba(79,70,229,.5);
          }
          #access-btn:active:not(:disabled) { transform: translateY(0); }
          #access-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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
              </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="access-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 accessBtn = document.getElementById('access-btn');

          if (requireVerify) {
            accessBtn.textContent = '验证并访问';
          }

          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, purpose: 'link' })
                .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);
            }
          }

          accessBtn.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;
              }
            }
            accessBtn.disabled = true;
            postJson(API + '/links/-/token', body)
              .then(function (res) {
                showMsg('正在跳转…', false);
                window.location.href = res.url;
                setTimeout(function () { accessBtn.disabled = false; }, 3000);
              })
              .catch(function (e) {
                showMsg(e.message, true);
                accessBtn.disabled = false;
              });
          });
        })();
        </script>
        </body>
        </html>
        """.replace("__SHARED_STYLE__", PublicPageRenderer.SHARED_STYLE);
}
