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 = normalizeApiUrl(document.getElementById('api-url').value);
  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']);
  // Show what was actually stored — the operator may have typed the instance
  // root and it was normalized to the API root.
  document.getElementById('api-url').value = apiUrl;
  showStatus(`Saved — using ${apiUrl}`, 'ok');
}

async function test() {
  const apiUrl = normalizeApiUrl(document.getElementById('api-url').value);
  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(`HTTP ${r.status}: ${r.statusText}`, 'err');
      return;
    }
    // A 200 is NOT sufficient. If the URL resolves to the Vue SPA instead of
    // the JSON API, the catch-all route returns 200 with an HTML document —
    // which used to report "Connected" on a config that could not POST at all.
    const contentType = r.headers.get('content-type') || '';
    if (!contentType.includes('json')) {
      showStatus(
        `${apiUrl} answered with ${contentType || 'no content-type'}, not JSON `
          + '— that looks like the FC web UI rather than its API.',
        'err',
      );
      return;
    }
    showStatus(`Connected to ${apiUrl} — HTTP ${r.status}.`, 'ok');
  } 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';
}
