// ═══════════════════════════════════════════════════════
//  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.querySelectorAll('.hive-filter-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      document.querySelectorAll('.hive-filter-btn').forEach(function (b) { b.classList.remove('active'); });
      btn.classList.add('active');
      _hiveCategoryFilter = btn.dataset.cat || '';
      loadHiveFeed();
    });
  });
}

// ── Feed rendering ──────────────────────────────────
function renderHiveEntry(entry) {
  var time = typeof formatDate === 'function' ? formatDate(entry.timestamp) : entry.timestamp;
  return '<div class="hive-entry">' +
    '<div class="hive-entry-header">' +
      categoryTag(entry.category || 'insight') +
      ' <span class="hive-agent">' + _escHive(entry.agent_id || 'unknown') + '</span>' +
      ' <span class="hive-time">' + _escHive(time) + '</span>' +
    '</div>' +
    '<div class="hive-entry-content">' + _escHive(entry.content) + '</div>' +
  '</div>';
}

async function loadHiveFeed() {
  var el = document.getElementById('hive-feed');
  if (!el) return;
  try {
    var data = await CvcApi.getHiveMemory(null, _hiveCategoryFilter || null, null, 50);
    var entries = data.entries || [];
    if (!entries.length) {
      el.innerHTML = '<p class="text-muted">The hive is quiet… no shared memories yet.</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-total-memories', stats.total_entries || 0);
    setText('hive-active-agents', stats.unique_agents || 0);
    setText('hive-categories-count', stats.categories_count || 0);
  } catch {
    // silently fail — stats are decorative
  }
}

// ── Summary ─────────────────────────────────────────
async function loadHiveSummary() {
  var el = document.getElementById('hive-summary-text');
  if (!el) return;
  try {
    var data = await CvcApi.getHiveMemorySummary();
    el.textContent = data.summary || 'No summary available.';
  } catch {
    el.textContent = 'Summary unavailable.';
  }
}

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

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