import { api } from '/static/js/api.js';
import { subscribe, onPollFallback } from '/static/js/ws.js';

const host = document.getElementById('review-list');
const errorBox = document.getElementById('error');
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({
  '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
}[c]));

async function load() {
  try {
    const res = await api('GET', '/api/v1/consultant/reviews');
    host.replaceChildren(...res.tasks.map((t) => {
      const card = document.createElement('div');
      card.className = 'card';
      const who = t.assignee
        ? (t.assignee.kind === 'ai' ? 'AI work performer' : 'developer')
        : 'unknown';
      card.innerHTML = `
        <div class="spread">
          <h3><a href="/tasks/${t.id}">${esc(t.title)}</a></h3>
          <span class="badge accent">◈ ${t.bounty}</span>
        </div>
        <p class="muted">submitted by ${who} · updated ${new Date(t.updatedAt).toLocaleString()}</p>
        <a class="btn primary" href="/tasks/${t.id}">Open review</a>`;
      return card;
    }));
    if (!res.tasks.length) {
      host.innerHTML = '<p class="muted">Nothing waiting for review.</p>';
    }
  } catch (e) { errorBox.textContent = e.message; }
}

subscribe('board', () => setTimeout(load, 300));
onPollFallback(load);
load();
