// ═══════════════════════════════════════════════════════
//  CVC Dashboard — Agent Creator Module
//  (Compiled from ts/agents.ts — edit TypeScript source)
// ═══════════════════════════════════════════════════════
"use strict";

function _escAgents(s) {
  const d = document.createElement('div');
  d.textContent = s;
  return d.innerHTML;
}

// ── Sub-tab switching ───────────────────────────────
function setupSdkSubtabs() {
  document.querySelectorAll('.sdk-subtab').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.sdk-subtab').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      const target = btn.dataset.subtab;
      document.querySelectorAll('.sdk-subtab-content').forEach(el => el.classList.add('hidden'));
      document.getElementById(`subtab-${target}`)?.classList.remove('hidden');
    });
  });
}

// ── Creator mode switching ──────────────────────────
function setupCreatorModes() {
  document.querySelectorAll('.creator-mode-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.creator-mode-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      const mode = btn.dataset.mode;
      document.querySelectorAll('.creator-panel').forEach(el => el.classList.add('hidden'));
      document.getElementById(`creator-${mode}`)?.classList.remove('hidden');
    });
  });
}

// ── Prefill manual form ─────────────────────────────
function prefillManualForm(t) {
  _setAgentVal('agent-man-id', t.id || '');
  _setAgentVal('agent-man-name', t.name || '');
  _setAgentVal('agent-man-desc', t.description || '');
  _setAgentVal('agent-man-tier', t.tool_tier || 'standard');
  _setAgentVal('agent-man-rank', t.rank || 'private');
  _setAgentVal('agent-man-squad', t.squad || 'alpha');
  _setAgentVal('agent-man-prompt', t.system_prompt || '');
  _setAgentVal('agent-man-model', t.model_override || '');
  _setAgentVal('agent-man-provider', t.provider_override || '');
  const autoShare = document.getElementById('agent-man-auto-share');
  if (autoShare) autoShare.checked = t.auto_share_to_hive || false;
  const autoRespond = document.getElementById('agent-man-auto-respond');
  if (autoRespond) autoRespond.checked = t.auto_respond || false;
}

function _setAgentVal(id, value) {
  const el = document.getElementById(id);
  if (el) el.value = value;
}

// ── Create from prompt ──────────────────────────────
function setupPromptCreator() {
  document.getElementById('create-from-prompt-btn')?.addEventListener('click', async () => {
    const input = document.getElementById('agent-prompt-input');
    const prompt = input?.value.trim();
    if (!prompt) { toast('Please describe what you want the agent to do', 'error'); return; }

    const btn = document.getElementById('create-from-prompt-btn');
    const resultDiv = document.getElementById('agent-prompt-result');
    btn.disabled = true;
    btn.textContent = '⏳ Generating…';
    resultDiv.style.display = 'none';

    try {
      const result = await CvcApi.createAgentFromPrompt(prompt);
      const t = result.template;
      resultDiv.style.display = '';
      resultDiv.innerHTML = `
        <div class="agent-preview-card">
          <h4>${_escAgents(t.name)} <span class="tag tag-blue">${_escAgents(t.tool_tier)}</span> <span class="tag tag-green">${_escAgents(t.rank)}</span></h4>
          <p>${_escAgents(t.description)}</p>
          <div class="preview-details">
            <div><strong>ID:</strong> <code>${_escAgents(t.id)}</code></div>
            <div><strong>Squad:</strong> ${_escAgents(t.squad)}</div>
            <div><strong>Capabilities:</strong> ${(t.capabilities || []).map(c => `<span class="tag">${_escAgents(c)}</span>`).join(' ')}</div>
          </div>
          <div class="preview-prompt" style="margin-top:0.5rem">
            <strong>System Prompt:</strong>
            <pre style="white-space:pre-wrap;font-size:0.8em;max-height:200px;overflow:auto">${_escAgents(t.system_prompt)}</pre>
          </div>
          <div class="preview-actions" style="margin-top:0.75rem">
            <button class="btn btn-accent btn-sm" id="confirm-prompt-agent">✓ Register This Agent</button>
            <button class="btn btn-sm" id="edit-prompt-agent">✏️ Edit First</button>
          </div>
        </div>
      `;
      document.getElementById('confirm-prompt-agent')?.addEventListener('click', async () => {
        try {
          await CvcApi.createAgent(t);
          toast(`Agent "${t.name}" created and registered!`, 'success');
          resultDiv.style.display = 'none';
          input.value = '';
          loadAgentsData();
        } catch (e) { toast(e.message, 'error'); }
      });
      document.getElementById('edit-prompt-agent')?.addEventListener('click', () => {
        prefillManualForm(t);
        document.querySelectorAll('.creator-mode-btn').forEach(b => b.classList.remove('active'));
        document.querySelector('.creator-mode-btn[data-mode="manual"]')?.classList.add('active');
        document.querySelectorAll('.creator-panel').forEach(el => el.classList.add('hidden'));
        document.getElementById('creator-manual')?.classList.remove('hidden');
      });
    } catch (e) {
      toast(e.message, 'error');
    } finally {
      btn.disabled = false;
      btn.textContent = '🪄 Generate Agent';
    }
  });
}

// ── Manual creation ─────────────────────────────────
function setupManualCreator() {
  document.getElementById('create-manual-btn')?.addEventListener('click', async () => {
    const id = document.getElementById('agent-man-id')?.value.trim();
    if (!id) { toast('Agent ID is required', 'error'); return; }

    const template = {
      id,
      name: document.getElementById('agent-man-name')?.value.trim() || id,
      description: document.getElementById('agent-man-desc')?.value.trim(),
      system_prompt: document.getElementById('agent-man-prompt')?.value.trim(),
      tool_tier: document.getElementById('agent-man-tier')?.value || 'standard',
      rank: document.getElementById('agent-man-rank')?.value || 'private',
      squad: document.getElementById('agent-man-squad')?.value.trim() || 'alpha',
      model_override: document.getElementById('agent-man-model')?.value.trim() || '',
      provider_override: document.getElementById('agent-man-provider')?.value.trim() || '',
      auto_share_to_hive: document.getElementById('agent-man-auto-share')?.checked || false,
      auto_respond: document.getElementById('agent-man-auto-respond')?.checked || false,
    };

    try {
      await CvcApi.createAgent(template);
      toast(`Agent "${template.name}" created!`, 'success');
      loadAgentsData();
    } catch (e) { toast(e.message, 'error'); }
  });
}

// ── Builtin templates ───────────────────────────────
async function loadBuiltinTemplates() {
  const grid = document.getElementById('builtin-templates-grid');
  if (!grid) return;
  try {
    const builtins = await CvcApi.getBuiltinAgents();
    if (!builtins.length) {
      grid.innerHTML = '<p class="text-muted">No built-in templates available.</p>';
      return;
    }
    grid.innerHTML = builtins.map(t => `
      <div class="template-card" data-template-id="${_escAgents(t.id)}">
        <div class="template-name">${_escAgents(t.name)}</div>
        <div class="template-desc">${_escAgents(t.description)}</div>
        <div class="template-meta">
          <span class="tag tag-blue">${_escAgents(t.tool_tier)}</span>
          <span class="tag tag-green">${_escAgents(t.rank)}</span>
          <span class="tag">${_escAgents(t.squad)}</span>
        </div>
        <button class="btn btn-sm btn-accent" onclick="useTemplateUI('${_escAgents(t.id)}')">Use Template</button>
      </div>
    `).join('');
  } catch {
    grid.innerHTML = '<p class="text-muted">Failed to load templates.</p>';
  }
}

function useTemplateUI(id) {
  CvcApi.getAgentDetail(id).then(t => {
    prefillManualForm(t);
    document.querySelectorAll('.creator-mode-btn').forEach(b => b.classList.remove('active'));
    document.querySelector('.creator-mode-btn[data-mode="manual"]')?.classList.add('active');
    document.querySelectorAll('.creator-panel').forEach(el => el.classList.add('hidden'));
    document.getElementById('creator-manual')?.classList.remove('hidden');
    toast(`Template "${t.name}" loaded`, 'info');
  }).catch(e => toast(e.message, 'error'));
}
window.useTemplateUI = useTemplateUI;

// ── Agents table ────────────────────────────────────
async function loadAgentsTable() {
  const el = document.getElementById('sdk-agents-table');
  if (!el) return;
  try {
    const agents = await CvcApi.getHiveMindAgents().catch(() => []);
    const list = Array.isArray(agents) ? agents : (agents.agents || []);
    const setText = (id, v) => { const e = document.getElementById(id); if (e) e.textContent = String(v); };
    setText('hive-agents-count', list.length);

    if (!list.length) {
      el.innerHTML = '<p class="text-muted">No agents registered.</p>';
      return;
    }
    el.innerHTML = `<table class="data-table"><thead><tr><th>ID</th><th>Name</th><th>Role</th><th>Rank</th><th>Squad</th><th>Actions</th></tr></thead><tbody>` +
      list.map(a =>
        `<tr>
          <td><code>${_escAgents(a.agent_id)}</code></td>
          <td>${_escAgents(a.name || '—')}</td>
          <td>${_escAgents(a.role || '—')}</td>
          <td><span class="tag">${_escAgents(a.rank || 'private')}</span></td>
          <td><span class="tag tag-blue">${_escAgents(a.squad || '—')}</span></td>
          <td><button class="btn btn-sm btn-red" onclick="removeAgent('${_escAgents(a.agent_id)}')">Remove</button></td>
        </tr>`
      ).join('') + '</tbody></table>';
  } catch {
    el.innerHTML = '<p class="text-muted">Failed to load agents.</p>';
  }
}

// ── Templates list ──────────────────────────────────
async function loadTemplatesList() {
  const el = document.getElementById('agent-templates-list');
  if (!el) return;
  try {
    const data = await CvcApi.listAgents();
    const templates = [...(data.templates || []), ...(data.builtins || [])];
    const setText = (id, v) => { const e = document.getElementById(id); if (e) e.textContent = String(v); };
    setText('hive-templates-count', templates.length);

    if (!templates.length) {
      el.innerHTML = '<p class="text-muted">No agent templates available.</p>';
      return;
    }
    el.innerHTML = `<table class="data-table"><thead><tr><th>Name</th><th>Tier</th><th>Rank</th><th>Squad</th><th>Source</th><th>Actions</th></tr></thead><tbody>` +
      templates.map(t =>
        `<tr>
          <td><strong>${_escAgents(t.name)}</strong><br><span class="text-muted">${_escAgents((t.description || '').slice(0, 60))}</span></td>
          <td><span class="tag tag-blue">${_escAgents(t.tool_tier || '—')}</span></td>
          <td><span class="tag">${_escAgents(t.rank || '—')}</span></td>
          <td>${_escAgents(t.squad || '—')}</td>
          <td>${t.is_builtin ? '<span class="tag tag-green">built-in</span>' : `<span class="tag">${_escAgents(t.source || 'custom')}</span>`}</td>
          <td>${!t.is_builtin ? `<button class="btn btn-sm btn-red" onclick="deleteAgentTemplateUI('${_escAgents(t.id)}')">Delete</button>` : `<button class="btn btn-sm btn-accent" onclick="useTemplateUI('${_escAgents(t.id)}')">Use</button>`}</td>
        </tr>`
      ).join('') + '</tbody></table>';
  } catch {
    el.innerHTML = '<p class="text-muted">Failed to load templates.</p>';
  }
}

function deleteAgentTemplateUI(id) {
  CvcApi.deleteAgent(id)
    .then(() => { toast('Agent template deleted', 'success'); loadAgentsData(); })
    .catch(e => toast(e.message, 'error'));
}
window.deleteAgentTemplateUI = deleteAgentTemplateUI;

// ── Squads ──────────────────────────────────────────
async function loadSquadsData() {
  const el = document.getElementById('squads-list');
  if (!el) return;
  try {
    const squads = await CvcApi.listSquads();
    if (!squads.length) {
      el.innerHTML = '<p class="text-muted">No squads configured.</p>';
      return;
    }
    el.innerHTML = squads.map(s => `
      <div class="squad-card">
        <h4>${_escAgents(s.name)}</h4>
        <div class="squad-meta">
          <span class="tag tag-blue">${s.agent_count} agent${s.agent_count !== 1 ? 's' : ''}</span>
          <span class="text-muted">Branch: ${_escAgents(s.branch)}</span>
        </div>
        <div class="squad-agents">
          ${s.agents.map(a => `<span class="tag">${_escAgents(a.agent_id || a.id || a)}</span>`).join(' ')}
        </div>
      </div>
    `).join('');
  } catch {
    el.innerHTML = '<p class="text-muted">Failed to load squads.</p>';
  }
}

function setupSquadCreator() {
  document.getElementById('create-squad-btn')?.addEventListener('click', () => {
    const card = document.getElementById('create-squad-card');
    if (card) card.style.display = card.style.display === 'none' ? '' : 'none';
  });

  document.getElementById('squad-submit-btn')?.addEventListener('click', async () => {
    const name = document.getElementById('squad-name-input')?.value.trim();
    const agentsStr = document.getElementById('squad-agents-input')?.value.trim();
    if (!name) { toast('Squad name required', 'error'); return; }
    const agents = agentsStr.split(',').map(s => s.trim()).filter(Boolean);
    try {
      await CvcApi.createSquad(name, agents);
      toast(`Squad "${name}" created`, 'success');
      const card = document.getElementById('create-squad-card');
      if (card) card.style.display = 'none';
      loadSquadsData();
    } catch (e) { toast(e.message, 'error'); }
  });
}

// ── Main loader ─────────────────────────────────────
async function loadAgentsData() {
  await Promise.all([
    loadAgentsTable(),
    loadTemplatesList(),
    loadBuiltinTemplates(),
    loadSquadsData(),
  ]);
}

// ── Init ────────────────────────────────────────────
function initAgents() {
  setupSdkSubtabs();
  setupCreatorModes();
  setupPromptCreator();
  setupManualCreator();
  setupSquadCreator();
}
