document.addEventListener('DOMContentLoaded', async () => {
  const stored = await browser.storage.local.get(['apiUrl', 'apiKey']);
  document.getElementById('api-url').value = stored.apiUrl || '';
  document.getElementById('api-key').value = stored.apiKey || '';

  document.getElementById('save-btn').addEventListener('click', save);
  document.getElementById('test-btn').addEventListener('click', test);
});

async function save() {
  const apiUrl = document.getElementById('api-url').value.trim().replace(/\/+$/, '');
  const apiKey = document.getElementById('api-key').value.trim();
  if (!apiUrl || !apiKey) {
    showStatus('Both fields are required.', 'err');
    return;
  }
  await browser.storage.local.set({ apiUrl, apiKey });
  await browser.storage.local.remove(['lastConnectionTest', 'lastConnectionStatus']);
  showStatus('Saved.', 'ok');
}

async function test() {
  const apiUrl = document.getElementById('api-url').value.trim().replace(/\/+$/, '');
  const apiKey = document.getElementById('api-key').value.trim();
  if (!apiUrl || !apiKey) {
    showStatus('Fill both fields first.', 'err');
    return;
  }
  try {
    const r = await fetch(`${apiUrl}/credentials`, {
      method: 'GET',
      headers: { 'X-Extension-Key': apiKey },
    });
    if (r.ok) showStatus(`Connected — HTTP ${r.status}.`, 'ok');
    else showStatus(`HTTP ${r.status}: ${r.statusText}`, 'err');
  } catch (e) {
    showStatus(`Cannot reach ${apiUrl}: ${e.message}`, 'err');
  }
}

function showStatus(text, kind) {
  const el = document.getElementById('status');
  el.textContent = text;
  el.className = `status ${kind}`;
  el.style.display = 'block';
}
