/* ═══════════════════════════════════════════════════════════════════
   Credentials Management
   ═══════════════════════════════════════════════════════════════════ */
document.getElementById('btn-credentials').addEventListener('click', () => {
  if (!currentProject) return;
  credentialsPanelOpen = !credentialsPanelOpen;
  const panel = document.getElementById('credentials-panel');
  panel.classList.toggle('open', credentialsPanelOpen);
  if (credentialsPanelOpen) loadCredentials();
});

function closeCredentials() {
  credentialsPanelOpen = false;
  document.getElementById('credentials-panel').classList.remove('open');
}

async function loadCredentials() {
  if (!currentProject) return;
  const list = document.getElementById('cred-list');
  list.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted);font-size:12px">加载中...</div>';
  try {
    const creds = await apiFetch(API + '/projects/' + currentProject + '/credentials');
    if (!creds || creds.length === 0) {
      list.innerHTML = '<div class="cred-empty"><div class="cred-empty-icon">🔑</div><div class="cred-empty-title">暂无凭据</div><div>点击上方按钮添加</div></div>';
      return;
    }
    list.innerHTML = creds.map(c => renderCredCard(c)).join('');
  } catch (e) {
    list.innerHTML = '<div class="cred-empty"><div>加载失败</div></div>';
  }
}

function renderCredCard(c) {
  const typeLabels = { password: '密码', api_key: 'API Key', token: 'Token', hash: 'Hash', key: '密钥', other: '其他' };
  const statusLabels = { active: '有效', expired: '过期', unknown: '未知' };
  const badgeCls = ['password','api_key','token','hash','key'].includes(c.cred_type) ? c.cred_type : 'other';
  const masked = '••••••••';
  const meta = [];
  if (c.username) meta.push('👤 ' + escHtml(c.username));
  if (c.created_at) meta.push('🕐 ' + formatDate(c.created_at));
  return '<div class="cred-card" data-cred-id="' + c.id + '">' +
    '<div class="cred-card-header">' +
      '<span class="cred-card-label">' + escHtml(c.label) + '</span>' +
      '<span class="cred-badge ' + badgeCls + '">' + escHtml(typeLabels[c.cred_type] || c.cred_type) + '</span>' +
      '<span class="cred-status-badge ' + (c.status || 'unknown') + '">' + escHtml(statusLabels[c.status] || c.status || '未知') + '</span>' +
    '</div>' +
    '<div class="cred-secret-row">' +
      '<span class="cred-secret" data-revealed="false">' + masked + '</span>' +
      '<button class="cred-eye-btn" onclick="toggleCredSecret(this,\'' + escHtml(c.secret || '') + '\')">👁</button>' +
    '</div>' +
    (meta.length ? '<div class="cred-card-meta">' + meta.join(' · ') + '</div>' : '') +
    (c.note ? '<div style="font-size:11px;color:var(--text-muted);margin-top:6px">' + escHtml(c.note) + '</div>' : '') +
    '<div class="cred-card-actions">' +
      '<button onclick="editCredential(\'' + c.id + '\')">编辑</button>' +
      '<button class="cred-delete-btn" onclick="deleteCredential(\'' + c.id + '\')">删除</button>' +
    '</div>' +
  '</div>';
}

function toggleCredSecret(btn, secret) {
  const span = btn.previousElementSibling;
  const revealed = span.getAttribute('data-revealed') === 'true';
  if (revealed) {
    span.textContent = '••••••••';
    span.setAttribute('data-revealed', 'false');
    btn.textContent = '👁';
  } else {
    span.textContent = secret;
    span.setAttribute('data-revealed', 'true');
    btn.textContent = '🔒';
  }
}

function showCredForm(cred) {
  const form = document.getElementById('cred-form');
  form.style.display = 'block';
  document.getElementById('btn-new-cred').style.display = 'none';
  if (cred) {
    document.getElementById('cred-form-title').textContent = '编辑凭据';
    document.getElementById('cred-label').value = cred.label || '';
    document.getElementById('cred-type').value = cred.cred_type || 'password';
    document.getElementById('cred-username').value = cred.username || '';
    document.getElementById('cred-secret').value = cred.secret || '';
    document.getElementById('cred-status').value = cred.status || 'unknown';
    document.getElementById('cred-note').value = cred.note || '';
    document.getElementById('cred-edit-id').value = cred.id || '';
  } else {
    document.getElementById('cred-form-title').textContent = '新增凭据';
    document.getElementById('cred-label').value = '';
    document.getElementById('cred-type').value = 'password';
    document.getElementById('cred-username').value = '';
    document.getElementById('cred-secret').value = '';
    document.getElementById('cred-status').value = 'active';
    document.getElementById('cred-note').value = '';
    document.getElementById('cred-edit-id').value = '';
  }
}

function cancelCredForm() {
  document.getElementById('cred-form').style.display = 'none';
  document.getElementById('btn-new-cred').style.display = '';
}

async function saveCredential() {
  if (!currentProject) return;
  const label = document.getElementById('cred-label').value.trim();
  if (!label) { toast('标签不能为空'); return; }
  const body = {
    label: label,
    cred_type: document.getElementById('cred-type').value,
    username: document.getElementById('cred-username').value.trim(),
    secret: document.getElementById('cred-secret').value,
    status: document.getElementById('cred-status').value,
    note: document.getElementById('cred-note').value.trim(),
  };
  const editId = document.getElementById('cred-edit-id').value;
  try {
    if (editId) {
      await apiFetch(API + '/projects/' + currentProject + '/credentials/' + editId, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      });
      toast('凭据已更新');
    } else {
      await apiFetch(API + '/projects/' + currentProject + '/credentials', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      });
      toast('凭据已创建');
    }
    cancelCredForm();
    loadCredentials();
  } catch (e) { /* already toasted */ }
}

async function editCredential(id) {
  if (!currentProject) return;
  try {
    const creds = await apiFetch(API + '/projects/' + currentProject + '/credentials');
    const cred = (creds || []).find(c => c.id === id);
    if (cred) showCredForm(cred);
  } catch (e) { /* already toasted */ }
}

async function deleteCredential(id) {
  if (!currentProject) return;
  if (!confirm('确定删除此凭据？')) return;
  try {
    await apiFetch(API + '/projects/' + currentProject + '/credentials/' + id, { method: 'DELETE' });
    toast('凭据已删除');
    loadCredentials();
  } catch (e) { /* already toasted */ }
}
