var __qrSession = '';
var __qrCookie = '';
var __qrType = '';
var __qrTimer = null;
var __qrNickname = '';
var __qrStorageUsed = '';
var __qrStorageTotal = '';
var QR_TYPES = ['quark','baidu'];

function openAddDialog(){
  document.getElementById('dlg_type').value = 'quark';
  document.getElementById('dlg_cookie').value = '';
  document.getElementById('dlg_promo').value = '';
  document.getElementById('dlg_nick').value = '';
  document.getElementById('dlg_storage_info').textContent = '扫码后自动获取';
  resetQR();
  onDlgTypeChange();
  document.getElementById('modalBg').style.display = 'flex';
}

function closeDialog(){
  cancelQRPoll();
  document.getElementById('modalBg').style.display = 'none';
}

function onDlgTypeChange(){
  var t = document.getElementById('dlg_type').value;
  document.getElementById('dlg_qr_section').style.display = (QR_TYPES.indexOf(t)!==-1) ? 'block' : 'none';
}

function resetQR(){
  cancelQRPoll();
  __qrSession = ''; __qrCookie = ''; __qrNickname = ''; __qrStorageUsed = ''; __qrStorageTotal = '';
  document.getElementById('dlg_qr_status').textContent = '点击下方按钮生成扫码链接';
  document.getElementById('dlg_qr_btn').disabled = false;
  document.getElementById('dlg_qr_btn').textContent = '生成扫码链接';
  document.getElementById('dlg_qr_btn').style.display = '';
  document.getElementById('dlg_qr_hint').textContent = '';
}

function doStartQR(){
  __qrType = document.getElementById('dlg_type').value;
  document.getElementById('dlg_qr_btn').disabled = true;
  document.getElementById('dlg_qr_btn').textContent = '生成中...';
  document.getElementById('dlg_qr_status').textContent = '正在生成二维码...';
  api('/api/admin/'+__qrType+'/qr-login/start', {method:'POST'}).then(function(d){
    if(d.error){
      document.getElementById('dlg_qr_status').innerHTML = '<span style="color:var(--danger)">❌ '+d.error+'</span>';
      document.getElementById('dlg_qr_btn').disabled=false;
      document.getElementById('dlg_qr_btn').textContent='重试';
      return;
    }
    __qrSession = d.sessionId;
    var url = d.qrUrl||d.url||'';
    if(url){
      var qrSrc = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(url);
      document.getElementById('dlg_qr_status').innerHTML = '<img src="'+qrSrc+'" style="max-width:200px;max-height:200px;border:1px solid var(--border);border-radius:4px;display:block;margin:0 auto"><p style="font-size:11px;color:var(--sub);margin-top:6px;text-align:center">用对应 App 扫码并在手机上确认登录</p>';
    }
    document.getElementById('dlg_qr_hint').textContent = '等待扫码确认...';
    document.getElementById('dlg_qr_btn').textContent = '重新生成';
    document.getElementById('dlg_qr_btn').disabled = false;
    pollQR();
  });
}

function pollQR(){
  if(!__qrSession) return;
  __qrTimer = setTimeout(function(){
    api('/api/admin/'+__qrType+'/qr-login/'+__qrSession+'/status').then(function(d){
      if(d.status==='logged_in'){
        __qrCookie = d.cookie||'';
        __qrNickname = d.nickname||'';
        __qrStorageUsed = d.storage_used||'';
        __qrStorageTotal = d.storage_total||'';
        if(__qrNickname){ var n = document.getElementById('dlg_nick'); if(!n.value.trim()) n.value = __qrNickname; }
        if(d.promotion_account){ var p = document.getElementById('dlg_promo'); if(!p.value.trim()) p.value = d.promotion_account; }
        var si = document.getElementById('dlg_storage_info');
        if(__qrStorageTotal){
          si.textContent = '💾 ' + (__qrStorageUsed||'?') + ' / ' + __qrStorageTotal;
          si.style.color = 'var(--success)';
        } else { si.textContent = '空间信息未获取'; si.style.color = 'var(--sub)'; }
        if(d.autoUpdated){
          document.getElementById('dlg_qr_status').innerHTML = '<span style="color:var(--success);font-size:14px">✅ 扫码成功！已自动更新现有账号 #'+d.updatedConfigId+'</span>';
          cancelQRPoll();
          toast('✅ 已自动更新账号','success');
          setTimeout(function(){ closeDialog(); nav('cloud-config'); }, 1000);
          return;
        }
        document.getElementById('dlg_qr_hint').textContent = '✅ 登录成功！';
        document.getElementById('dlg_qr_status').innerHTML = '<span style="color:var(--success);font-size:14px">✅ 扫码成功！已自动填入</span>';
        document.getElementById('dlg_cookie').value = __qrCookie;
        document.getElementById('dlg_qr_btn').style.display = 'none';
        cancelQRPoll();
      }else if(d.status==='expired'){
        cancelQRPoll();
        setTimeout(function(){ doStartQR(); }, 500);
      }else{
        pollQR();
      }
    }).catch(function(){ pollQR(); });
  }, 3000);
}

function cancelQRPoll(){
  if(__qrTimer){ clearTimeout(__qrTimer); __qrTimer = null; }
  if(__qrSession){ api('/api/admin/'+__qrType+'/qr-login/'+__qrSession+'/cancel', {method:'POST'}).catch(function(){}); __qrSession=''; }
}
