initLocale().then(function () {
  setActiveNav('tools');
  const nav = document.querySelector('.nav');
  if (nav) {
    nav.innerHTML = chromeNav('tools');
  }
  document.getElementById('btnLogout').addEventListener('click', logout);

  loadMe().then(me => {
    if (me?.organizationName)
      document.getElementById('orgName').textContent = me.organizationName;
    if (me?.license) renderLicenseBanner(me.license);
    if (me?.role) applyRoleNav(me.role);
  }).catch(() => {});
});

async function run(btn, url, body, outEl) {
  btn.disabled = true;
  outEl.textContent = '…';
  try {
    const res = await api(url, { method: 'POST', body: JSON.stringify(body) });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error(data.error || ('HTTP ' + res.status));
    outEl.textContent = JSON.stringify(data, null, 2);
  } catch (e) {
    outEl.textContent = e.message;
  } finally {
    btn.disabled = false;
  }
}

document.getElementById('btnPing').addEventListener('click', () => run(
  document.getElementById('btnPing'),
  '/api/tools/ping',
  { host: document.getElementById('pingHost').value, count: Number(document.getElementById('pingCount').value) || 4 },
  document.getElementById('pingOut')
));

document.getElementById('btnDns').addEventListener('click', () => run(
  document.getElementById('btnDns'),
  '/api/tools/dns',
  { host: document.getElementById('dnsHost').value },
  document.getElementById('dnsOut')
));

document.getElementById('btnPort').addEventListener('click', () => run(
  document.getElementById('btnPort'),
  '/api/tools/port',
  { host: document.getElementById('portHost').value, port: Number(document.getElementById('portPort').value) },
  document.getElementById('portOut')
));
