// ═══════════════════════════════════════════════════════
//  CVC Dashboard — Hive Mind Module
//  (Compiled from ts/hive.ts — edit TypeScript source)
// ═══════════════════════════════════════════════════════
"use strict";

var CATEGORY_COLORS = {
  insight:    'tag-purple',
  decision:   'tag-cyan',
  warning:    'tag-pink',
  discovery:  'tag-yellow',
  pattern:    'tag-blue',
  preference: 'tag-green',
};

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

function categoryTag(cat) {
  var cls = CATEGORY_COLORS[cat] || '';
  return '<span class="tag tag-sm ' + cls + '">' + _escHive(cat) + '</span>';
}

// ── Write form ──────────────────────────────────────
function setupHiveWriter() {
  document.getElementById('hive-write-btn')?.addEventListener('click', async function () {
    var contentEl = document.getElementById('hive-write-content');
    var catEl     = document.getElementById('hive-write-category');
    var agentEl   = document.getElementById('hive-write-agent');

    var content = contentEl?.value.trim();
    if (!content) { toast('Write some content first', 'error'); return; }

    var category  = catEl?.value || 'insight';
    var agent_id  = agentEl?.value.trim() || 'dashboard-user';

    this.disabled = true;
    try {
      await CvcApi.writeHiveMemory(agent_id, content, category, []);
      toast('Memory written to the hive ✓', 'success');
      contentEl.value = '';
      loadHiveData();
    } catch (e) {
      toast(e.message, 'error');
    } finally {
      this.disabled = false;
    }
  });
}

// ── Filters ─────────────────────────────────────────
var _hiveCategoryFilter = '';
function setupHiveFilters() {
  document.getElementById('hive-filter-btn')?.addEventListener('click', function () {
    loadHiveFeed();
  });

  document.getElementById('hive-compact-btn')?.addEventListener('click', async function () {
    try {
      var result = await CvcApi.compactHiveMemory();
      toast(result.message || 'Hive memory compacted', 'success');
      loadHiveData();
    } catch (e) { toast(e.message, 'error'); }
  });
}

// ── Feed rendering ──────────────────────────────────
function renderHiveEntry(entry) {
  var tags = (entry.tags || []).map(function (t) { return '<span class="tag tag-sm">' + _escHive(t) + '</span>'; }).join(' ');
  var time = typeof formatDate === 'function' ? formatDate(entry.timestamp) : entry.timestamp;
  return '<div class="hive-entry">' +
    '<div class="hive-entry-header">' +
      '<span class="hive-entry-agent">🤖 ' + _escHive(entry.agent_id || 'unknown') + '</span> ' +
      categoryTag(entry.category || 'general') +
      ' <span class="hive-entry-time">' + _escHive(time) + '</span>' +
    '</div>' +
    '<div class="hive-entry-content">' + _escHive(entry.content) + '</div>' +
    (tags ? '<div class="hive-entry-tags">' + tags + '</div>' : '') +
    (entry.commit_hash ? '<div class="hive-entry-hash"><code>' + _escHive(entry.commit_hash.slice(0, 8)) + '</code></div>' : '') +
  '</div>';
}

async function loadHiveFeed() {
  var el = document.getElementById('hive-memory-feed');
  if (!el) return;
  try {
    var category = document.getElementById('hive-filter-category')?.value || undefined;
    var agentId  = document.getElementById('hive-filter-agent')?.value.trim() || undefined;
    var query    = document.getElementById('hive-filter-query')?.value.trim() || undefined;
    var data = await CvcApi.getHiveMemory(query || null, category || null, agentId || null, 50);
    var entries = data.entries || [];
    if (!entries.length) {
      el.innerHTML = '<p class="text-muted">No hive memory entries yet. Write something to the hive above!</p>';
      return;
    }
    el.innerHTML = entries.map(renderHiveEntry).join('');
  } catch {
    el.innerHTML = '<p class="text-muted">Failed to load hive memory feed.</p>';
  }
}

// ── Stats ───────────────────────────────────────────
async function loadHiveStats() {
  try {
    var stats = await CvcApi.getHiveMemoryStats();
    var setText = function (id, v) {
      var e = document.getElementById(id);
      if (e) e.textContent = String(v);
    };
    setText('hive-mem-total', stats.total_entries || 0);
    setText('hive-mem-agents', stats.agent_count || 0);
    setText('hive-mem-categories', Object.keys(stats.categories || {}).length);
  } catch {
    // silently fail — stats are decorative
  }
}

// ── Summary ─────────────────────────────────────────
async function loadHiveSummary() {
  var el = document.getElementById('hive-summary-context');
  if (!el) return;
  try {
    var data = await CvcApi.getHiveMemorySummary();
    var text = data.context || '';
    if (text) {
      el.innerHTML = '<pre class="hive-summary-pre">' + _escHive(text) + '</pre>';
    } else {
      el.innerHTML = '<p class="text-muted">No summary available yet.</p>';
    }
  } catch {
    el.innerHTML = '<p class="text-muted">Summary unavailable.</p>';
  }
}

// ── Main loader ─────────────────────────────────────
async function loadHiveData() {
  await Promise.all([
    loadHiveFeed(),
    loadHiveStats(),
    loadHiveSummary(),
  ]);
}

// ── Init ────────────────────────────────────────────
function initHive() {
  setupHiveWriter();
  setupHiveFilters();
}
