// panes/api.js — interactive request explorer.
import { registerPane } from '../app.js';
import { jraw } from '../lib/api.js';
import { fmtJSON } from '../lib/ui.js';

const TPL = `
  <div class="pane-head">
    <div><div class="title">API Explorer</div><div class="sub">Hit any backend route.</div></div>
  </div>
  <div class="card">
    <div class="flex gap-2 mb-3">
      <select class="input" id="ax-method" style="max-width:120px">
        <option>GET</option><option>POST</option><option>PUT</option><option>PATCH</option><option>DELETE</option>
      </select>
      <input class="input" id="ax-path" value="/api/health" placeholder="/api/…"/>
      <button class="btn btn-primary" id="ax-send">Send</button>
      <button class="btn btn-ghost" id="ax-clear">Clear</button>
    </div>
    <label class="field mb-3"><span class="lbl">Body (JSON or text)</span><textarea class="input" id="ax-body" rows="5"></textarea></label>
    <div class="card-title"><h2>Response</h2><span class="muted mono" id="ax-status">—</span></div>
    <pre id="ax-out" class="muted">no request yet</pre>
  </div>
`;

registerPane('api', {
  label: 'API Explorer',
  init(host) {
    host.innerHTML = TPL;
    host.querySelector('#ax-send').addEventListener('click', async () => {
      const m = host.querySelector('#ax-method').value;
      const p = host.querySelector('#ax-path').value;
      const b = host.querySelector('#ax-body').value.trim();
      const t0 = performance.now();
      try {
        const r = await jraw(m, p, m === 'GET' ? '' : b);
        const dt = Math.round(performance.now() - t0);
        host.querySelector('#ax-status').textContent = `${r.status} · ${dt}ms · ${r.raw.length}b`;
        host.querySelector('#ax-out').textContent = typeof r.body === 'string' ? r.body : fmtJSON(r.body);
      } catch (e) {
        host.querySelector('#ax-status').textContent = 'error';
        host.querySelector('#ax-out').textContent = e.message;
      }
    });
    host.querySelector('#ax-clear').addEventListener('click', () => {
      host.querySelector('#ax-out').textContent = '';
      host.querySelector('#ax-status').textContent = '—';
    });
  },
});
