  // ── Pinned context (create / view / edit / unpin) ──────────────
  // Slim front-end over the same endpoints the classic dashboard uses:
  //   GET (via /api/status `pinned`), POST /api/pinned (create),
  //   POST /api/pinned/update (edit), POST /api/pinned/remove (unpin).
  // The "Pin Content" action button and the "Pinned context" status tile
  // both surface this. Editing reuses the atomic update endpoint.

  // When non-null, the editor is editing the entry with this (original) title;
  // null means it is creating a new pin.
  var _pinEditOriginal = null;

  function slimPinnedEntries() {
    return (lastStatusData && Array.isArray(lastStatusData.pinned)) ? lastStatusData.pinned : [];
  }

  function pinLevelChipClass(level) {
    return level === 'critical' ? 'red' : level === 'warning' ? 'amber' : 'blue';
  }

  // ── Editor (create + edit) ───────────────────────────────────────
  function openSlimPinEditor(entry) {
    _pinEditOriginal = entry ? entry.title : null;
    var modal = document.getElementById('slim-pin-edit-modal');
    if (!modal) return;
    document.getElementById('slim-pin-edit-heading').textContent = entry ? 'Edit pinned content' : 'Pin content';
    document.getElementById('slim-pin-title').value = entry ? (entry.title || '') : '';
    document.getElementById('slim-pin-content').value = entry ? (entry.content || '') : '';
    document.getElementById('slim-pin-level').value = (entry && entry.level) ? entry.level : 'info';
    var msg = document.getElementById('slim-pin-msg');
    if (msg) { msg.textContent = ''; msg.style.color = 'var(--muted)'; }
    var submit = document.getElementById('slim-pin-submit');
    if (submit) { submit.disabled = false; submit.textContent = entry ? 'Save' : 'Pin'; }
    modal.classList.add('open');
    setTimeout(function() { var t = document.getElementById('slim-pin-title'); if (t) t.focus(); }, 40);
  }
  function closeSlimPinEditor() {
    var modal = document.getElementById('slim-pin-edit-modal');
    if (modal) modal.classList.remove('open');
  }

  async function submitSlimPin() {
    var title = (document.getElementById('slim-pin-title').value || '').trim();
    var content = document.getElementById('slim-pin-content').value;
    var level = document.getElementById('slim-pin-level').value;
    var msg = document.getElementById('slim-pin-msg');
    var submit = document.getElementById('slim-pin-submit');
    if (!title || !content.trim()) {
      if (msg) { msg.style.color = 'var(--red)'; msg.textContent = 'Title and content are required.'; }
      return;
    }
    var editing = _pinEditOriginal != null;
    if (submit) { submit.disabled = true; submit.textContent = editing ? 'Saving…' : 'Pinning…'; }
    try {
      var res;
      if (editing) {
        res = await fetch('/api/pinned/update', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ originalTitle: _pinEditOriginal, title: title, content: content, level: level }),
        });
      } else {
        res = await fetch('/api/pinned', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ title: title, content: content, level: level }),
        });
      }
      var d = await res.json().catch(function() { return {}; });
      if (!res.ok) throw new Error(d.error || ('HTTP ' + res.status));
      closeSlimPinEditor();
      scheduleStatusRefresh(400);           // refresh the Pinned-context tile
      // If the list modal is open, re-render it once the snapshot catches up.
      setTimeout(function() {
        var listModal = document.getElementById('slim-pinned-modal');
        if (listModal && listModal.classList.contains('open')) renderSlimPinnedList();
      }, 700);
    } catch (e) {
      if (msg) { msg.style.color = 'var(--red)'; msg.textContent = 'Error: ' + (e && e.message ? e.message : 'failed'); }
      if (submit) { submit.disabled = false; submit.textContent = editing ? 'Save' : 'Pin'; }
    }
  }

  // ── List / view / unpin ──────────────────────────────────────────
  function openSlimPinnedList() {
    var modal = document.getElementById('slim-pinned-modal');
    if (!modal) return;
    renderSlimPinnedList();
    modal.classList.add('open');
  }
  function closeSlimPinnedList() {
    var modal = document.getElementById('slim-pinned-modal');
    if (modal) modal.classList.remove('open');
  }

  function renderSlimPinnedList() {
    var body = document.getElementById('slim-pinned-body');
    if (!body) return;
    var entries = slimPinnedEntries();
    body.textContent = '';
    if (!entries.length) {
      var empty = document.createElement('div');
      empty.className = 'tile-empty';
      empty.textContent = 'Nothing pinned. Pin context all agents should read first.';
      body.appendChild(empty);
      return;
    }
    entries.forEach(function(entry) {
      var card = document.createElement('div');
      card.className = 'pinned-row';

      var top = document.createElement('div');
      top.className = 'pinned-row-top';
      var titleEl = document.createElement('span');
      titleEl.className = 'pinned-row-title';
      titleEl.textContent = entry.title || '(untitled)';
      titleEl.title = entry.title || '';
      top.appendChild(titleEl);
      var chip = document.createElement('span');
      chip.className = 'tile-chip ' + pinLevelChipClass(entry.level);
      chip.textContent = entry.level || 'info';
      top.appendChild(chip);
      card.appendChild(top);

      var preview = document.createElement('div');
      preview.className = 'pinned-row-preview';
      var text = String(entry.content || '');
      preview.textContent = text.length > 220 ? text.slice(0, 220) + '…' : text;
      card.appendChild(preview);

      var actions = document.createElement('div');
      actions.className = 'pinned-row-actions';
      var editBtn = document.createElement('button');
      editBtn.className = 'btn-secondary';
      editBtn.type = 'button';
      editBtn.textContent = 'Edit';
      editBtn.addEventListener('click', function() { openSlimPinEditor(entry); });
      var unpinBtn = document.createElement('button');
      unpinBtn.className = 'btn-secondary pinned-row-unpin';
      unpinBtn.type = 'button';
      unpinBtn.textContent = 'Unpin';
      unpinBtn.addEventListener('click', function() { removeSlimPin(entry.title); });
      actions.appendChild(editBtn);
      actions.appendChild(unpinBtn);
      card.appendChild(actions);

      body.appendChild(card);
    });
  }

  async function removeSlimPin(title) {
    if (!title) return;
    if (!confirm('Unpin "' + title + '"?')) return;
    try {
      var res = await fetch('/api/pinned/remove', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title }),
      });
      if (!res.ok) { var d = await res.json().catch(function() { return {}; }); throw new Error(d.error || ('HTTP ' + res.status)); }
      // Optimistically drop it from the cached snapshot so the list + tile update
      // before the next poll, then reconcile.
      if (lastStatusData && Array.isArray(lastStatusData.pinned)) {
        lastStatusData.pinned = lastStatusData.pinned.filter(function(e) { return e.title !== title; });
      }
      renderSlimPinnedList();
      scheduleStatusRefresh(400);
    } catch (e) {
      alert('Unpin failed: ' + (e && e.message ? e.message : e));
    }
  }

  bindModalClose('slim-pinned-modal', 'slim-pinned-close');
  bindModalClose('slim-pin-edit-modal', 'slim-pin-edit-close');
  (function bindPinnedUi() {
    var pinBtn = document.getElementById('slim-pin-btn');
    if (pinBtn) pinBtn.addEventListener('click', function() { openSlimPinEditor(null); });
    var addBtn = document.getElementById('slim-pinned-add');
    if (addBtn) addBtn.addEventListener('click', function() { openSlimPinEditor(null); });
    var tileChip = document.getElementById('slim-tile-pin-chip');
    if (tileChip) tileChip.addEventListener('click', function(ev) { ev.stopPropagation(); openSlimPinEditor(null); });
    var cancel = document.getElementById('slim-pin-cancel');
    if (cancel) cancel.addEventListener('click', closeSlimPinEditor);
    var submit = document.getElementById('slim-pin-submit');
    if (submit) submit.addEventListener('click', submitSlimPin);
  })();
