<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>RDC 登录</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }

    html, body {
      width: 100%; height: 100%;
      background: #fff;
      font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
      -webkit-font-smoothing: antialiased;
      overflow: hidden;
    }

    .login-container {
      width: 100%; height: 100%;
      display: flex; flex-direction: column;
      align-items: center; justify-content: center;
      padding: 20px 30px;
      background: #fff;
      user-select: none;
      position: relative;
    }

    /* Logo & Brand */
    .brand { text-align: center; margin-bottom: 22px; }
    .brand-name {
      font-size: 22px; font-weight: 700; color: #1a1a1a;
      letter-spacing: 2px;
    }

    /* Tab switcher */
    .tab-bar {
      display: flex; gap: 0;
      border-bottom: 1px solid #eee;
      margin-bottom: 22px;
      width: 100%;
    }
    .tab-item {
      flex: 1; text-align: center;
      padding: 10px 0; font-size: 13px;
      cursor: pointer;
      color: #999; transition: all 0.25s;
      font-weight: 400;
      border-bottom: 2px solid transparent;
      margin-bottom: -1px;
    }
    .tab-item.active {
      color: #1a1a1a;
      border-bottom-color: #2F80ED;
      font-weight: 700;
    }

    /* Panels */
    .panel { display: none; width: 100%; text-align: center; }
    .panel.active { display: block; }

    /* WeChat QR Panel */
    .qr-box {
      width: 240px;
      margin: 0 auto 12px;
      display: flex; align-items: center; justify-content: center;
      position: relative;
      overflow: hidden;
    }
    .qr-loading {
      width: 180px; height: 180px;
      background: #fafafa;
      border: 1px solid #eee;
      border-radius: 12px;
      display: flex; align-items: center; justify-content: center;
      font-size: 12px; color: #999;
    }
    .qr-wrap {
      width: 240px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .qr-wrap img {
      width: 180px; height: 180px;
      border-radius: 8px;
      border: 1px solid #eee;
      image-rendering: pixelated;
    }
    .qr-tip {
      font-size: 13px; color: #555;
      margin: 8px 0 4px;
      text-align: center;
    }
    .qr-tip strong { color: #07c160; }
    .qr-sub-tip {
      font-size: 12px; color: #999;
      text-align: center;
      margin-bottom: 4px;
    }
    .qr-sub-tip span { color: #e74c3c; font-weight: 700; }

    /* Form */
    .form-group { margin-bottom: 12px; text-align: left; }
    .form-label {
      font-size: 12px; color: #666;
      margin-bottom: 6px; display: block;
    }
    .input-row { display: flex; gap: 8px; }
    .form-input {
      flex: 1; height: 36px;
      border: 1px solid #e0e0e0; border-radius: 6px;
      padding: 0 12px; font-size: 13px;
      outline: none; transition: border-color 0.2s;
      background: #fafafa;
      font-family: inherit;
      min-width: 0;
    }
    .form-input:focus { border-color: #2F80ED; background: #fff; }
    .form-input::placeholder { color: #ccc; }
    .btn-code {
      flex-shrink: 0;
      width: 90px; height: 36px;
      background: #fff; border: 1px solid #2F80ED;
      border-radius: 6px; color: #2F80ED;
      font-size: 11px; cursor: pointer;
      transition: all 0.2s; white-space: nowrap;
      font-family: inherit;
    }
    .btn-code:hover:not(:disabled) { background: #2F80ED; color: #fff; }
    .btn-code:disabled {
      border-color: #ddd; color: #bbb;
      cursor: not-allowed; background: #fafafa;
    }

    .btn-login {
      width: 100%; height: 38px;
      background: #2F80ED;
      border: none; border-radius: 6px;
      color: #fff; font-size: 14px; font-weight: 700;
      cursor: pointer; transition: all 0.2s;
      margin-top: 4px;
      font-family: inherit;
      letter-spacing: 1px;
    }
    .btn-login:hover:not(:disabled) { background: #1a6dd4; }
    .btn-login:active:not(:disabled) { transform: scale(0.98); }
    .btn-login:disabled { background: #aac8f0; cursor: not-allowed; }

    /* Error message */
    .error-msg {
      font-size: 12px; color: #e74c3c;
      margin-top: 8px; min-height: 16px;
      text-align: center;
    }
    .info-msg {
      font-size: 12px; color: #999;
      margin-top: 10px; text-align: center;
    }
    .info-msg .hl { color: #e74c3c; font-weight: 700; }

    /* Footer */
    .footer { margin-top: 20px; text-align: center; }
    .footer-text { font-size: 10px; color: #999; }
    .footer-text a { color: #2F80ED; text-decoration: none; }

    /* Login success overlay */
    .success-overlay {
      position: absolute; inset: 0;
      background: rgba(255,255,255,0.97);
      display: none; flex-direction: column;
      align-items: center; justify-content: center;
      z-index: 100;
    }
    .success-overlay.show { display: flex; }
    .success-icon {
      width: 56px; height: 56px;
      background: #07c160;
      border-radius: 50%;
      display: flex; align-items: center; justify-content: center;
      margin-bottom: 16px;
    }
    .success-icon svg { width: 28px; height: 28px; fill: #fff; }
    .success-title {
      font-size: 18px; font-weight: 700; color: #1a1a1a;
      margin-bottom: 8px;
    }
    .success-desc { font-size: 13px; color: #666; margin-bottom: 4px; }
    .success-trial {
      font-size: 12px; color: #2F80ED;
      background: #eef5ff; padding: 6px 16px;
      border-radius: 4px; margin-top: 14px;
      border-left: 3px solid #2F80ED;
    }
  </style>
</head>
<body oncontextmenu="return false;">

  <div class="login-container" id="app">
    <div class="brand">
      <div class="brand-name">RDC提案搭子</div>
    </div>

    <div class="tab-bar">
      <div class="tab-item" :class="{active: tab==='wechat'}" @click="tab='wechat'">微信扫码</div>
      <div class="tab-item" :class="{active: tab==='phone'}" @click="tab='phone'">手机号</div>
      <div class="tab-item" :class="{active: tab==='email'}" @click="tab='email'">邮箱</div>
    </div>

    <!-- WeChat Panel -->
    <div class="panel" :class="{active: tab==='wechat'}">
      <!-- 加载中 -->
      <div v-if="wechatStatus==='loading'" class="qr-box">
        <div class="qr-loading">加载中...</div>
      </div>
      <!-- 二维码容器 -->
      <div v-show="wechatStatus==='ready'" class="qr-box">
        <div class="qr-wrap">
          <img :src="wechatQrUrl" alt="微信扫码登录" />
        </div>
      </div>
      <!-- 过期 -->
      <div v-if="wechatStatus==='expired'" class="qr-box" style="cursor:pointer;height:176px;" @click="requestWechatQr">
        <div class="qr-loading" style="flex-direction:column;gap:8px;">
          <span style="font-size:28px;">🔄</span>
          <span>二维码已过期，点击刷新</span>
        </div>
      </div>
      <!-- 错误 -->
      <div v-if="wechatStatus==='error'" class="qr-box" style="cursor:pointer;height:176px;" @click="requestWechatQr">
        <div class="qr-loading" style="flex-direction:column;gap:6px;">
          <span style="font-size:12px;color:#e74c3c;">{{ wechatError }}</span>
          <span style="font-size:11px;color:#999;">点击重试</span>
        </div>
      </div>
      <p class="qr-tip" v-if="wechatStatus==='ready'||wechatStatus==='loading'">打开 <strong>微信</strong> 扫码关注并登录</p>
      <p class="qr-sub-tip" v-if="wechatStatus==='ready'||wechatStatus==='loading'">新用户关注即注册 <span>赠送7天免费试用</span></p>
      <p class="error-msg" v-show="errorMsg && tab==='wechat'">{{ errorMsg }}</p>
    </div>

    <!-- Phone Panel -->
    <div class="panel" :class="{active: tab==='phone'}">
      <div class="form-group">
        <label class="form-label">手机号</label>
        <input class="form-input" type="tel" placeholder="请输入手机号" v-model="phone" maxlength="11">
      </div>
      <div class="form-group">
        <label class="form-label">验证码</label>
        <div class="input-row">
          <input class="form-input" type="text" placeholder="请输入验证码" v-model="phoneCode" maxlength="6">
          <button class="btn-code" :disabled="phoneCountdown>0||sendingPhone" @click="sendPhoneCode">
            {{ phoneCountdown > 0 ? phoneCountdown + 's' : (sendingPhone ? '发送中' : '获取验证码') }}
          </button>
        </div>
      </div>
      <button class="btn-login" :disabled="loggingIn" @click="loginByPhone">{{ loggingIn ? '登录中...' : '登录' }}</button>
      <p class="error-msg" v-show="errorMsg">{{ errorMsg }}</p>
      <p class="info-msg">新用户登录即注册，<span class="hl">赠送7天免费试用</span></p>
    </div>

    <!-- Email Panel -->
    <div class="panel" :class="{active: tab==='email'}">
      <div class="form-group">
        <label class="form-label">邮箱地址</label>
        <input class="form-input" type="email" placeholder="请输入邮箱地址" v-model="email">
      </div>
      <div class="form-group">
        <label class="form-label">验证码</label>
        <div class="input-row">
          <input class="form-input" type="text" placeholder="请输入验证码" v-model="emailCode" maxlength="6">
          <button class="btn-code" :disabled="emailCountdown>0||sendingEmail" @click="sendEmailCode">
            {{ emailCountdown > 0 ? emailCountdown + 's' : (sendingEmail ? '发送中' : '获取验证码') }}
          </button>
        </div>
      </div>
      <button class="btn-login" :disabled="loggingIn" @click="loginByEmail">{{ loggingIn ? '登录中...' : '登录' }}</button>
      <p class="error-msg" v-show="errorMsg">{{ errorMsg }}</p>
      <p class="info-msg">新用户登录即注册，<span class="hl">赠送7天免费试用</span></p>
    </div>

    <div class="footer">
      <p class="footer-text">登录即表示同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a></p>
      <p style="font-size:10px;color:#aaa;margin-top:4px;">由RDC住宅设计中心提供</p>
    </div>

    <!-- Login Success Overlay -->
    <div class="success-overlay" :class="{show: showSuccess}">
      <div class="success-icon">
        <svg viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>
      </div>
      <div class="success-title">登录成功</div>
      <div class="success-desc">{{ successDesc }}</div>
      <div class="success-trial" v-show="trialTip">{{ trialTip }}</div>
    </div>
  </div>

  <!-- 本地 Vue -->
  <script src="vue.min.js"></script>
  <script>
    // 用 sketchup.callback 与 Ruby 桥接；浏览器中调试时退化为 console.log
    function callRuby(action, payload) {
      try {
        if (window.sketchup && typeof window.sketchup[action] === 'function') {
          window.sketchup[action](JSON.stringify(payload || {}));
        } else {
          console.log('[BrowserDebug]', action, payload);
        }
      } catch (e) { console.error(e); }
    }

    var app = new Vue({
      el: '#app',
      data: {
        tab: 'phone',
        phone: '',
        phoneCode: '',
        phoneCountdown: 0,
        sendingPhone: false,
        email: '',
        emailCode: '',
        emailCountdown: 0,
        sendingEmail: false,
        loggingIn: false,
        showSuccess: false,
        successDesc: '欢迎使用 RDC 提案搭子',
        trialTip: '',
        errorMsg: '',
        // WeChat
        wechatStatus: 'loading', // loading | ready | expired | error
        wechatError: '',
        wechatQrUrl: '', // 公众号二维码图片 URL
        debugInfo: ''
      },
      watch: {
        tab: function (val) {
          this.errorMsg = '';
          if (val === 'wechat') {
            this.requestWechatQr();
          }
        }
      },
      methods: {
        requestWechatQr: function () {
          this.wechatStatus = 'loading';
          this.wechatError = '';
          this.wechatQrUrl = '';
          callRuby('rdc_wechat_qrcode', {});
        },
        startCountdown: function (key) {
          var self = this;
          self[key] = 60;
          var timer = setInterval(function () {
            self[key]--;
            if (self[key] <= 0) clearInterval(timer);
          }, 1000);
        },
        sendPhoneCode: function () {
          if (!/^1[3-9]\d{9}$/.test(this.phone)) {
            this.errorMsg = '请输入正确的手机号';
            return;
          }
          this.errorMsg = '';
          this.sendingPhone = true;
          callRuby('rdc_send_sms', { phone: this.phone });
        },
        sendEmailCode: function () {
          if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email)) {
            this.errorMsg = '请输入正确的邮箱地址';
            return;
          }
          this.errorMsg = '';
          this.sendingEmail = true;
          callRuby('rdc_send_email', { email: this.email });
        },
        loginByPhone: function () {
          if (!this.phone || !this.phoneCode) {
            this.errorMsg = '请填写手机号和验证码';
            return;
          }
          this.errorMsg = '';
          this.loggingIn = true;
          callRuby('rdc_login_phone', { phone: this.phone, code: this.phoneCode });
        },
        loginByEmail: function () {
          if (!this.email || !this.emailCode) {
            this.errorMsg = '请填写邮箱和验证码';
            return;
          }
          this.errorMsg = '';
          this.loggingIn = true;
          callRuby('rdc_login_email', { email: this.email, code: this.emailCode });
        },
        // 由 Ruby 通过 execute_script 调用
        onCallback: function (action, data) {
          if (action === 'send_sms' || action === 'send_email') {
            var key = action === 'send_sms' ? 'sendingPhone' : 'sendingEmail';
            this[key] = false;
            if (data && data.code === 'SUCCESS') {
              this.startCountdown(action === 'send_sms' ? 'phoneCountdown' : 'emailCountdown');
              this.errorMsg = '';
            } else {
              this.errorMsg = (data && data.message) || '验证码发送失败';
            }
          } else if (action === 'login_success') {
            this.loggingIn = false;
            this.showSuccess = true;
            if (data && data.is_new_user && data.subscription && data.subscription.status === 'trial') {
              this.successDesc = '欢迎使用 RDC 提案搭子';
              this.trialTip = '7天免费试用已开启';
            } else if (data && data.subscription && data.subscription.expires_at) {
              this.successDesc = '欢迎回来';
              this.trialTip = '订阅有效期至 ' + String(data.subscription.expires_at).split('T')[0];
            } else {
              this.successDesc = '欢迎使用 RDC 提案搭子';
              this.trialTip = '';
            }
          } else if (action === 'login_failed') {
            this.loggingIn = false;
            this.errorMsg = (data && data.message) || '登录失败，请重试';
          } else if (action === 'wechat_qr_image') {
            // 收到公众号二维码图片 URL
            if (data && data.qr_url) {
              this.wechatQrUrl = data.qr_url;
              this.wechatStatus = 'ready';
            } else {
              this.wechatStatus = 'error';
              this.wechatError = '获取二维码失败';
            }
          } else if (action === 'wechat_error') {
            this.wechatStatus = 'error';
            this.wechatError = (data && data.message) || '获取授权链接失败';
          } else if (action === 'wechat_expired') {
            this.wechatStatus = 'expired';
          }
        }
      }
    });

    // 暴露给 Ruby 调用
    window.rdcLoginCallback = function (action, data) {
      app.onCallback(action, data);
    };
  </script>
</body>
</html>
